repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
madhupolisetti/iossdk
SMSCountryApi/Classes/BaseResponse.h
// // BaseResponse.h // SMSCountryApi // // Created by <NAME> on 03/10/16. // Copyright © 2016 SMS Country. All rights reserved. // #import <Foundation/Foundation.h> @interface BaseResponse: NSObject @property (nonatomic, strong) NSString *apiId; @property (nonatomic, strong) NSString *success; @property (nonatomic, strong) NSString *message; @end
madhupolisetti/iossdk
SMSCountryApi/Classes/SMSCountryApi.h
<gh_stars>0 // // SMSCountryApi.h // Pods // // Created by <NAME> on 03/10/16. // Copyright © 2016 SMS Country. All rights reserved. // #import <Foundation/Foundation.h> #import <RestKit/RestKit.h> @interface SMSCountryApi : NSObject @property (nonatomic, strong) NSString *baseUrl; @property (nonatomic, strong) NSString *authKey; @property (nonatomic, strong) NSString *authToken; @property (nonatomic, strong) RKObjectManager *restKitManager; @property (nonatomic, strong) NSString *apiVersion; @property (nonatomic, strong) NSString *endPointPrefix; -(void)initWithBaseUrl:(NSString *)baseUrl authKey:(NSString *)authKey authToken:(NSString *)authToken; -(void)setRequestMapping:(NSDictionary *)requestDict withClass:(Class)objectClass; -(void)setResponseMapping:(NSDictionary *)responseDict forPathPattern:(NSString *)pathPattern withClass:(Class)objectClass; @end
madhupolisetti/iossdk
Example/Pods/Target Support Files/SMSCountryApi/SMSCountryApi-umbrella.h
#import <UIKit/UIKit.h> FOUNDATION_EXPORT double SMSCountryApiVersionNumber; FOUNDATION_EXPORT const unsigned char SMSCountryApiVersionString[];
madhupolisetti/iossdk
SMSCountryApi/Classes/SendSMSRequest.h
// // SendSMSRequest.h // SMSCountryApi // // Created by <NAME> on 03/10/16. // Copyright © 2016 SMS Country. All rights reserved. // #import <Foundation/Foundation.h> @interface SendSMSRequest: NSObject @property (nonatomic, strong) NSString *text; @property (nonatomic, strong) NSString *number; @property (nonatomic, strong) NSString *senderId; @property (nonatomic, strong) NSString *drNotifyUrl; @property (nonatomic, strong) NSString *drNotifyHttpMethod; @end
H2CO3/yajl-sparkling
yajl_sparkling.c
// // yajl_sparkling.c // YAJL bindings for Sparkling // // Created by <NAME> // on 22/02/2015 // // Licensed under the 2-clause BSD License // #include <assert.h> #include <yajl/yajl_parse.h> #include <yajl/yajl_gen.h> #include <spn/ctx.h> #include <spn/str.h> // the special 'null' value static const SpnValue null_value = { .type = SPN_TYPE_WEAKUSERINFO, .v.p = (void *)&null_value }; // parser state typedef struct StackNode { SpnValue key; // for maps only SpnValue value; struct StackNode *next; } StackNode; typedef struct ParserState { SpnValue root; StackNode *stack; int explicit_null; } ParserState; static ParserState state_init() { return (ParserState) { .root = spn_nilval, .stack = NULL, .explicit_null = 0 }; } static void state_free(ParserState *state) { StackNode *head = state->stack; while (head) { StackNode *next = head->next; spn_value_release(&head->key); spn_value_release(&head->value); free(head); head = next; } } static void state_push(ParserState *state, SpnValue collection) { assert(spn_isarray(&collection) || spn_ishashmap(&collection)); StackNode *node = malloc(sizeof *node); node->key = spn_nilval; node->value = collection; node->next = state->stack; state->stack = node; } static SpnValue state_pop(ParserState *state) { assert(state->stack); StackNode *head = state->stack; StackNode *next = head->next; SpnValue value = head->value; assert(spn_isnil(&head->key)); free(head); state->stack = next; return value; } static void set_value(ParserState *state, SpnValue value) { if (state->stack == NULL) { state->root = value; } else if (spn_isarray(&state->stack->value)) { SpnArray *array = spn_arrayvalue(&state->stack->value); spn_array_push(array, &value); spn_value_release(&value); } else if (spn_ishashmap(&state->stack->value)) { SpnHashMap *hashmap = spn_hashmapvalue(&state->stack->value); assert(spn_isstring(&state->stack->key)); spn_hashmap_set(hashmap, &state->stack->key, &value); spn_value_release(&state->stack->key); spn_value_release(&value); state->stack->key = spn_nilval; } else { assert("cannot add value to non-collection object" == NULL); } } // Parser callbacks static int cb_null(void *ctx) { ParserState *state = ctx; SpnValue nullrepr = state->explicit_null ? null_value : spn_nilval; set_value(ctx, nullrepr); return 1; } static int cb_boolean(void *ctx, int boolval) { set_value(ctx, spn_makebool(boolval)); return 1; } static int cb_integer(void *ctx, long long intval) { set_value(ctx, spn_makeint(intval)); return 1; } static int cb_double(void *ctx, double doubleval) { set_value(ctx, spn_makefloat(doubleval)); return 1; } static int cb_string(void *ctx, const unsigned char *strval, size_t length) { set_value(ctx, spn_makestring_len((const char *)(strval), length)); return 1; } static int cb_start_map(void *ctx) { state_push(ctx, spn_makehashmap()); return 1; } static int cb_map_key(void *ctx, const unsigned char *key, size_t length) { ParserState *state = ctx; assert(state->stack); assert(spn_isnil(&state->stack->key)); state->stack->key = spn_makestring_len((const char *)(key), length); return 1; } static int cb_end_map(void *ctx) { set_value(ctx, state_pop(ctx)); return 1; } static int cb_start_array(void *ctx) { state_push(ctx, spn_makearray()); return 1; } static int cb_end_array(void *ctx) { set_value(ctx, state_pop(ctx)); return 1; } static const yajl_callbacks parser_callbacks = { .yajl_null = cb_null, .yajl_boolean = cb_boolean, .yajl_integer = cb_integer, .yajl_double = cb_double, .yajl_number = NULL, .yajl_string = cb_string, .yajl_start_map = cb_start_map, .yajl_map_key = cb_map_key, .yajl_end_map = cb_end_map, .yajl_start_array = cb_start_array, .yajl_end_array = cb_end_array }; // Helper for obtaining the parser's error message static void error_message_to_spn_context( yajl_handle hndl, SpnContext *ctx, const unsigned char *json, size_t length ) { unsigned char *errmsg = yajl_get_error(hndl, 1, json, length); const void *args[1] = { errmsg }; spn_ctx_runtime_error(ctx, "error parsing JSON: %s", args); yajl_free_error(hndl, errmsg); } static void parser_set_bool_option( yajl_handle parser, yajl_option opt, SpnHashMap *config, const char *name ) { SpnValue optval = spn_hashmap_get_strkey(config, name); if (spn_isbool(&optval)) { yajl_config(parser, opt, spn_boolvalue(&optval)); } } static void state_set_bool_option( int *opt, SpnHashMap *config, const char *name ) { SpnValue optval = spn_hashmap_get_strkey(config, name); if (spn_isbool(&optval)) { *opt = spn_boolvalue(&optval); } } static void config_parser(yajl_handle parser, ParserState *state, SpnValue config_obj) { assert(spn_ishashmap(&config_obj)); SpnHashMap *config = spn_hashmapvalue(&config_obj); // Allow C-style comments in JSON parser_set_bool_option(parser, yajl_allow_comments, config, "comment"); // parse 'null' to the special yajl.null value instead of nil state_set_bool_option(&state->explicit_null, config, "parse_null"); } static int json_parse(SpnValue *ret, int argc, SpnValue argv[], void *ctx) { if (argc < 1 || argc > 2) { spn_ctx_runtime_error(ctx, "expecting 1 or 2 arguments", NULL); return -1; } if (!spn_isstring(&argv[0])) { spn_ctx_runtime_error(ctx, "1st argument must be a string", NULL); return -2; } if (argc >= 2 && !spn_ishashmap(&argv[1])) { spn_ctx_runtime_error(ctx, "2nd argument must be a config object", NULL); return -3; } SpnString *strobj = spn_stringvalue(&argv[0]); const unsigned char *str = (const unsigned char *)(strobj->cstr); size_t length = strobj->len; int rv = 0; ParserState state = state_init(); yajl_handle yajl_hndl = yajl_alloc(&parser_callbacks, NULL, &state); if (argc >= 2) { config_parser(yajl_hndl, &state, argv[1]); } yajl_status status = yajl_parse(yajl_hndl, str, length); if (status != yajl_status_ok) { // handle parse error rv = -4; } status = yajl_complete_parse(yajl_hndl); if (rv == 0 && status != yajl_status_ok) { // garbage after input rv = -5; } if (rv == 0) { *ret = state.root; } else { spn_value_release(&state.root); error_message_to_spn_context(yajl_hndl, ctx, str, length); } yajl_free(yajl_hndl); state_free(&state); return rv; } /* * JSON Generator (serializer) API */ #define RETURN_IF_FAIL(call) \ do { \ if ((call) != yajl_gen_status_ok) { \ const void *args[1] = { #call }; \ spn_ctx_runtime_error(ctx, "YAJL error: %s", args); \ return -1; \ } \ } while (0) static int generate_recursive(yajl_gen gen, SpnValue node, SpnContext *ctx) { switch (spn_valtype(&node)) { case SPN_TTAG_NIL: /* this shouldn't really happen */ RETURN_IF_FAIL(yajl_gen_null(gen)); break; case SPN_TTAG_BOOL: RETURN_IF_FAIL(yajl_gen_bool(gen, spn_boolvalue(&node))); break; case SPN_TTAG_NUMBER: if (spn_isint(&node)) { RETURN_IF_FAIL(yajl_gen_integer(gen, spn_intvalue(&node))); } else { RETURN_IF_FAIL(yajl_gen_double(gen, spn_floatvalue(&node))); } break; case SPN_TTAG_STRING: { SpnString *strobj = spn_stringvalue(&node); const unsigned char *str = (const unsigned char *)(strobj->cstr); size_t length = strobj->len; RETURN_IF_FAIL(yajl_gen_string(gen, str, length)); break; } case SPN_TTAG_ARRAY: { RETURN_IF_FAIL(yajl_gen_array_open(gen)); SpnArray *array = spn_arrayvalue(&node); size_t n = spn_array_count(array); for (size_t i = 0; i < n; i++) { SpnValue elem = spn_array_get(array, i); int error = generate_recursive(gen, elem, ctx); if (error) { return -1; } } RETURN_IF_FAIL(yajl_gen_array_close(gen)); break; } case SPN_TTAG_HASHMAP: { RETURN_IF_FAIL(yajl_gen_map_open(gen)); SpnHashMap *hm = spn_hashmapvalue(&node); SpnValue key, val; size_t cursor = 0; while ((cursor = spn_hashmap_next(hm, cursor, &key, &val)) != 0) { int error; error = generate_recursive(gen, key, ctx); if (error) { return -1; } error = generate_recursive(gen, val, ctx); if (error) { return -1; } } RETURN_IF_FAIL(yajl_gen_map_close(gen)); break; } case SPN_TTAG_USERINFO: if (spn_value_equal(&node, &null_value)) { RETURN_IF_FAIL(yajl_gen_null(gen)); } else { spn_ctx_runtime_error(ctx, "found non-serializable value", NULL); return -1; } break; default: spn_ctx_runtime_error(ctx, "found value of unknown type", NULL); return -1; } return 0; } #undef RETURN_IF_FAIL static void gen_set_bool_option( yajl_gen gen, yajl_gen_option opt, SpnHashMap *config, const char *name ) { SpnValue optval = spn_hashmap_get_strkey(config, name); if (spn_isbool(&optval)) { yajl_gen_config(gen, opt, spn_boolvalue(&optval)); } } static void gen_set_string_option( yajl_gen gen, yajl_gen_option opt, SpnHashMap *config, const char *name ) { SpnValue optval = spn_hashmap_get_strkey(config, name); if (spn_isstring(&optval)) { SpnString *str = spn_stringvalue(&optval); yajl_gen_config(gen, opt, str->cstr); } } static void config_gen(yajl_gen gen, SpnValue config_obj) { assert(spn_ishashmap(&config_obj)); SpnHashMap *config = spn_hashmapvalue(&config_obj); // Generate indented ('beautified') output gen_set_bool_option(gen, yajl_gen_beautify, config, "beautify"); // When beautifying, use this string to indent. gen_set_string_option(gen, yajl_gen_indent_string, config, "indent"); // Escape slash ('/') [for use with HTML] gen_set_bool_option(gen, yajl_gen_escape_solidus, config, "escape_slash"); } static int json_generate(SpnValue *ret, int argc, SpnValue *argv, void *ctx) { if (argc < 1 || argc > 2) { spn_ctx_runtime_error(ctx, "expecting 1 or 2 arguments", NULL); return -1; } if (argc >= 2 && !spn_ishashmap(&argv[1])) { spn_ctx_runtime_error(ctx, "2nd argument must be a config object", NULL); return -2; } yajl_gen gen = yajl_gen_alloc(NULL); if (argc >= 2) { config_gen(gen, argv[1]); } int error = generate_recursive(gen, argv[0], ctx); if (error == 0) { const unsigned char *str; size_t length; yajl_gen_status status = yajl_gen_get_buf(gen, &str, &length); if (status == yajl_gen_status_ok) { *ret = spn_makestring_len((const char *)str, length); } else { spn_ctx_runtime_error(ctx, "error generating JSON string", NULL); error = -3; } } yajl_gen_free(gen); return error; } // The module initializer SPN_LIB_OPEN_FUNC(ctx) { SpnValue module = spn_makehashmap(); SpnHashMap *hm = spn_hashmapvalue(&module); const SpnExtFunc F[] = { { "parse", json_parse }, { "generate", json_generate } }; const SpnExtValue C[] = { { "null", null_value } }; size_t nf = sizeof F / sizeof F[0]; size_t nc = sizeof C / sizeof C[0]; for (size_t i = 0; i < nf; i++) { SpnValue fn = spn_makenativefunc(F[i].name, F[i].fn); spn_hashmap_set_strkey(hm, F[i].name, &fn); spn_value_release(&fn); } for (size_t i = 0; i < nc; i++) { spn_hashmap_set_strkey(hm, C[i].name, &C[i].value); } return module; }
LuaDist-testing/lua-libmodbus
lua-libmodbus.c
/* lua-libmodbus.c - Lua bindings to libmodbus Copyright (c) 2016 <NAME> <<EMAIL>> 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 <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <assert.h> #include <sys/time.h> #include <lua.h> #include <lualib.h> #include <lauxlib.h> #include <modbus/modbus.h> #include "compat.h" /* unique naming for userdata metatables */ #define MODBUS_META_CTX "modbus.ctx" typedef struct { lua_State *L; modbus_t *modbus; size_t max_len; } ctx_t; /** * Push either "true" or "nil, errormessage" * @param L * @param rc rc from modbus_xxxx function call * @param expected what rc was meant to be * @return the count of stack elements pushed */ static int libmodbus_rc_to_nil_error(lua_State *L, int rc, int expected) { if (rc == expected) { lua_pushboolean(L, true); return 1; } else { lua_pushnil(L); // TODO - insert the integer errno code here too? lua_pushstring(L, modbus_strerror(errno)); return 2; } } /** * Returns the runtime linked version of libmodbus as a string * @param L * @return eg "3.0.6" */ static int libmodbus_version(lua_State *L) { char version[16]; snprintf(version, sizeof(version) - 1, "%i.%i.%i", libmodbus_version_major, libmodbus_version_minor, libmodbus_version_micro); lua_pushstring(L, version); return 1; } static int libmodbus_new_rtu(lua_State *L) { const char *device = luaL_checkstring(L, 1); int baud = luaL_optnumber(L, 2, 19200); const char *parityin = luaL_optstring(L, 3, "EVEN"); int databits = luaL_optnumber(L, 4, 8); int stopbits = luaL_optnumber(L, 5, 1); /* just accept baud as is */ /* parity must be one of a few things... */ char parity; switch (parityin[0]) { case 'e': case 'E': parity = 'E'; break; case 'n': case 'N': parity = 'N'; break; case 'o': case 'O': parity = 'O'; break; default: return luaL_argerror(L, 3, "Unrecognised parity"); } ctx_t *ctx = (ctx_t *) lua_newuserdata(L, sizeof(ctx_t)); ctx->modbus = modbus_new_rtu(device, baud, parity, databits, stopbits); ctx->max_len = MODBUS_RTU_MAX_ADU_LENGTH; if (ctx->modbus == NULL) { return luaL_error(L, modbus_strerror(errno)); } ctx->L = L; luaL_getmetatable(L, MODBUS_META_CTX); // Can I put more functions in for rtu here? maybe? lua_setmetatable(L, -2); return 1; } static int libmodbus_new_tcp_pi(lua_State *L) { const char *host = luaL_checkstring(L, 1); const char *service = luaL_checkstring(L, 2); // Do we really need any of this? no callbacks in libmodbus? ctx_t *ctx = (ctx_t *) lua_newuserdata(L, sizeof(ctx_t)); ctx->modbus = modbus_new_tcp_pi(host, service); ctx->max_len = MODBUS_TCP_MAX_ADU_LENGTH; if (ctx->modbus == NULL) { return luaL_error(L, modbus_strerror(errno)); } ctx->L = L; luaL_getmetatable(L, MODBUS_META_CTX); // Can I put more functions in for tcp here? maybe? lua_setmetatable(L, -2); return 1; } static ctx_t * ctx_check(lua_State *L, int i) { return (ctx_t *) luaL_checkudata(L, i, MODBUS_META_CTX); } static int ctx_destroy(lua_State *L) { ctx_t *ctx = ctx_check(L, 1); modbus_close(ctx->modbus); modbus_free(ctx->modbus); /* remove all methods operating on ctx */ lua_newtable(L); lua_setmetatable(L, -2); /* Nothing to return on stack */ return 0; } static int ctx_connect(lua_State *L) { ctx_t *ctx = ctx_check(L, 1); int rc = modbus_connect(ctx->modbus); return libmodbus_rc_to_nil_error(L, rc, 0); } static int ctx_close(lua_State *L) { ctx_t *ctx = ctx_check(L, 1); modbus_close(ctx->modbus); return 0; } static int ctx_set_debug(lua_State *L) { ctx_t *ctx = ctx_check(L, 1); bool opt; if (lua_isnil(L, -1)) { opt = true; } else { opt = lua_toboolean(L, -1); } modbus_set_debug(ctx->modbus, opt); return 0; } static int ctx_set_error_recovery(lua_State *L) { ctx_t *ctx = ctx_check(L, 1); int opt = luaL_checkinteger(L, 2); int opt2 = luaL_optinteger(L, 3, 0); int rc = modbus_set_error_recovery(ctx->modbus, opt | opt2); return libmodbus_rc_to_nil_error(L, rc, 0); } static int ctx_set_byte_timeout(lua_State *L) { ctx_t *ctx = ctx_check(L, 1); int opt = luaL_checkinteger(L, 2); int opt2 = luaL_optinteger(L, 3, 0); #if LIBMODBUS_VERSION_CHECK(3,1,0) modbus_set_byte_timeout(ctx->modbus, opt, opt2); #else struct timeval t = { opt, opt2 }; modbus_set_byte_timeout(ctx->modbus, &t); #endif return 0; } static int ctx_get_byte_timeout(lua_State *L) { ctx_t *ctx = ctx_check(L, 1); uint32_t opt1, opt2; #if LIBMODBUS_VERSION_CHECK(3,1,0) modbus_get_byte_timeout(ctx->modbus, &opt1, &opt2); #else struct timeval t; modbus_get_byte_timeout(ctx->modbus, &t); opt1 = t.tv_sec; opt2 = t.tv_usec; #endif lua_pushnumber(L, opt1); lua_pushnumber(L, opt2); return 2; } static int ctx_set_response_timeout(lua_State *L) { ctx_t *ctx = ctx_check(L, 1); int opt = luaL_checkinteger(L, 2); int opt2 = luaL_optinteger(L, 3, 0); #if LIBMODBUS_VERSION_CHECK(3,1,0) modbus_set_response_timeout(ctx->modbus, opt, opt2); #else struct timeval t = { opt, opt2 }; modbus_set_response_timeout(ctx->modbus, &t); #endif return 0; } static int ctx_get_response_timeout(lua_State *L) { ctx_t *ctx = ctx_check(L, 1); uint32_t opt1, opt2; #if LIBMODBUS_VERSION_CHECK(3,1,0) modbus_get_response_timeout(ctx->modbus, &opt1, &opt2); #else struct timeval t; modbus_get_response_timeout(ctx->modbus, &t); opt1 = t.tv_sec; opt2 = t.tv_usec; #endif lua_pushnumber(L, opt1); lua_pushnumber(L, opt2); return 2; } static int ctx_get_socket(lua_State *L) { ctx_t *ctx = ctx_check(L, 1); lua_pushinteger(L, modbus_get_socket(ctx->modbus)); return 1; } static int ctx_set_socket(lua_State *L) { ctx_t *ctx = ctx_check(L, 1); int newfd = luaL_checknumber(L, 2); modbus_set_socket(ctx->modbus, newfd); return 0; } static int ctx_get_header_length(lua_State *L) { ctx_t *ctx = ctx_check(L, 1); lua_pushinteger(L, modbus_get_header_length(ctx->modbus)); return 1; } static int ctx_set_slave(lua_State *L) { ctx_t *ctx = ctx_check(L, 1); int slave = luaL_checknumber(L, 2); int rc = modbus_set_slave(ctx->modbus, slave); return libmodbus_rc_to_nil_error(L, rc, 0); } static int _ctx_read_bits(lua_State *L, bool input) { ctx_t *ctx = ctx_check(L, 1); int addr = luaL_checknumber(L, 2); int count = luaL_checknumber(L, 3); int rcount = 0; int rc; if (count > MODBUS_MAX_READ_BITS) { return luaL_argerror(L, 3, "requested too many bits"); } uint8_t *buf = malloc(count * sizeof(uint8_t)); assert(buf); if (input) { rc = modbus_read_input_bits(ctx->modbus, addr, count, buf); } else { rc = modbus_read_bits(ctx->modbus, addr, count, buf); } if (rc == count) { lua_newtable(L); /* nota bene, lua style offsets! */ for (int i = 1; i <= rc; i++) { lua_pushnumber(L, i); /* TODO - push number or push bool? what's a better lua api? */ lua_pushnumber(L, buf[i-1]); lua_settable(L, -3); } rcount = 1; } else { rcount = libmodbus_rc_to_nil_error(L, rc, count); } free(buf); return rcount; } static int ctx_read_input_bits(lua_State *L) { return _ctx_read_bits(L, true); } static int ctx_read_bits(lua_State *L) { return _ctx_read_bits(L, false); } static int _ctx_read_regs(lua_State *L, bool input) { ctx_t *ctx = ctx_check(L, 1); int addr = luaL_checknumber(L, 2); int count = luaL_checknumber(L, 3); int rcount = 0; int rc; if (count > MODBUS_MAX_READ_REGISTERS) { return luaL_argerror(L, 3, "requested too many registers"); } // better malloc as much space as we need to return data here... uint16_t *buf = malloc(count * sizeof(uint16_t)); assert(buf); if (input) { rc = modbus_read_input_registers(ctx->modbus, addr, count, buf); } else { rc = modbus_read_registers(ctx->modbus, addr, count, buf); } if (rc == count) { lua_newtable(L); /* nota bene, lua style offsets! */ for (int i = 1; i <= rc; i++) { lua_pushnumber(L, i); lua_pushnumber(L, buf[i-1]); lua_settable(L, -3); } rcount = 1; } else { rcount = libmodbus_rc_to_nil_error(L, rc, count); } free(buf); return rcount; } static int ctx_read_input_registers(lua_State *L) { return _ctx_read_regs(L, true); } static int ctx_read_registers(lua_State *L) { return _ctx_read_regs(L, false); } static int ctx_report_slave_id(lua_State *L) { ctx_t *ctx = ctx_check(L, 1); uint8_t *buf = malloc(ctx->max_len); assert(buf); #if LIBMODBUS_VERSION_CHECK(3,1,0) int rc = modbus_report_slave_id(ctx->modbus, ctx->max_len, buf); #else int rc = modbus_report_slave_id(ctx->modbus, buf); #endif if (rc < 0) { return libmodbus_rc_to_nil_error(L, rc, 0); } lua_pushlstring(L, (char *)buf, rc); return 1; } static int ctx_write_bit(lua_State *L) { ctx_t *ctx = ctx_check(L, 1); int addr = luaL_checknumber(L, 2); int val; if (lua_type(L, 3) == LUA_TNUMBER) { val = lua_tonumber(L, 3); } else if (lua_type(L, 3) == LUA_TBOOLEAN) { val = lua_toboolean(L, 3); } else { return luaL_argerror(L, 3, "bit must be numeric or boolean"); } int rc = modbus_write_bit(ctx->modbus, addr, val); return libmodbus_rc_to_nil_error(L, rc, 1); } static int ctx_write_register(lua_State *L) { ctx_t *ctx = ctx_check(L, 1); int addr = luaL_checknumber(L, 2); int val = luaL_checknumber(L, 3); int rc = modbus_write_register(ctx->modbus, addr, val); return libmodbus_rc_to_nil_error(L, rc, 1); } static int ctx_write_bits(lua_State *L) { ctx_t *ctx = ctx_check(L, 1); int addr = luaL_checknumber(L, 2); int rc; int rcount; /* * TODO - could allow just a series of arguments too? easier for * smaller sets?"?) */ luaL_checktype(L, 3, LUA_TTABLE); /* array style table only! */ int count = lua_objlen(L, 3); if (count > MODBUS_MAX_WRITE_BITS) { return luaL_argerror(L, 3, "requested too many bits"); } /* Convert table to uint8_t array */ uint8_t *buf = malloc(count * sizeof(uint8_t)); assert(buf); for (int i = 1; i <= count; i++) { bool ok = false; lua_rawgeti(L, 3, i); if (lua_type(L, -1) == LUA_TNUMBER) { buf[i-1] = lua_tonumber(L, -1); ok = true; } if (lua_type(L, -1) == LUA_TBOOLEAN) { buf[i-1] = lua_toboolean(L, -1); ok = true; } if (ok) { lua_pop(L, 1); } else { free(buf); return luaL_argerror(L, 3, "table values must be numeric or bool"); } } rc = modbus_write_bits(ctx->modbus, addr, count, buf); if (rc == count) { rcount = 1; lua_pushboolean(L, true); } else { rcount = libmodbus_rc_to_nil_error(L, rc, count); } free(buf); return rcount; } static int ctx_write_registers(lua_State *L) { ctx_t *ctx = ctx_check(L, 1); int addr = luaL_checknumber(L, 2); int rc; int rcount; /* * TODO - could allow just a series of arguments too? easier for * smaller sets? (more compatible with "write_register"?) */ luaL_checktype(L, 3, LUA_TTABLE); /* array style table only! */ int count = lua_objlen(L, 3); if (count > MODBUS_MAX_WRITE_REGISTERS) { return luaL_argerror(L, 3, "requested too many registers"); } /* Convert table to uint16_t array */ uint16_t *buf = malloc(count * sizeof(uint16_t)); assert(buf); for (int i = 1; i <= count; i++) { lua_rawgeti(L, 3, i); /* user beware! we're not range checking your values */ if (lua_type(L, -1) != LUA_TNUMBER) { free(buf); return luaL_argerror(L, 3, "table values must be numeric yo"); } buf[i-1] = lua_tonumber(L, -1); lua_pop(L, 1); } rc = modbus_write_registers(ctx->modbus, addr, count, buf); if (rc == count) { rcount = 1; lua_pushboolean(L, true); } else { rcount = libmodbus_rc_to_nil_error(L, rc, count); } free(buf); return rcount; } static int ctx_send_raw_request(lua_State *L) { ctx_t *ctx = ctx_check(L, 1); int rc; int rcount; int count = lua_objlen(L, 2); luaL_checktype(L, 2, LUA_TTABLE); /* array style table only! */ /* Convert table to uint8_t array */ uint8_t *buf = malloc(lua_objlen(L, 2) * sizeof(uint8_t)); assert(buf); for (int i = 1; i <= count; i++) { lua_rawgeti(L, 2, i); /* user beware! we're not range checking your values */ if (lua_type(L, -1) != LUA_TNUMBER) { free(buf); return luaL_argerror(L, 2, "table values must be numeric"); } buf[i-1] = lua_tonumber(L, -1); lua_pop(L, 1); }; rc = modbus_send_raw_request(ctx->modbus, buf, count); if (rc < 0) { lua_pushnil(L); lua_pushstring(L, modbus_strerror(errno)); rcount = 2; } else { // wait lua_pushboolean(L, true); rcount = 1; } long wait = lua_tonumber(L,3); if (wait > 0) { static struct timeval tim; tim.tv_sec = 0; tim.tv_usec = wait; if (select(0, NULL, NULL, NULL, &tim) < 0) { lua_pushnil(L); return 2; }; } free(buf); return rcount; } static int ctx_tcp_pi_listen(lua_State *L) { ctx_t *ctx = ctx_check(L, 1); int conns = luaL_optinteger(L, 2, 1); int sock = modbus_tcp_pi_listen(ctx->modbus, conns); if (sock == -1) { return libmodbus_rc_to_nil_error(L, 0, 1); } lua_pushnumber(L, sock); return 1; } static int ctx_tcp_pi_accept(lua_State *L) { ctx_t *ctx = ctx_check(L, 1); int sock = luaL_checknumber(L, 2); sock = modbus_tcp_pi_accept(ctx->modbus, &sock); if (sock == -1) { return libmodbus_rc_to_nil_error(L, 0, 1); } lua_pushnumber(L, sock); return 1; } static int ctx_receive(lua_State *L) { ctx_t *ctx = ctx_check(L, 1); int rcount; uint8_t *req = malloc(ctx->max_len); int rc = modbus_receive(ctx->modbus, req); if (rc > 0) { lua_pushnumber(L, rc); lua_pushlstring(L, (char *)req, rc); rcount = 2; } else if (rc == 0) { printf("Special case for rc = 0, can't remember\n"); rcount = 0; } else { rcount = libmodbus_rc_to_nil_error(L, rc, 0); } return rcount; } static int ctx_reply(lua_State *L) { ctx_t *ctx = ctx_check(L, 1); size_t req_len; const char *req = luaL_checklstring(L, 2, &req_len); luaL_checktype(L, 3, LUA_TTABLE); // FIXME - oh boy, probably need a whole lot of wrappers on the mappings? //modbus_reply(ctx->modbus, (uint8_t*)req, req_len, mapping); (void)ctx; (void)req; return luaL_error(L, "reply is simply unimplemented my friend!"); } static int ctx_reply_exception(lua_State *L) { ctx_t *ctx = ctx_check(L, 1); const char *req = luaL_checklstring(L, 2, NULL); int exception = luaL_checknumber(L, 3); int rc = modbus_reply_exception(ctx->modbus, (uint8_t*)req, exception); if (rc == -1) { return libmodbus_rc_to_nil_error(L, 0, 1); } else { return libmodbus_rc_to_nil_error(L, rc, rc); } } struct definei { const char* name; int value; }; struct defines { const char* name; const char* value; }; static const struct definei D[] = { {"RTU_RS232", MODBUS_RTU_RS232}, {"RTU_RS485", MODBUS_RTU_RS485}, {"TCP_SLAVE", MODBUS_TCP_SLAVE}, {"BROADCAST_ADDRESS", MODBUS_BROADCAST_ADDRESS}, {"ERROR_RECOVERY_NONE", MODBUS_ERROR_RECOVERY_NONE}, {"ERROR_RECOVERY_LINK", MODBUS_ERROR_RECOVERY_LINK}, {"ERROR_RECOVERY_PROTOCOL", MODBUS_ERROR_RECOVERY_PROTOCOL}, {"EXCEPTION_ILLEGAL_FUNCTION", MODBUS_EXCEPTION_ILLEGAL_FUNCTION}, {"EXCEPTION_ILLEGAL_DATA_ADDRESS", MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS}, {"EXCEPTION_ILLEGAL_DATA_VALUE", MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE}, {"EXCEPTION_SLAVE_OR_SERVER_FAILURE", MODBUS_EXCEPTION_SLAVE_OR_SERVER_FAILURE}, {"EXCEPTION_ACKNOWLEDGE", MODBUS_EXCEPTION_ACKNOWLEDGE}, {"EXCEPTION_SLAVE_OR_SERVER_BUSY", MODBUS_EXCEPTION_SLAVE_OR_SERVER_BUSY}, {"EXCEPTION_NEGATIVE_ACKNOWLEDGE", MODBUS_EXCEPTION_NEGATIVE_ACKNOWLEDGE}, {"EXCEPTION_MEMORY_PARITY", MODBUS_EXCEPTION_MEMORY_PARITY}, {"EXCEPTION_NOT_DEFINED", MODBUS_EXCEPTION_NOT_DEFINED}, {"EXCEPTION_GATEWAY_PATH", MODBUS_EXCEPTION_GATEWAY_PATH}, {"EXCEPTION_GATEWAY_TARGET", MODBUS_EXCEPTION_GATEWAY_TARGET}, {NULL, 0} }; static const struct defines S[] = { {"VERSION_STRING", LIBMODBUS_VERSION_STRING}, {NULL, NULL} }; static void modbus_register_defs(lua_State *L, const struct definei *D, const struct defines *S) { while (D->name != NULL) { lua_pushinteger(L, D->value); lua_setfield(L, -2, D->name); D++; } while (S->name != NULL) { lua_pushstring(L, S->value); lua_setfield(L, -2, S->name); S++; } } static const struct luaL_Reg R[] = { {"new_rtu", libmodbus_new_rtu}, {"new_tcp_pi", libmodbus_new_tcp_pi}, {"version", libmodbus_version}, {NULL, NULL} }; static const struct luaL_Reg ctx_M[] = { {"connect", ctx_connect}, {"close", ctx_close}, {"destroy", ctx_destroy}, {"get_socket", ctx_get_socket}, {"get_byte_timeout", ctx_get_byte_timeout}, {"get_header_length", ctx_get_header_length}, {"get_response_timeout",ctx_get_response_timeout}, {"read_bits", ctx_read_bits}, {"read_input_bits", ctx_read_input_bits}, {"read_input_registers",ctx_read_input_registers}, {"read_registers", ctx_read_registers}, {"report_slave_id", ctx_report_slave_id}, {"set_debug", ctx_set_debug}, {"set_byte_timeout", ctx_set_byte_timeout}, {"set_error_recovery", ctx_set_error_recovery}, {"set_response_timeout",ctx_set_response_timeout}, {"set_slave", ctx_set_slave}, {"set_socket", ctx_set_socket}, {"write_bit", ctx_write_bit}, {"write_bits", ctx_write_bits}, {"write_register", ctx_write_register}, {"write_registers", ctx_write_registers}, {"send_raw_request", ctx_send_raw_request}, {"__gc", ctx_destroy}, // FIXME - should really add these funcs only to contexts with tcp_pi! {"tcp_pi_listen", ctx_tcp_pi_listen}, {"tcp_pi_accept", ctx_tcp_pi_accept}, {"receive", ctx_receive}, {"reply", ctx_reply}, /* Totally busted */ {"reply_exception", ctx_reply_exception}, {NULL, NULL} }; int luaopen_libmodbus(lua_State *L) { #ifdef LUA_ENVIRONINDEX /* set private environment for this module */ lua_newtable(L); lua_replace(L, LUA_ENVIRONINDEX); #endif /* metatable.__index = metatable */ luaL_newmetatable(L, MODBUS_META_CTX); lua_pushvalue(L, -1); lua_setfield(L, -2, "__index"); luaL_setfuncs(L, ctx_M, 0); luaL_newlib(L, R); modbus_register_defs(L, D, S); return 1; }
LuaDist-testing/lua-libmodbus
compat.h
<reponame>LuaDist-testing/lua-libmodbus<filename>compat.h #if LUA_VERSION_NUM < 502 # define luaL_newlib(L,l) (lua_newtable(L), luaL_register(L,NULL,l)) # define luaL_setfuncs(L,l,n) (assert(n==0), luaL_register(L,NULL,l)) #endif
EwanMcA/GameEngine
BlueMarble/src/BlueMarble/entryPoint.h
<reponame>EwanMcA/GameEngine #pragma once #ifdef BM_PLATFORM_WINDOWS extern BlueMarble::Application* BlueMarble::CreateApplication(); int main(int argc, char** argv) { BlueMarble::Log::Init(); BM_CORE_WARN("Init Log"); BM_INFO("Init Log"); auto app = BlueMarble::CreateApplication(); app->Run(); delete app; } #endif // BM_PLATFORM_WINDOWS
EwanMcA/GameEngine
BlueMarble/src/BlueMarble.h
#pragma once // For use by BlueMarble Applications #include "BlueMarble/application.h" #include "BlueMarble/layer.h" #include "BlueMarble/Log.h" #include "BlueMarble/ecs.h" #include "BlueMarble/component.h" #include "BlueMarble/Core/timeStep.h" #include "BlueMarble/input.h" #include "BlueMarble/keyCodes.h" #include "BlueMarble/mouseCodes.h" #include "BlueMarble/imgui/imguilayer.h" // Renderer ------------------------------ #include "BlueMarble/Renderer/renderer.h" #include "BlueMarble/Renderer/renderCommand.h" #include "BlueMarble/Renderer/buffer.h" #include "BlueMarble/Renderer/shader.h" #include "BlueMarble/Renderer/texture.h" #include "BlueMarble/Renderer/vertexArray.h" #include "BlueMarble/Renderer/camera.h" // Objects ------------------------------- #include "BlueMarble/terrain.h" // Entry Point --------------------------- // TODO: Have to include this manually at the moment //#include "BlueMarble/entryPoint.h"
EwanMcA/GameEngine
Sandbox/src/systems/PlayerInputSystem.h
<reponame>EwanMcA/GameEngine #pragma once #include <BlueMarble.h> #include "components/components.h" using BlueMarble::Entity; using BlueMarble::Ref; class PlayerInputSystem : public BlueMarble::System { public: PlayerInputSystem(std::shared_ptr<BlueMarble::GameCamera> camera) : oCamera(camera) {} virtual ~PlayerInputSystem() = default; virtual void OnUpdate(BlueMarble::TimeStep ts, std::vector<Ref<Entity>>& entities) { bool leftClick = BlueMarble::Input::IsMouseButtonPressed(0); bool rightClick = BlueMarble::Input::IsMouseButtonPressed(1); glm::vec3 mousePosition = oCamera->GetWorldCoords(BlueMarble::Input::GetNormMouseX(), BlueMarble::Input::GetNormMouseY(), BlueMarble::Input::GetNormMouseZ()); for (BlueMarble::Ref<BlueMarble::Entity> entity : entities) { if (entity->HasComponent<PlayerInputComponent>()) { auto pInputComp = entity->GetComponent<PlayerInputComponent>(); pInputComp->leftClick = leftClick; pInputComp->rightClick = rightClick; pInputComp->mousePosition = mousePosition; } } } bool CanPlace(glm::vec3& position); private: std::shared_ptr<BlueMarble::GameCamera> oCamera; };
EwanMcA/GameEngine
BlueMarble/src/Platform/OpenGL/glError.h
<filename>BlueMarble/src/Platform/OpenGL/glError.h #pragma once #include <glad/glad.h> #include <BlueMarble/log.h> #define GL_CALL(fn) do { BlueMarble::GLClearError(); \ fn;\ BM_CORE_ASSERT(BlueMarble::GLLogCall(#fn, __FILE__, __LINE__), "OpenGL Error: ");\ } while (0) namespace BlueMarble { inline static void GLClearError() { while (glGetError() != GL_NO_ERROR); } inline static bool GLLogCall(const char* function, const char* file, int line) { while (GLenum error = glGetError()) { BM_CORE_ERROR("({0}): {1} {2}: {3}", error, function, file, line); return false; } return true; } }
EwanMcA/GameEngine
BlueMarble/src/BlueMarble/input.h
<reponame>EwanMcA/GameEngine #pragma once #include "BlueMarble/core.h" #include "BlueMarble/Renderer/camera.h" namespace BlueMarble { class Input { public: inline static bool IsKeyPressed(int keycode) { return cInstance->IsKeyPressedImpl(keycode); } inline static bool IsMouseButtonPressed(int button) { return cInstance->IsMouseButtonPressedImpl(button); } inline static std::pair<float, float> GetMousePosition() { return cInstance->GetMousePositionImpl(); } inline static float GetMouseX() { return cInstance->GetMouseXImpl(); } inline static float GetMouseY() { return cInstance->GetMouseYImpl(); } inline static float GetMouseZ() { return cInstance->GetMouseZImpl(); } inline static std::pair<float, float> GetNormMousePosition() { return cInstance->GetNormMousePositionImpl(); } inline static float GetNormMouseX() { return cInstance->GetNormMouseXImpl(); } inline static float GetNormMouseY() { return cInstance->GetNormMouseYImpl(); } inline static float GetNormMouseZ() { return cInstance->GetNormMouseZImpl(); } protected: virtual bool IsKeyPressedImpl(int keycode) = 0; virtual bool IsMouseButtonPressedImpl(int button) = 0; virtual std::pair<float, float> GetMousePositionImpl() = 0; virtual float GetMouseXImpl() = 0; virtual float GetMouseYImpl() = 0; virtual float GetMouseZImpl() = 0; virtual std::pair<float, float> GetNormMousePositionImpl() = 0; virtual float GetNormMouseXImpl() = 0; virtual float GetNormMouseYImpl() = 0; virtual float GetNormMouseZImpl() = 0; private: static Input* cInstance; }; }
EwanMcA/GameEngine
BlueMarble/src/BlueMarble/Events/keyEvent.h
#pragma once #include "event.h" namespace BlueMarble { class KeyEvent : public Event { public: inline int GetKeyCode() const { return m_KeyCode; } virtual int GetCategoryFlags() const override { return (EventCategoryKeyboard | EventCategoryInput); } protected: KeyEvent(int keycode) : m_KeyCode(keycode) {} int m_KeyCode; }; class KeyPressEvent : public KeyEvent { public: KeyPressEvent(int keycode, int repeatCount) : KeyEvent(keycode), m_RepeatCount(repeatCount) {} inline int GetRepeatCount() const { return m_RepeatCount; } std::string ToString() const override { std::stringstream ss; ss << "KeyPressEvent: " << m_KeyCode << " (" << m_RepeatCount << " repeats)"; return ss.str(); } static EventType GetStaticType() { return EventType::KeyPress; } virtual EventType GetEventType() const override { return GetStaticType(); } virtual const char* GetName() const override { return "KeyPress"; } private: int m_RepeatCount; }; class KeyReleaseEvent : public KeyEvent { public: KeyReleaseEvent(int keycode) : KeyEvent(keycode) {} std::string ToString() const override { std::stringstream ss; ss << "KeyReleaseEvent: " << m_KeyCode; return ss.str(); } static EventType GetStaticType() { return EventType::KeyRelease; } virtual EventType GetEventType() const override { return GetStaticType(); } virtual const char* GetName() const override { return "KeyRelease"; } }; class KeyTypeEvent : public KeyEvent { public: KeyTypeEvent(int keycode) : KeyEvent(keycode) {} std::string ToString() const override { std::stringstream ss; ss << "KeyTypeEvent: " << m_KeyCode; return ss.str(); } static EventType GetStaticType() { return EventType::KeyType; } virtual EventType GetEventType() const override { return GetStaticType(); } virtual const char* GetName() const override { return "KeyType"; } }; }
EwanMcA/GameEngine
BlueMarble/src/BlueMarble/Renderer/renderer.h
#pragma once #include "camera.h" #include "material.h" #include "renderCommand.h" #include "shader.h" #include "texture.h" namespace BlueMarble { class Renderer { public: static void Init(); //TODO take in the rest of the scene parameters static void BeginScene(Camera& camera); static void EndScene(); static void Submit(const Ref<Material>& material, const Ref<VertexArray>& vertexArray, const glm::mat4& transform = glm::mat4(1.0f)); inline static RendererAPI::API GetAPI() { return RendererAPI::GetAPI(); } private: struct SceneData { glm::mat4 ProjectionViewMatrix; }; static SceneData* cSceneData; }; } // Namespace BlueMarble
EwanMcA/GameEngine
BlueMarble/src/BlueMarble/core.h
#pragma once #include <memory> #ifdef BM_PLATFORM_WINDOWS #ifdef BM_BUILD_DLL #define BLUEMARBLE_API __declspec(dllexport) #endif #else #error BlueMarble currently only supports Windows. #endif #ifdef BM_DEBUG #define BM_ENABLE_ASSERTS #endif #ifdef BM_ENABLE_ASSERTS #define BM_ASSERT(x, ...) { if(!(x)) { BM_ERROR("Assertion Failed: {0}", __VA_ARGS__); __debugbreak(); } } #define BM_CORE_ASSERT(x, ...) { if(!(x)) { BM_CORE_ERROR("Assertion Failed: {0}", __VA_ARGS__); __debugbreak(); } } #else #define BM_ASSERT(x, ...) #define BM_CORE_ASSERT(x, ...) #endif #define BIT(x) (1 << x) #define BM_BIND_EVENT_FN(fn) std::bind(&fn, this, std::placeholders::_1) namespace BlueMarble { template<typename T> using Scope = std::unique_ptr<T>; template<typename T> using Ref = std::shared_ptr<T>; }
EwanMcA/GameEngine
Sandbox/src/systems/renderSystem.h
#pragma once #include <BlueMarble.h> using BlueMarble::Entity; using BlueMarble::Ref; class RenderSystem : public BlueMarble::System { public: RenderSystem(std::shared_ptr<BlueMarble::GameCamera> camera) : oCamera(camera) {} virtual ~RenderSystem() = default; virtual void OnUpdate(BlueMarble::TimeStep ts, std::vector<Ref<Entity>>& entities) override; private: std::shared_ptr<BlueMarble::GameCamera> oCamera; };
EwanMcA/GameEngine
BlueMarble/src/Platform/Windows/windowsInput.h
<reponame>EwanMcA/GameEngine #pragma once #include "BlueMarble/application.h" #include "BlueMarble/input.h" namespace BlueMarble { class WindowsInput : public Input { protected: virtual bool IsKeyPressedImpl(int keycode) override; virtual bool IsMouseButtonPressedImpl(int button) override; virtual std::pair<float, float> GetMousePositionImpl() override; virtual float GetMouseXImpl() override; virtual float GetMouseYImpl() override; virtual float GetMouseZImpl() override; virtual std::pair<float, float> GetNormMousePositionImpl() override; virtual float GetNormMouseXImpl() override { return GetMouseXImpl() / (Application::Get().GetWindow().GetWidth() * 0.5f) - 1.0f; } virtual float GetNormMouseYImpl() override { return GetMouseYImpl() / (Application::Get().GetWindow().GetHeight() * 0.5f) - 1.0f; } virtual float GetNormMouseZImpl() override { return 2 * GetMouseZImpl() - 1.0f; } }; }
EwanMcA/GameEngine
BlueMarble/src/BlueMarble/application.h
#pragma once #include "core.h" #include "Window.h" #include "BlueMarble/layerStack.h" #include "BlueMarble/Events/event.h" #include "BlueMarble/Events/applicationEvent.h" #include "BlueMarble/Core/timeStep.h" #include "BlueMarble/ImGui/imGuiLayer.h" namespace BlueMarble { class Application { public: Application(); virtual ~Application() = default; void Run(); void OnEvent(Event& e); void PushLayer(Layer* layer); void PushOverlay(Layer* overlay); void PopLayer(Layer* layer); void PopOverlay(Layer* overlay); inline Window& GetWindow() { return *oWindow; } inline static Application& Get() { return *cInstance; } private: bool OnWindowClose(WindowCloseEvent& e); private: std::shared_ptr<Window> oWindow; ImGuiLayer* oImGuiLayer; bool oRunning = true; LayerStack oLayerStack; float oLastFrameTime = 0.0f; private: static Application* cInstance; }; // To be defined in CLIENT Application* CreateApplication(); }
EwanMcA/GameEngine
Sandbox/src/components/components.h
#pragma once #include <BlueMarble.h> class MapPositionComponent : public BlueMarble::Component { public: MapPositionComponent(int x, int y) : oX(x), oY(y) {} int oX, oY; }; class PopulationComponent : public BlueMarble::Component { public: PopulationComponent(uint32_t population = 0) : oPopulation(population) {} uint32_t oPopulation; bool oDirty; }; // Size of a rectangular or circular structure on map class SizeComponent : public BlueMarble::Component { public: SizeComponent(uint32_t x, uint32_t y, uint32_t r = 0) : oX(x), oY(y), oR(r) {} // Number of vertices in width (or radius) // R = 0 -> rectangular object // R > 0 -> circular object uint32_t oX, oY, oR; }; // Defines player ownership of many entities (not an actual player entity) class PlayerComponent : public BlueMarble::Component { public: PlayerComponent(uint32_t playerID) : oPlayerID(playerID) {} uint32_t oPlayerID; }; class PlayerInputComponent : public BlueMarble::Component { public: PlayerInputComponent() = default; bool leftClick = false; bool rightClick = false; glm::vec3 mousePosition{ 0.0f, 0.0f, 0.0f }; }; class SelectedComponent : public BlueMarble::Component { public: SelectedComponent(bool selected = false) : oSelected(selected) {} bool oSelected = false; }; class PlacingComponent : public BlueMarble::Component { public: PlacingComponent(bool placing = false) : oPlacing(placing) {} bool oPlacing = false; }; class TerritoryComponent : public BlueMarble::Component { public: TerritoryComponent() = default; BlueMarble::TimeStep oTimer; };
EwanMcA/GameEngine
BlueMarble/src/Platform/OpenGL/openGLBuffer.h
#pragma once #include "BlueMarble/Renderer/buffer.h" namespace BlueMarble { class OpenGLVertexBuffer : public VertexBuffer { public: OpenGLVertexBuffer(float* vertices, uint32_t size); virtual ~OpenGLVertexBuffer(); virtual void Bind() const override; virtual void Unbind() const override; virtual const BufferLayout GetLayout() const override { return oLayout; }; virtual void SetLayout(const BufferLayout& layout) override { oLayout = layout; } private: uint32_t oRendererID; BufferLayout oLayout; }; class OpenGLIndexBuffer : public IndexBuffer { public: OpenGLIndexBuffer(uint32_t* indices, uint32_t size); virtual ~OpenGLIndexBuffer(); virtual void Bind() const; virtual void Unbind() const; virtual uint32_t GetCount() const { return oCount; } private: uint32_t oRendererID; uint32_t oCount; }; } // namespace BlueMarble
EwanMcA/GameEngine
BlueMarble/src/Platform/OpenGL/openGLVertexArray.h
#pragma once #include "BlueMarble/Renderer/vertexArray.h" namespace BlueMarble { class OpenGLVertexArray : public VertexArray { public: OpenGLVertexArray(); virtual ~OpenGLVertexArray(); virtual void Bind() const override; virtual void Unbind() const override; virtual void AddVertexBuffer(const Ref<VertexBuffer>& vertexBuffer) override; virtual void SetVertexBuffer(const Ref<VertexBuffer>& vertexBuffer) override; virtual void SetIndexBuffer(const Ref<IndexBuffer>& indexBuffer) override; virtual const std::vector<Ref<VertexBuffer>>& GetVertexBuffers() const override { return oVertexBuffers; } virtual const Ref<IndexBuffer>& GetIndexBuffer() const override { return oIndexBuffer; } private: std::vector<Ref<VertexBuffer>> oVertexBuffers; Ref<IndexBuffer> oIndexBuffer; uint32_t oRendererID; }; } // namespace BlueMarble
EwanMcA/GameEngine
BlueMarble/src/BlueMarble/Core/timeStep.h
<gh_stars>1-10 #pragma once namespace BlueMarble { class TimeStep { public: TimeStep(float time = 0.0f) : oTime(time) {} operator float() const { return oTime; } float GetSeconds() const { return oTime; } float GetMilliseconds() const { return oTime * 1000.0f; } TimeStep operator +(TimeStep ts) { return TimeStep(oTime + ts.GetSeconds()); } TimeStep& operator +=(TimeStep& ts) { oTime += ts.GetSeconds(); return *this; } private: float oTime; }; } // namespace BlueMarble
EwanMcA/GameEngine
BlueMarble/src/BlueMarble/mouseCodes.h
#pragma once // From glfw3.h #define BM_MOUSE_BUTTON_1 0 #define BM_MOUSE_BUTTON_2 1 #define BM_MOUSE_BUTTON_3 2 #define BM_MOUSE_BUTTON_4 3 #define BM_MOUSE_BUTTON_5 4 #define BM_MOUSE_BUTTON_6 5 #define BM_MOUSE_BUTTON_7 6 #define BM_MOUSE_BUTTON_8 7 #define BM_MOUSE_BUTTON_LAST BM_MOUSE_BUTTON_8 #define BM_MOUSE_BUTTON_LEFT BM_MOUSE_BUTTON_1 #define BM_MOUSE_BUTTON_RIGHT BM_MOUSE_BUTTON_2 #define BM_MOUSE_BUTTON_MIDDLE BM_MOUSE_BUTTON_3
EwanMcA/GameEngine
BlueMarble/src/Platform/OpenGL/openGLMaterial.h
#pragma once #include <map> #include "BlueMarble/Renderer/material.h" #include "Platform/OpenGL/openGLShader.h" #include "Platform/OpenGL/openGLTexture.h" namespace BlueMarble { class OpenGLMaterial : public Material { public: OpenGLMaterial(Ref<OpenGLShader> shader) : oShader(shader) {} virtual ~OpenGLMaterial() = default; virtual void UploadUniforms() override; virtual void UploadTextures() override; virtual void SetBool(const std::string& name, const bool value) override { oBools[name] = value; } virtual void SetInt(const std::string& name, const int value) override { oInts[name] = value; } virtual void SetFloat(const std::string& name, const float value) override { oFloats[name] = value; } virtual void SetFloat2(const std::string& name, const glm::vec2& values) override { oFloat2s[name] = values; } virtual void SetFloat3(const std::string& name, const glm::vec3& values) override { oFloat3s[name] = values; } virtual void SetFloat4(const std::string& name, const glm::vec4& values) override { oFloat4s[name] = values; } virtual void SetMat3(const std::string& name, const glm::mat3& matrix) override { oMat3s[name] = matrix; } virtual void SetMat4(const std::string& name, const glm::mat4& matrix) override { oMat4s[name] = matrix; } virtual void AddTexture2D(Ref<Texture2D> texture) override { oTextures.push_back(std::dynamic_pointer_cast<OpenGLTexture2D>(texture)); } virtual const bool GetBool(const std::string& name) const override { return oBools.find(name)->second; } virtual const int GetInt(const std::string& name) const override { return oInts.find(name)->second; } virtual const float GetFloat(const std::string& name) const override { return oFloats.find(name)->second; } virtual const glm::vec2& GetFloat2(const std::string& name) const override { return oFloat2s.find(name)->second; } virtual const glm::vec3& GetFloat3(const std::string& name) const override { return oFloat3s.find(name)->second; } virtual const glm::vec4& GetFloat4(const std::string& name) const override { return oFloat4s.find(name)->second; } virtual const glm::mat3& GetMat3(const std::string& name) const override { return oMat3s.find(name)->second; } virtual const glm::mat4& GetMat4(const std::string& name) const override { return oMat4s.find(name)->second; } private: Ref<OpenGLShader> oShader; std::vector<Ref<OpenGLTexture2D>> oTextures; // TODO: Refactor this into map of std::any or std::variant or similar. // Should be able to use templates for the above methods. std::map<std::string, bool> oBools; std::map<std::string, int> oInts; std::map<std::string, float> oFloats; std::map<std::string, glm::vec2> oFloat2s; std::map<std::string, glm::vec3> oFloat3s; std::map<std::string, glm::vec4> oFloat4s; std::map<std::string, glm::mat3> oMat3s; std::map<std::string, glm::mat4> oMat4s; }; }
EwanMcA/GameEngine
BlueMarble/src/BlueMarble/ImGui/imGuiLayer.h
#pragma once #include "BlueMarble/layer.h" #include "BlueMarble/Events/applicationEvent.h" #include "BlueMarble/Events/keyEvent.h" #include "BlueMarble/Events/mouseEvent.h" namespace BlueMarble { class ImGuiLayer : public Layer { public: ImGuiLayer(); ~ImGuiLayer(); virtual void OnAttach() override; virtual void OnDetach() override; virtual void OnImGuiRender() override; void Begin(); void End(); private: float oTime = 0.0f; }; }
EwanMcA/GameEngine
BlueMarble/src/BlueMarble/ecs.h
#pragma once #include "Core/timeStep.h" #include "entity.h" #include <vector> namespace BlueMarble { class System { public: System() = default; virtual ~System() = default; virtual void OnUpdate(TimeStep ts, std::vector<Ref<Entity>>& entities) = 0; }; class EntityComponentSystem { public: EntityComponentSystem() {} void AddSystem(System* system); void RemoveSystem(System* system); void Update(TimeStep ts); void AddEntity(Ref<Entity> entity) { oEntities.push_back(entity); } void RemoveEntity(Ref<Entity> entity); private: std::vector<System*> oSystems; std::vector<Ref<Entity>> oEntities; }; }
EwanMcA/GameEngine
BlueMarble/src/BlueMarble/layer.h
<filename>BlueMarble/src/BlueMarble/layer.h #pragma once #include "BlueMarble/core.h" #include "BlueMarble/Events/event.h" #include "BlueMarble/Core/timeStep.h" namespace BlueMarble { class Layer { public: Layer(const std::string& name = "Layer"); virtual ~Layer(); virtual void OnAttach() {} virtual void OnDetach() {} virtual void OnUpdate(TimeStep ts) {} virtual void OnImGuiRender() {} virtual void OnEvent(Event& event) {} inline const std::string& GetName() const { return oDebugName; } protected: std::string oDebugName; }; }
EwanMcA/GameEngine
Sandbox/src/systems/territorySystem.h
#pragma once #include <BlueMarble.h> using BlueMarble::Entity; using BlueMarble::Ref; class TerritorySystem : public BlueMarble::System { public: TerritorySystem(std::shared_ptr<BlueMarble::GameCamera> camera) : oCamera(camera) {} virtual ~TerritorySystem() = default; virtual void OnUpdate(BlueMarble::TimeStep ts, std::vector<Ref<Entity>>& entities) override; int GetRadius(Ref<Entity> entity) const; void Grow(Ref<BlueMarble::Terrain> terrain, int x, int y, int r); private: std::shared_ptr<BlueMarble::GameCamera> oCamera; };
EwanMcA/GameEngine
BlueMarble/src/BlueMarble/component.h
#pragma once #include <atomic> #include <vector> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include "BlueMarble/Renderer/material.h" #include "BlueMarble/Renderer/vertexArray.h" namespace BlueMarble { extern std::atomic<uint32_t> TypeIdCounter; template <typename T> int GetTypeID() { static int uint32_t = ++TypeIdCounter; return uint32_t; } // TODO: Implement shared components, for things like vector_arrays // which are common among many entities. class Component { public: virtual ~Component() = default; }; class TransformComponent : public Component { public: TransformComponent(const glm::mat4& transform) : oTransform(transform) {} TransformComponent(const glm::vec3& position) : oTransform(glm::translate(glm::mat4(1.0f), position)) {} virtual ~TransformComponent() = default; glm::mat4 oTransform; bool oTrackMouse = false; }; class VelocityComponent : public Component { public: virtual ~VelocityComponent() = default; glm::vec3 oVelocity; }; class MeshComponent : public Component { public: virtual ~MeshComponent() = default; std::vector<float[6]> oMesh; }; class VertexArrayComponent : public Component { public: VertexArrayComponent(Ref<BlueMarble::VertexArray> va) : oVA(va) {} virtual ~VertexArrayComponent() = default; Ref<BlueMarble::VertexArray> oVA; }; class MaterialComponent : public Component { public: MaterialComponent(Ref<BlueMarble::Material> material) : oMaterial(material) {} virtual ~MaterialComponent() = default; Ref<Material> oMaterial; }; }
EwanMcA/GameEngine
BlueMarble/src/BlueMarble/Events/applicationEvent.h
#pragma once #include "Event.h" namespace BlueMarble { class WindowResizeEvent : public Event { public: WindowResizeEvent(unsigned int width, unsigned int height) : oWidth(width), oHeight(height) {} inline unsigned int GetWidth() const { return oWidth; } inline unsigned int GetHeight() const { return oHeight; } std::string ToString() const override { std::stringstream ss; ss << "WindowResizeEvent: " << oWidth << ", " << oHeight; return ss.str(); } static EventType GetStaticType() { return EventType::WindowResize; } virtual EventType GetEventType() const override { return GetStaticType(); } virtual const char* GetName() const override { return "WindowResize"; } virtual int GetCategoryFlags() const override { return (EventCategoryApplication); } private: unsigned int oWidth, oHeight; }; class WindowCloseEvent : public Event { public: WindowCloseEvent() {} static EventType GetStaticType() { return EventType::WindowClose; } virtual EventType GetEventType() const override { return GetStaticType(); } virtual const char* GetName() const override { return "WindowClose"; } virtual int GetCategoryFlags() const override { return (EventCategoryApplication); } }; }
EwanMcA/GameEngine
BlueMarble/src/Platform/OpenGL/OpenGLRendererAPI.h
#pragma once #include "BlueMarble/Renderer/RendererAPI.h" namespace BlueMarble { class OpenGLRendererAPI : public RendererAPI { public: virtual void Init() override; virtual void SetClearColor(const glm::vec4& color) override; virtual void Clear() override; virtual void DrawIndexed(const Ref<VertexArray>& vertexArray) override; }; } // namespace BlueMarble
EwanMcA/GameEngine
BlueMarble/src/BlueMarble/Renderer/camera.h
#pragma once #include "BlueMarble/Core/timeStep.h" #include <glm/glm.hpp> namespace BlueMarble { class Camera { public: Camera(glm::mat4 projectionMatrix, glm::mat4 viewMatrix) : oProjectionMatrix(projectionMatrix), oViewMatrix(viewMatrix) { oPVMatrix = oProjectionMatrix * oViewMatrix; } const glm::vec3& GetPosition() const { return oPosition; } void SetPosition(const glm::vec3& position) { oPosition = position; RecalculateViewMatrix(); } const glm::mat4 GetProjectionMatrix() const { return oProjectionMatrix; } const glm::mat4 GetViewMatrix() const { return oViewMatrix; } const glm::mat4 GetViewProjectionMatrix() const { return oPVMatrix; } protected: virtual void RecalculateViewMatrix() = 0; protected: glm::mat4 oProjectionMatrix; glm::mat4 oViewMatrix; glm::mat4 oPVMatrix; glm::vec3 oPosition = { 0.0f, 0.0f, 0.0f }; }; class OrthographicCamera : public Camera { public: // clipping planes -1 near, 1 far OrthographicCamera(float left, float right, float bottom, float top); const float GetRotation() const { return oRotation; } void SetRotation(float rotation) { oRotation = rotation; RecalculateViewMatrix(); } protected: virtual void RecalculateViewMatrix() override; private: float oRotation = 0.0f; }; class PerspectiveCamera : public Camera { public: PerspectiveCamera(float fovy, float aspect, float zNear, float zFar); const glm::vec3 GetRotation() const { return oRotation; } // Params in normalized [-1, 1] coords glm::vec3 GetWorldCoords(float mouseX, float mouseY, float mouseZ) const; void SetRotation(glm::vec3 rotation) { oRotation = rotation; RecalculateViewMatrix(); } protected: virtual void RecalculateViewMatrix() override; private: //TODO Need to do this with quarternions in future glm::vec3 oRotation = { 0.0f, 0.0f, 0.0f }; }; class GameCamera : public PerspectiveCamera { public: GameCamera(float fovy, float aspect, float zNear, float zFar); void Zoom(int change); void Translate(const float x, const float y); protected: virtual void RecalculateViewMatrix() override; private: int oZoom = 50; }; } // namespace BlueMarble
EwanMcA/GameEngine
BlueMarble/src/BlueMarble/keyCodes.h
#pragma once // From glfw3.h #define BM_KEY_SPACE 32 #define BM_KEY_APOSTROPHE 39 /* ' */ #define BM_KEY_COMMA 44 /* , */ #define BM_KEY_MINUS 45 /* - */ #define BM_KEY_PERIOD 46 /* . */ #define BM_KEY_SLASH 47 /* / */ #define BM_KEY_0 48 #define BM_KEY_1 49 #define BM_KEY_2 50 #define BM_KEY_3 51 #define BM_KEY_4 52 #define BM_KEY_5 53 #define BM_KEY_6 54 #define BM_KEY_7 55 #define BM_KEY_8 56 #define BM_KEY_9 57 #define BM_KEY_SEMICOLON 59 /* ; */ #define BM_KEY_EQUAL 61 /* = */ #define BM_KEY_A 65 #define BM_KEY_B 66 #define BM_KEY_C 67 #define BM_KEY_D 68 #define BM_KEY_E 69 #define BM_KEY_F 70 #define BM_KEY_G 71 #define BM_KEY_H 72 #define BM_KEY_I 73 #define BM_KEY_J 74 #define BM_KEY_K 75 #define BM_KEY_L 76 #define BM_KEY_M 77 #define BM_KEY_N 78 #define BM_KEY_O 79 #define BM_KEY_P 80 #define BM_KEY_Q 81 #define BM_KEY_R 82 #define BM_KEY_S 83 #define BM_KEY_T 84 #define BM_KEY_U 85 #define BM_KEY_V 86 #define BM_KEY_W 87 #define BM_KEY_X 88 #define BM_KEY_Y 89 #define BM_KEY_Z 90 #define BM_KEY_LEFT_BRACKET 91 /* [ */ #define BM_KEY_BACKSLASH 92 /* \ */ #define BM_KEY_RIGHT_BRACKET 93 /* ] */ #define BM_KEY_GRAVE_ACCENT 96 /* ` */ #define BM_KEY_WORLD_1 161 /* non-US #1 */ #define BM_KEY_WORLD_2 162 /* non-US #2 */ /* Function keys */ #define BM_KEY_ESCAPE 256 #define BM_KEY_ENTER 257 #define BM_KEY_TAB 258 #define BM_KEY_BACKSPACE 259 #define BM_KEY_INSERT 260 #define BM_KEY_DELETE 261 #define BM_KEY_RIGHT 262 #define BM_KEY_LEFT 263 #define BM_KEY_DOWN 264 #define BM_KEY_UP 265 #define BM_KEY_PAGE_UP 266 #define BM_KEY_PAGE_DOWN 267 #define BM_KEY_HOME 268 #define BM_KEY_END 269 #define BM_KEY_CAPS_LOCK 280 #define BM_KEY_SCROLL_LOCK 281 #define BM_KEY_NUM_LOCK 282 #define BM_KEY_PRINT_SCREEN 283 #define BM_KEY_PAUSE 284 #define BM_KEY_F1 290 #define BM_KEY_F2 291 #define BM_KEY_F3 292 #define BM_KEY_F4 293 #define BM_KEY_F5 294 #define BM_KEY_F6 295 #define BM_KEY_F7 296 #define BM_KEY_F8 297 #define BM_KEY_F9 298 #define BM_KEY_F10 299 #define BM_KEY_F11 300 #define BM_KEY_F12 301 #define BM_KEY_F13 302 #define BM_KEY_F14 303 #define BM_KEY_F15 304 #define BM_KEY_F16 305 #define BM_KEY_F17 306 #define BM_KEY_F18 307 #define BM_KEY_F19 308 #define BM_KEY_F20 309 #define BM_KEY_F21 310 #define BM_KEY_F22 311 #define BM_KEY_F23 312 #define BM_KEY_F24 313 #define BM_KEY_F25 314 #define BM_KEY_KP_0 320 #define BM_KEY_KP_1 321 #define BM_KEY_KP_2 322 #define BM_KEY_KP_3 323 #define BM_KEY_KP_4 324 #define BM_KEY_KP_5 325 #define BM_KEY_KP_6 326 #define BM_KEY_KP_7 327 #define BM_KEY_KP_8 328 #define BM_KEY_KP_9 329 #define BM_KEY_KP_DECIMAL 330 #define BM_KEY_KP_DIVIDE 331 #define BM_KEY_KP_MULTIPLY 332 #define BM_KEY_KP_SUBTRACT 333 #define BM_KEY_KP_ADD 334 #define BM_KEY_KP_ENTER 335 #define BM_KEY_KP_EQUAL 336 #define BM_KEY_LEFT_SHIFT 340 #define BM_KEY_LEFT_CONTROL 341 #define BM_KEY_LEFT_ALT 342 #define BM_KEY_LEFT_SUPER 343 #define BM_KEY_RIGHT_SHIFT 344 #define BM_KEY_RIGHT_CONTROL 345 #define BM_KEY_RIGHT_ALT 346 #define BM_KEY_RIGHT_SUPER 347 #define BM_KEY_MENU 348
EwanMcA/GameEngine
Sandbox/src/gameLayer.h
#pragma once #include <BlueMarble.h> #include "imgui/imgui.h" #include "imgui/misc/cpp/imgui_stdlib.h" #include "glm/gtc/matrix_transform.hpp" #include "glm/gtc/type_ptr.hpp" class GameLayer : public BlueMarble::Layer { public: GameLayer(const uint32_t xCount, const uint32_t yCount, std::shared_ptr<BlueMarble::GameCamera> camera, std::shared_ptr<BlueMarble::EntityComponentSystem> ecs); virtual ~GameLayer() = default; virtual void OnUpdate(BlueMarble::TimeStep ts) override; virtual void OnImGuiRender() override; virtual void OnEvent(BlueMarble::Event& event) override; bool OnMouseScrollEvent(BlueMarble::MouseScrollEvent& event); private: const uint32_t oXCount; const uint32_t oYCount; std::shared_ptr<BlueMarble::GameCamera> oCamera; std::shared_ptr<BlueMarble::EntityComponentSystem> oECS; float oCameraMoveSpeed = 5.0f; };
EwanMcA/GameEngine
Sandbox/src/mapLayer.h
<reponame>EwanMcA/GameEngine<filename>Sandbox/src/mapLayer.h #pragma once #include <BlueMarble.h> class MapLayer : public BlueMarble::Layer { public: enum MODE { PLAYING = 0, EDITING = 1 }; enum DATA_LAYER { HEIGHT = 0, MOISTURE = 1, HEAT = 2 }; enum EDIT_MODE { ADD = 0, SET = 1, SUBTRACT = 2, SMOOTH = 3 }; MapLayer(const uint32_t xCount, const uint32_t yCount, std::shared_ptr<BlueMarble::GameCamera> camera, std::shared_ptr<BlueMarble::EntityComponentSystem> ecs) : Layer("MapLayer"), oXCount{ xCount }, oYCount{ yCount }, oCamera(camera), oECS(ecs) {} virtual ~MapLayer() = default; virtual void OnAttach() override; virtual void OnUpdate(BlueMarble::TimeStep ts) override; virtual void OnImGuiRender() override; virtual void OnEvent(BlueMarble::Event& event) override; void CreateTerrain(); void UpdateTerrain(BlueMarble::TimeStep ts); void RenderEditorUI(); private: const uint32_t oXCount; const uint32_t oYCount; std::shared_ptr<BlueMarble::GameCamera> oCamera; std::shared_ptr<BlueMarble::EntityComponentSystem> oECS; BlueMarble::Ref<BlueMarble::Terrain> oTerrain; std::string oHeightmapFilename; glm::vec4 oTerrainCutoffs{ 0.0f, 0.015f, 0.03f, 0.3f }; float oTerrainHeightScale = 0.5f; float oTerrainModAmount = 1.0f; float oTerrainSetAmount = 0.1f; float oTerrainModRadius = 3.0f; // TODO: Fix up this weird ref situation BlueMarble::Ref<std::vector<float>> oMoisture; BlueMarble::Ref<std::vector<float>> oHeat; BlueMarble::Ref<std::vector<float>> oTerritory; DATA_LAYER oEditLayer{ HEIGHT }; EDIT_MODE oEditMode{ ADD }; MODE oMode{ PLAYING }; };
EwanMcA/GameEngine
Sandbox/src/city.h
<gh_stars>1-10 #pragma once #include <BlueMarble.h> #include "components/components.h" using BlueMarble::Ref; class City : public BlueMarble::Entity { public: City(uint32_t playerID, uint32_t initialPop, glm::vec3& position = glm::vec3(0)) { auto va = BlueMarble::Ref<BlueMarble::VertexArray>(BlueMarble::VertexArray::Create()); // TODO: Scale this the proper way. // TODO: Get a 3D mesh / texture for cities. float scale = 0.25f; std::vector<float> vertices = { scale * -0.5f, scale * 0.5f, 0.0f, 0.0f, 1.0f, scale * -0.5f, scale * -0.5f, 0.0f, 0.0f, 0.0f, scale * 0.5f, scale * -0.5f, 0.0f, 1.0f, 0.0f, scale * 0.5f, scale * 0.5f, 0.0f, 1.0f, 1.0f }; Ref<BlueMarble::VertexBuffer> squareVB; squareVB.reset(BlueMarble::VertexBuffer::Create(vertices.data(), vertices.size() * sizeof(float))); squareVB->SetLayout({ { BlueMarble::ShaderDataType::Float3, "aPosition" }, { BlueMarble::ShaderDataType::Float2, "aTexCoord" } }); va->SetVertexBuffer(squareVB); std::vector<uint32_t> squareIndices = { 0, 1, 3, 3, 1, 2 }; Ref<BlueMarble::IndexBuffer> squareIB; squareIB.reset(BlueMarble::IndexBuffer::Create(squareIndices.data(), squareIndices.size())); va->SetIndexBuffer(squareIB); SetComponent<BlueMarble::VertexArrayComponent>(std::make_shared<BlueMarble::VertexArrayComponent>(va)); BlueMarble::Ref<BlueMarble::Shader> shader = BlueMarble::Ref<BlueMarble::Shader>(BlueMarble::Shader::Create("assets/shaders/basic.glsl")); BlueMarble::Ref<BlueMarble::Material> material = BlueMarble::Ref<BlueMarble::Material>(BlueMarble::Material::Create(shader)); material->AddTexture2D(BlueMarble::Texture2D::Create("assets/textures/village.png")); SetComponent<BlueMarble::MaterialComponent>(std::make_shared<BlueMarble::MaterialComponent>(material)); SetComponent<BlueMarble::TransformComponent>(std::make_shared<BlueMarble::TransformComponent>(position)); SetComponent<PlayerComponent>(std::make_shared<PlayerComponent>(playerID)); SetComponent<SizeComponent>(std::make_shared<SizeComponent>(5, 5)); // starting width & length SetComponent<MapPositionComponent>(std::make_shared<MapPositionComponent>(0, 0)); SetComponent<PopulationComponent>(std::make_shared<PopulationComponent>(initialPop)); } virtual ~City() = default; };
EwanMcA/GameEngine
Sandbox/src/systems/citySystem.h
#pragma once #include <BlueMarble.h> using BlueMarble::Entity; using BlueMarble::Ref; class CitySystem : public BlueMarble::System { public: CitySystem(std::shared_ptr<BlueMarble::GameCamera> camera) : oCamera(camera) {} virtual ~CitySystem() = default; virtual void OnUpdate(BlueMarble::TimeStep ts, std::vector<Ref<Entity>>& entities) override; bool CanPlace(BlueMarble::Ref<Entity> terrain, glm::vec3& position); void PlaceCity(BlueMarble::Ref<Entity> city, glm::vec3& position); private: std::shared_ptr<BlueMarble::GameCamera> oCamera; };
EwanMcA/GameEngine
BlueMarble/src/BlueMarble/Renderer/RenderCommand.h
<reponame>EwanMcA/GameEngine #pragma once #include "RendererAPI.h" namespace BlueMarble { class RenderCommand { public: inline static void Init() { cRendererAPI->Init(); } inline static void SetClearColor(const glm::vec4& color) { cRendererAPI->SetClearColor(color); } inline static void Clear() { cRendererAPI->Clear(); } inline static void DrawIndexed(const Ref<VertexArray>& vertexArray) { cRendererAPI->DrawIndexed(vertexArray); } private: static RendererAPI* cRendererAPI; }; } // namespace BlueMarble
EwanMcA/GameEngine
Sandbox/src/sandbox.h
<reponame>EwanMcA/GameEngine #pragma once #include <BlueMarble.h> #include "gameLayer.h" #include "mapLayer.h" #include "systems/renderSystem.h" #include "systems/citySystem.h" #include "systems/playerInputSystem.h" #include "systems/territorySystem.h" #define X_VERTICES 256 #define Y_VERTICES 256 class Sandbox : public BlueMarble::Application { public: Sandbox() : oCamera(std::make_shared<BlueMarble::GameCamera>( glm::radians(45.0f), (float)BlueMarble::Application::Get().GetWindow().GetWidth() / (float)BlueMarble::Application::Get().GetWindow().GetHeight(), 0.1f, 100.0f)) { ecs = std::make_shared<BlueMarble::EntityComponentSystem>(); ecs->AddSystem(new RenderSystem(oCamera)); ecs->AddSystem(new PlayerInputSystem(oCamera)); ecs->AddSystem(new CitySystem(oCamera)); ecs->AddSystem(new TerritorySystem(oCamera)); PushLayer(new MapLayer(X_VERTICES, Y_VERTICES, oCamera, ecs)); PushLayer(new GameLayer(X_VERTICES, Y_VERTICES, oCamera, ecs)); } virtual ~Sandbox() override { } private: BlueMarble::Ref<BlueMarble::GameCamera> oCamera; std::shared_ptr<BlueMarble::EntityComponentSystem> ecs; };
EwanMcA/GameEngine
BlueMarble/src/Platform/OpenGL/openGLTexture.h
<reponame>EwanMcA/GameEngine #pragma once #include "BlueMarble/core.h" #include "BlueMarble/Renderer/texture.h" namespace BlueMarble { class OpenGLTexture2D : public Texture2D { public: OpenGLTexture2D(const std::string& path); virtual ~OpenGLTexture2D(); virtual uint32_t GetWidth() const override { return oWidth; } virtual uint32_t GetHeight() const override { return oHeight; } virtual void Bind(uint32_t slot = 0) const override; private: std::string oPath; uint32_t oWidth, oHeight; uint32_t oRendererID; }; }
EwanMcA/GameEngine
BlueMarble/src/BlueMarble/Events/mouseEvent.h
<reponame>EwanMcA/GameEngine #pragma once #include "event.h" namespace BlueMarble { class MouseMoveEvent : public Event { public: MouseMoveEvent(float x, float y) : oMouseX(x), oMouseY(y) {} inline float GetX() const { return oMouseX; } inline float GetY() const { return oMouseY; } std::string ToString() const override { std::stringstream ss; ss << "MouseMoveEvent: " << oMouseX << ", " << oMouseY; return ss.str(); } static EventType GetStaticType() { return EventType::MouseMove; } virtual EventType GetEventType() const override { return GetStaticType(); } virtual const char* GetName() const override { return "MouseMove"; } virtual int GetCategoryFlags() const override { return (EventCategoryMouse | EventCategoryInput); } private: float oMouseX, oMouseY; }; class MouseScrollEvent : public Event { public: MouseScrollEvent(float xOffset, float yOffset) : oXOffset(xOffset), oYOffset(yOffset) {} inline float GetXOffset() const { return oXOffset; } inline float GetYOffset() const { return oYOffset; } std::string ToString() const override { std::stringstream ss; ss << "MouseScrollEvent: " << GetXOffset() << ", " << GetYOffset(); return ss.str(); } static EventType GetStaticType() { return EventType::MouseScroll; } virtual EventType GetEventType() const override { return GetStaticType(); } virtual const char* GetName() const override { return "MouseScroll"; } virtual int GetCategoryFlags() const override { return (EventCategoryMouse | EventCategoryInput); } private: float oXOffset, oYOffset; }; class MouseButtonEvent : public Event { public: inline int GetMouseButton() const { return oButton; } virtual int GetCategoryFlags() const override { return (EventCategoryMouse | EventCategoryInput); } protected: MouseButtonEvent(int button) : oButton(button) {} int oButton; }; class MousePressEvent : public MouseButtonEvent { public: MousePressEvent(int button) : MouseButtonEvent(button) {} std::string ToString() const override { std::stringstream ss; ss << "MousePressEvent: " << oButton; return ss.str(); } static EventType GetStaticType() { return EventType::MousePress; } virtual EventType GetEventType() const override { return GetStaticType(); } virtual const char* GetName() const override { return "MousePress"; } }; class MouseReleaseEvent : public MouseButtonEvent { public: MouseReleaseEvent(int button) : MouseButtonEvent(button) {} std::string ToString() const override { std::stringstream ss; ss << "MouseReleaseEvent: " << oButton; return ss.str(); } static EventType GetStaticType() { return EventType::MouseRelease; } virtual EventType GetEventType() const override { return GetStaticType(); } virtual const char* GetName() const override { return "MouseRelease"; } }; }
EwanMcA/GameEngine
BlueMarble/src/BlueMarble/Renderer/material.h
<filename>BlueMarble/src/BlueMarble/Renderer/material.h<gh_stars>1-10 #pragma once #include "shader.h" #include "texture.h" #include <string> #include "glm/glm.hpp" namespace BlueMarble { class Material { public: virtual ~Material() = default; static Material* Create(Ref<Shader> shader); virtual void UploadUniforms() = 0; virtual void UploadTextures() = 0; virtual void SetBool(const std::string& name, const bool value) = 0; virtual void SetInt(const std::string& name, const int value) = 0; virtual void SetFloat(const std::string& name, const float value) = 0; virtual void SetFloat2(const std::string& name, const glm::vec2& values) = 0; virtual void SetFloat3(const std::string& name, const glm::vec3& values) = 0; virtual void SetFloat4(const std::string& name, const glm::vec4& values) = 0; virtual void SetMat3(const std::string& name, const glm::mat3& matrix) = 0; virtual void SetMat4(const std::string& name, const glm::mat4& matrix) = 0; virtual const bool GetBool(const std::string& name) const = 0; virtual const int GetInt(const std::string& name) const = 0; virtual const float GetFloat(const std::string& name) const = 0; virtual const glm::vec2& GetFloat2(const std::string& name) const = 0; virtual const glm::vec3& GetFloat3(const std::string& name) const = 0; virtual const glm::vec4& GetFloat4(const std::string& name) const = 0; virtual const glm::mat3& GetMat3(const std::string& name) const = 0; virtual const glm::mat4& GetMat4(const std::string& name) const = 0; virtual void AddTexture2D(Ref<Texture2D> texture) = 0; }; }
EwanMcA/GameEngine
BlueMarble/src/BlueMarble/Events/event.h
#pragma once #include "bmpch.h" #include "BlueMarble/core.h" namespace BlueMarble { enum class EventType { None = 0, MousePress, MouseRelease, MouseMove, MouseScroll, KeyPress, KeyRelease, KeyType, WindowClose, WindowFocus, WindowResize, WindowLostFocus, WindowMove }; enum EventCategory { None = 0, EventCategoryApplication = BIT(0), EventCategoryInput = BIT(1), EventCategoryKeyboard = BIT(2), EventCategoryMouse = BIT(3), EventCategoryMouseButton = BIT(4) }; class Event { public: bool Handled = false; virtual std::string ToString() const { return GetName(); } virtual const char* GetName() const = 0; virtual EventType GetEventType() const = 0; virtual int GetCategoryFlags() const = 0; inline bool IsInCategory(EventCategory category) { return GetCategoryFlags() & category; } }; class EventDispatcher { template<typename T> using EventFn = std::function<bool(T&)>; public: EventDispatcher(Event& event) : m_Event(event) { } template<typename T> bool Dispatch(EventFn<T> func) { if (m_Event.GetEventType() == T::GetStaticType()) { m_Event.Handled = func(*(T*)&m_Event); return true; } return false; } private: Event& m_Event; }; inline std::ostream& operator<<(std::ostream& os, const Event& e) { return os << e.ToString(); } }
EwanMcA/GameEngine
BlueMarble/src/BlueMarble/log.h
<reponame>EwanMcA/GameEngine #pragma once #include "core.h" #include "spdlog/spdlog.h" #include "spdlog/fmt/ostr.h" namespace BlueMarble { class Log { public: static void Init(); inline static std::shared_ptr<spdlog::logger>& GetCoreLogger() { return cCoreLogger; } inline static std::shared_ptr<spdlog::logger>& GetClientLogger() { return cClientLogger; } private: static std::shared_ptr<spdlog::logger> cClientLogger; static std::shared_ptr<spdlog::logger> cCoreLogger; }; } // Core Logging macros #define BM_CORE_ERROR(...) ::BlueMarble::Log::GetCoreLogger()->error(__VA_ARGS__) #define BM_CORE_WARN(...) ::BlueMarble::Log::GetCoreLogger()->warn(__VA_ARGS__) #define BM_CORE_INFO(...) ::BlueMarble::Log::GetCoreLogger()->info(__VA_ARGS__) #define BM_CORE_TRACE(...) ::BlueMarble::Log::GetCoreLogger()->trace(__VA_ARGS__) #define BM_CORE_FATAL(...) ::BlueMarble::Log::GetCoreLogger()->fatal(__VA_ARGS__) // Client Logging macros #define BM_ERROR(...) ::BlueMarble::Log::GetClientLogger()->error(__VA_ARGS__) #define BM_WARN(...) ::BlueMarble::Log::GetClientLogger()->warn(__VA_ARGS__) #define BM_INFO(...) ::BlueMarble::Log::GetClientLogger()->info(__VA_ARGS__) #define BM_TRACE(...) ::BlueMarble::Log::GetClientLogger()->trace(__VA_ARGS__) #define BM_FATAL(...) ::BlueMarble::Log::GetClientLogger()->fatal(__VA_ARGS__) // If distribution build.. def these to nothing..
EwanMcA/GameEngine
BlueMarble/src/BlueMarble/window.h
<gh_stars>1-10 #pragma once #include "bmpch.h" #include "BlueMarble/Core.h" #include "BlueMarble/Events/Event.h" namespace BlueMarble { struct WindowProps { std::string Title; unsigned int Width; unsigned int Height; WindowProps(const std::string& title = "BlueMarble Engine", unsigned int width = 1600, unsigned int height = 900) : Title(title), Width(width), Height(height) { } }; // Interface representing a desktop Window class Window { public: using EventCallbackFn = std::function<void(Event&)>; virtual ~Window() {} virtual void OnUpdate() = 0; virtual unsigned int GetWidth() const = 0; virtual unsigned int GetHeight() const = 0; // Window attributes virtual void SetEventCallback(const EventCallbackFn& callback) = 0; virtual void SetVSync(bool enabled) = 0; virtual bool IsVSync() const = 0; virtual void* GetNativeWindow() const = 0; static Window* Create(const WindowProps& props = WindowProps()); }; }
EwanMcA/GameEngine
BlueMarble/src/BlueMarble/terrain.h
#pragma once #include <memory> #include <vector> #include "BlueMarble/entity.h" #include "BlueMarble/Renderer/shader.h" #include "BlueMarble/Renderer/vertexArray.h" #include "BlueMarble/Renderer/texture.h" namespace BlueMarble { class BMPHeightMap { public: BMPHeightMap(const std::string& path); std::string oFilePath; unsigned char* oLocalBuffer; int oWidth, oHeight, oBPP; }; class Terrain : public Entity { public: Terrain() : oXCount(0), oYCount(0), oSpacing(0) {} virtual ~Terrain() = default; void Init(const uint32_t xCount, const uint32_t yCount, const float spacing = 1.0f, const glm::vec3& position = glm::vec3(0.0f)); void Load(Ref<Material> material); // Getters float GetXWidth() const { return oXCount * oSpacing; } float GetYWidth() const { return oYCount * oSpacing; } float GetSpacing() const { return oSpacing; } uint32_t GetXCount() const { return oXCount; } uint32_t GetYCount() const { return oYCount; } float HeightAt(const uint32_t x, const uint32_t y) const { return oHeightScale * (*oHeightMap)[x + y * oXCount]; } float GetHeightScale() const { return oHeightScale; } void NormalAt(const uint32_t x, const uint32_t y, glm::vec3& normal) const; const glm::vec3& GetPosition() const { return oPosition; } float LayerGet(const int layerIx, const int x, const int y) const { return (*oDataLayers[layerIx])[x + y * oXCount]; } // Modifiers void GenerateVertices(std::vector<float>& vertices); void GenerateRandomHeightMap(); void RefreshOverlay(); void RefreshVertices() { RefreshVertices(-1, 0, 0, oXCount, oYCount); } void RefreshVertices(const int layerIx, const int xMin, const int yMin, const int xMax, const int yMax); void LayerAdd(const int layerIx, const int x, const int y, const float amount, const int radius); void LayerSet(const int layerIx, const int x, const int y, const float amount); void LayerSet(const int layerIx, const int x, const int y, const float amount, const int radius); void LayerSmooth(const int layerIx, const int x, const int y, const int radius); void LayerClear(const int layerIx) { oDataLayers[layerIx]->clear(); oDataLayers[layerIx]->resize(oXCount * oYCount, 0.0f); } void ResetHeightMap() { LayerClear(0); } void ResetHeightMap(BMPHeightMap& heightMap); void SetHeightScale(const float scale) { oHeightScale = scale; } void SetTexCoordCallback(const std::function<std::pair<float, float>(int, int)>& callback) { oTexCoordCallback = callback; } void SetOverlayCallback(const std::function<float(int, int)>& callback) { oOverlayCallback = callback; } void AddDataLayer(Ref<std::vector<float>> layer) { oDataLayers.push_back(layer); } void LoadVB(); private: // Counts = number of squares (also number of vertices in the heightmap) unsigned int oXCount; unsigned int oYCount; float oSpacing; float oHeightScale = 0.25f; glm::vec3 oPosition; Ref<std::vector<float>> oHeightMap; std::vector<float> oVertices; // TODO: Generalise this callback system so that everything beyond positions/normals comes from the // user, and not with the stock terrain object. // Thus only the game code / shader would know about the tex coords and vertex stats. // - The difficulty lies in modifying the BufferLayout. // (x, y) -> (2d texture coords) by default, function returns unit square coords. std::function<std::pair<float, float>(int, int)> oTexCoordCallback = [](int x, int y) -> std::pair<float, float> { float xTex = (x % 2 == 0) ? 0.0f : 1.0f; float yTex = (y % 2 == 0) ? 0.0f : 1.0f; return { xTex, yTex }; }; std::function<float(int, int)> oOverlayCallback = [](int x, int y) -> float { return 0.0f; }; // Layers have a data point for each vertex, and are submitted to the shader in the vertex buffer std::vector<Ref<std::vector<float>>> oDataLayers; Ref<BlueMarble::VertexArray> oVA; }; } // namespace BlueMarble
EwanMcA/GameEngine
BlueMarble/src/BlueMarble/layerStack.h
<filename>BlueMarble/src/BlueMarble/layerStack.h #pragma once #include "BlueMarble/core.h" #include "layer.h" #include <vector> namespace BlueMarble { class LayerStack { public: LayerStack(); ~LayerStack(); void PushLayer(Layer* layer); void PushOverlay(Layer* overlay); void PopLayer(Layer* layer); void PopOverlay(Layer* overlay); std::vector<Layer*>::iterator begin() { return oLayers.begin(); } std::vector<Layer*>::iterator end() { return oLayers.end(); } private: std::vector<Layer*> oLayers; unsigned int oLayerInsertIndex = 0; }; } // namespace BlueMarble
EwanMcA/GameEngine
BlueMarble/src/BlueMarble/entity.h
<filename>BlueMarble/src/BlueMarble/entity.h<gh_stars>1-10 #pragma once #include <map> #include "component.h" namespace BlueMarble { class Entity { public: Entity(long id = 0) : oID(id) {} virtual ~Entity() = default; long GetID() { return oID; } template <typename T> void SetComponent(Ref<Component> component) { oComponents[GetTypeID<T>()] = component; } template <typename T> void RemoveComponent() { oComponents.erase(GetTypeID<T>()); } template<typename T> Ref<T> GetComponent() { return std::static_pointer_cast<T>(oComponents[GetTypeID<T>()]); } template<typename T> bool HasComponent() { return oComponents.find(GetTypeID<T>()) != oComponents.end(); } std::map<uint32_t, Ref<Component>>::iterator begin() { return oComponents.begin(); } std::map<uint32_t, Ref<Component>>::iterator end() { return oComponents.end(); } std::map<uint32_t, Ref<Component>>::const_iterator begin() const { return oComponents.begin(); } std::map<uint32_t, Ref<Component>>::const_iterator end() const { return oComponents.end(); } private: std::map<uint32_t, Ref<Component>> oComponents; long oID{ 0 }; }; }
erikalveflo/parallella-remapper
include/pcg.h
<filename>include/pcg.h #pragma once #include <stdint.h> // *Really* minimal PCG32 code / (c) 2014 <NAME> / pcg-random.org // Licensed under Apache License 2.0 (NO WARRANTY, etc. see website) typedef struct { uint64_t state; uint64_t inc; } pcg32_random_t; #define PCG32_INITIALIZER { 0x853c49e6748fea9bULL, 0xda3e39cb94b95bdbULL } uint32_t pcg32_random_r(pcg32_random_t* rng);
erikalveflo/parallella-remapper
src/remapping.c
#include "remapping.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <math.h> // A function pointer to a comparison function used when sorting a list. typedef e_bool_t (*w_compare_func_t)(w_list_element_t, w_list_element_t); //////////////////////////////////////////////////////////////////////////////// // Frees the data pointer to by [p] and sets to to NULL. Protects against // multiple frees of the same data. static void w_free(void **p) { if (p != NULL && *p != NULL) { free(*p); *p = NULL; } } // Generates a random double between 0 and 1 using the supplied PRNG-state. static double w_random01(pcg32_random_t *pcg) { return (double)pcg32_random_r(pcg) / UINT32_MAX; } // Generates a random integer between 0 and [max] using the supplied PRNG-state. static w_size_t w_random_range(w_size_t max, pcg32_random_t *pcg) { return max * w_random01(pcg); } //////////////////////////////////////////////////////////////////////////////// w_coord_t w_get_coord(w_core_id_t id, w_size_t cols) { w_coord_t coord; coord.row = id / cols; coord.col = id % cols; return coord; } w_core_id_t w_get_core_id(w_coord_t coord, w_size_t cols) { return coord.col + coord.row * cols; } // Compute the Manhattan distance between two coordinates [a] and [b]. static double w_manhattan_distance(w_coord_t a, w_coord_t b) { return abs(a.col - b.col) + abs(a.row - b.row); } //////////////////////////////////////////////////////////////////////////////// unsigned w_get_global_address(e_epiphany_t *device, w_core_id_t id, unsigned offset) { w_coord_t coord = w_get_coord(id, device->cols); coord.col += device->base_coreid; return offset + coord.col * 0x00100000 + coord.row * 0x04000000; } w_error_code_t w_write(e_epiphany_t *device, w_core_id_t id, unsigned address, void *source, size_t size) { w_coord_t coord = w_get_coord(id, device->cols); return e_write(device, coord.row, coord.col, address, source, size); } w_error_code_t w_read(e_epiphany_t *device, w_core_id_t id, unsigned address, void *target, size_t size) { w_coord_t coord = w_get_coord(id, device->cols); return e_read(device, coord.row, coord.col, address, target, size); } //////////////////////////////////////////////////////////////////////////////// void w_init_list(w_list_t *list, w_size_t capacity) { list->capacity = capacity; list->size = 0; if (capacity > 0) { list->elements = malloc(capacity * sizeof(list->elements[0])); } else { list->elements = NULL; } } void w_free_list(w_list_t *list) { w_free((void **)&list->elements); list->capacity = 0; list->size = 0; } // Adds [element] to the end of [list]. static void w_push_back(w_list_t *list, w_list_element_t element) { assert(list->capacity > list->size); list->elements[list->size] = element; ++list->size; } // Removes element at [index] from [list]. static void w_remove_at(w_list_t *list, w_size_t index) { assert(index < list->size); assert(list->size > 0); list->elements[index] = list->elements[list->size - 1]; --list->size; } // Clears the list and grows its storage capacity. static void w_clear_list(w_list_t *list, w_size_t new_capacity) { if (new_capacity > list->capacity) { // Allocate more memory for the array. w_free_list(list); w_init_list(list, new_capacity); } list->size = 0; } // Copies the elements in [src] to [dst]. The lists can be of different sizes // and capacities. static void w_copy_list(w_list_t *dst, w_list_t *src) { w_clear_list(dst, src->capacity); dst->size = src->size; memcpy(dst->elements, src->elements, src->capacity * sizeof(src->elements[0])); } // Sorts [list] based on the predicate [compare] where [compare] is a function // which returns true when its first argument should go before its second // argument. Implemented as bubble sort which is O(N^2). static void w_sort(w_list_t *list, w_compare_func_t compare) { w_size_t i, j; w_list_element_t tmp; for (i = 0; i < list->size; ++i) { for (j = 0; j < list->size; ++j) { if (compare(list->elements[i], list->elements[j]) == E_TRUE) { tmp = list->elements[i]; list->elements[i] = list->elements[j]; list->elements[j] = tmp; } } } } //////////////////////////////////////////////////////////////////////////////// w_matrix_t w_create_matrix(w_size_t rows, w_size_t cols) { w_matrix_t matrix; uint16_t size = rows * cols; matrix.size = size; matrix.rows = rows; matrix.cols = cols; matrix.elements = calloc(size, sizeof(matrix.elements[0])); return matrix; } void w_free_matrix(w_matrix_t *matrix) { w_free((void **)&matrix->elements); matrix->size = 0; matrix->rows = 0; matrix->cols = 0; } // Copies the elements in [src] to [dst]. The matrices must be of equal size. static void w_copy_matrix(w_matrix_t *dst, w_matrix_t *src) { assert(dst->size == src->size); memcpy(dst->elements, src->elements, dst->size * sizeof(dst->elements[0])); } void w_find_not_in_matrix(w_matrix_t *matrix, w_list_t *result, w_matrix_element_t needle) { w_size_t i; w_clear_list(result, matrix->size); for (i = 0; i < matrix->size; ++i) { if (matrix->elements[i] != needle) { w_push_back(result, i); } } } void w_find_in_matrix(w_matrix_t *matrix, w_list_t *result, w_matrix_element_t needle) { w_size_t i; w_clear_list(result, matrix->size); for (i = 0; i < matrix->size; ++i) { if (matrix->elements[i] == needle) { w_push_back(result, i); } } } void w_find_mask_in_matrix(w_matrix_t *matrix, w_list_t *result, w_matrix_element_t mask) { w_size_t i; w_clear_list(result, matrix->size); for (i = 0; i < matrix->size; ++i) { if ((matrix->elements[i] & mask) != 0) { w_push_back(result, i); } } } void w_print_matrix(w_matrix_t *matrix, const char *name) { w_size_t row, col; w_matrix_element_t e; printf("%s Matrix (rows: %u, cols: %u)\n", name, matrix->rows, matrix->cols); for (row = 0; row < matrix->rows; ++row) { printf(" "); for (col = 0; col < matrix->cols; ++col) { e = matrix->elements[col + row * matrix->cols]; e != 0 ? (e == W_SIZE_MAX ? printf(" X ") : printf("%2u ", e)) : printf(" . "); } printf("\n"); } } // Swaps element at index [a] with element at index [b] in [matrix]. static void w_swap_matrix_elements(w_matrix_t *matrix, uint16_t a, uint16_t b) { assert(matrix->size > a && "index out of bounds"); assert(matrix->size > b && "index out of bounds"); w_matrix_element_t tmp = matrix->elements[a]; matrix->elements[a] = matrix->elements[b]; matrix->elements[b] = tmp; } // Shuffles the elements in [matrix] randomly using the suppled PRNG-state. static void w_shuffle_matrix(w_matrix_t *matrix, pcg32_random_t *pcg) { w_size_t i, a, b; w_size_t size; size = matrix->size; for (i = 0; i < 2 * size; ++i) { a = w_random_range(size, pcg); b = w_random_range(size, pcg); w_swap_matrix_elements(matrix, a, b); } } // Shuffles the [matrix] elements with [indices] randomly using the suppled // PRNG-state. static void w_shuffle_partial_matrix(w_matrix_t *matrix, w_list_t *indices, pcg32_random_t *pcg) { w_size_t i, a, b; for (i = 2 * matrix->size; i > 0; --i) { a = w_random_range(indices->size, pcg); b = w_random_range(indices->size, pcg); a = indices->elements[a]; b = indices->elements[b]; w_swap_matrix_elements(matrix, a, b); } } //////////////////////////////////////////////////////////////////////////////// // Resets the mapping matrix to its original values: core 0 and location 0, core // 1 at 1 ... core N at N. static void w_reset_mapping_matrix(w_mapper_t *mapper) { w_size_t i; for (i = 0; i < mapper->num_cores; ++i) { mapper->mapping_matrix.elements[i] = i; } } // Resets the constraint matrix to allow any task on all cores. static void w_reset_constraint_matrix(w_mapper_t *mapper) { w_size_t i; for (i = 0; i < mapper->num_cores; ++i) { mapper->constraint_matrix.elements[i] = W_ALLOW_ANY; } } w_mapper_t w_create_mapper(w_size_t rows, w_size_t cols) { assert(rows > 0); assert(cols > 0); size_t size; uint16_t num_cores; w_mapper_t mapper; memset(&mapper, 0, sizeof(mapper)); num_cores = rows * cols; mapper.num_cores = num_cores; mapper.rows = rows; mapper.cols = cols; size = num_cores * sizeof(mapper.links.indices[0]); mapper.links.indices = malloc(size); memset(mapper.links.indices, W_NO_LINK, size); mapper.allocation_matrix = w_create_matrix(rows, cols); mapper.constraint_matrix = w_create_matrix(rows, cols); mapper.fault_matrix = w_create_matrix(rows, cols); mapper.assignment_matrix = w_create_matrix(rows, cols); mapper.mapping_matrix = w_create_matrix(rows, cols); w_reset_constraint_matrix(&mapper); w_reset_mapping_matrix(&mapper); return mapper; } void w_free_mapper(w_mapper_t *mapper) { mapper->num_cores = 0; mapper->links.capacity = 0; mapper->links.size = 0; w_free((void **)&mapper->links.indices); w_free((void **)&mapper->links.data); w_free_matrix(&mapper->allocation_matrix); w_free_matrix(&mapper->constraint_matrix); w_free_matrix(&mapper->fault_matrix); w_free_matrix(&mapper->assignment_matrix); w_free_matrix(&mapper->mapping_matrix); } void w_set_allocation_matrix(w_mapper_t *mapper, w_matrix_element_t *allocation_matrix) { memcpy(mapper->allocation_matrix.elements, allocation_matrix, mapper->allocation_matrix.size * sizeof(w_matrix_element_t)); } void w_set_constraint_matrix(w_mapper_t *mapper, w_matrix_element_t *constraint_matrix) { memcpy(mapper->constraint_matrix.elements, constraint_matrix, mapper->constraint_matrix.size * sizeof(w_matrix_element_t)); } void w_set_fault_matrix(w_mapper_t *mapper, w_matrix_element_t *fault_matrix) { memcpy(mapper->fault_matrix.elements, fault_matrix, mapper->fault_matrix.size * sizeof(w_matrix_element_t)); } void w_set_assignment_matrix(w_mapper_t *mapper, w_matrix_element_t *assignment_matrix) { memcpy(mapper->assignment_matrix.elements, assignment_matrix, mapper->assignment_matrix.size * sizeof(w_matrix_element_t)); } void w_add_link(w_mapper_t *mapper, w_core_id_t begin, w_core_id_t end) { assert(mapper->num_cores > begin); assert(mapper->num_cores > end); w_link_collection_t *links; w_link_t link; w_size_t new_capacity; w_size_t insert_at, next; links = &mapper->links; if (links->size + 1 > links->capacity) { // Increase capacity to make room for more links. new_capacity = (links->capacity * 3) / 2; new_capacity = new_capacity < 8 ? 8 : new_capacity; printf("Increasing link storage capacity to %u\n", new_capacity); links->data = realloc(links->data, new_capacity * sizeof(links->data[0])); links->capacity = new_capacity; } // Insert at the end of the list. Use the next field to point to the // previous head of the array. insert_at = links->size; next = links->indices[begin]; printf("Inserting link from %u to %u (at: %u, next: %u)\n", begin, end, insert_at, next); link.begin = begin; link.end = end; link.next = next; links->indices[begin] = insert_at; links->data[insert_at] = link; ++links->size; } //////////////////////////////////////////////////////////////////////////////// // Check that the given [allocation]/assignment matrix upholds the constraints // defined in the [constraint] matrix. static w_error_code_t w_verify_constraints(w_matrix_t *constraint, w_matrix_t *allocation) { assert(constraint->size == allocation->size); w_size_t i; w_task_id_t task; for (i = 0; i < allocation->size; ++i) { task = allocation->elements[i]; if (task != 0 && (constraint->elements[i] & task) == 0) { printf("Constraint violation: task %u not allowed on core %u\n", task, i); return E_ERR; } } return E_OK; } // Check that the given assignment matrix does not use faulty cores from the // [faults] matrix. static w_error_code_t w_verify_assignment(w_matrix_t *faults, w_matrix_t *assignment) { assert(faults->size == assignment->size); w_size_t i; w_task_id_t task; for (i = 0; i < assignment->size; ++i) { task = assignment->elements[i]; if (task != 0 && faults->elements[i] != 0) { printf("Faulty core %u assigned to task %u\n", i, task); return E_ERR; } } return E_OK; } // Counts the number of set bits (ones) in the supplied 32-bit number. Adopted // from code by <NAME> http://stackoverflow.com/a/109025/1009118 static uint32_t w_count_high_bits(uint32_t i) { i = i - ((i >> 1) & 0x55555555); i = (i & 0x33333333) + ((i >> 2) & 0x33333333); return (((i + (i >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24; } // A predicate for sorting by the number of set bits in ascending order. static e_bool_t w_sort_by_number_of_bits_asc(w_list_element_t a, w_list_element_t b) { return w_count_high_bits(a) > w_count_high_bits(b) ? E_TRUE : E_FALSE; } w_error_code_t w_assign_naive(w_mapper_t *mapper) { w_error_code_t error_code; w_size_t i, j; w_list_t faults, spares, choices; w_core_id_t faulty, spare; w_task_id_t task; e_bool_t spare_found; e_bool_t available_cores[mapper->num_cores]; w_init_list(&faults, mapper->num_cores); w_init_list(&spares, mapper->num_cores); w_init_list(&choices, mapper->num_cores); if (w_verify_constraints(&mapper->constraint_matrix, &mapper->allocation_matrix) != E_OK) { printf("WARNING: Constraint violation in allocation matrix.\n"); } // Reset mapper: clear changes and use the allocation matrix as the initial // solution. w_reset_mapping_matrix(mapper); w_copy_matrix(&mapper->assignment_matrix, &mapper->allocation_matrix); w_find_not_in_matrix(&mapper->fault_matrix, &faults, 0); if (faults.size == 0) { // No faults: the allocation matrix is a good assignment matrix. goto success; } // Faults are present in the system. Find the spares. w_find_in_matrix(&mapper->allocation_matrix, &spares, 0); if (faults.size > spares.size) { printf("ERROR: Too many faults. Only %u spare cores are available but %u are faulty.\n", spares.size, faults.size); goto error; } // Mark all cores as either available or not. Allocated and faulty cores are // not available. for (i = 0; i < mapper->num_cores; ++i) { if (mapper->fault_matrix.elements[i] == 0 && mapper->allocation_matrix.elements[i] == 0) { available_cores[i] = E_TRUE; } else { available_cores[i] = E_FALSE; } } // This is the naive part. Replace each faulty core with the first spare // core. for (i = 0; i < faults.size; ++i) { faulty = faults.elements[i]; task = mapper->allocation_matrix.elements[faulty]; if (task == 0) continue; // Find the cores form which a spare can be chosen. The choices are // limited by constraints and faults. It should be possible to cache // these results. w_find_mask_in_matrix(&mapper->constraint_matrix, &choices, task); // Sort the cores in order of restrictiveness. This will assign // restrictive cores first; for example, if core 1 only accepts task 1 // then it will be assigned prior to core 0 which accepts any task. w_sort(&choices, &w_sort_by_number_of_bits_asc); // Find an unassigned core among the choices that fulfill the // constraints. spare_found = E_FALSE; for (j = 0; j < choices.size; ++j) { spare = choices.elements[j]; if (available_cores[spare] == E_TRUE) { spare_found = E_TRUE; break; } } if (spare_found == E_FALSE) { printf("ERROR: Spare not found for core %u. Task %u is constrained to %u location(s) of %u free spare location(s).\n", faulty, task, choices.size, spares.size); w_print_matrix(&mapper->assignment_matrix, "Partial Assignment"); goto error; } printf("Fault at %u replaced by %u\n", faulty, spare); mapper->assignment_matrix.elements[spare] = task; mapper->assignment_matrix.elements[faulty] = 0; available_cores[spare] = E_FALSE; // Keep track of all changes. w_swap_matrix_elements(&mapper->mapping_matrix, faulty, spare); } if (w_verify_constraints(&mapper->constraint_matrix, &mapper->assignment_matrix) != E_OK) { printf("ERROR: Constraint violation in assignment matrix.\n"); goto error; } // The assignment was a success. goto success; success: error_code = E_OK; goto cleanup; error: error_code = E_ERR; goto cleanup; cleanup: w_free_list(&faults); w_free_list(&spares); w_free_list(&choices); return error_code; } //////////////////////////////////////////////////////////////////////////////// // Computes the probability of accepting a neighbor solution when running // simulated annealing for the given temperature and energies. The probability // is a number between 0 and 1; where 1 means that the neighbor solution should // be accepted. static double w_acceptance_propability(double current_energy, double neighbor_energy, double temperature) { if (neighbor_energy < current_energy) return 1.0; return exp((current_energy - neighbor_energy) / temperature); } // Computes the energy of the given [solution]. The energy is the cost function // that simulated annealing tries to minimize. A high energy equals a high cost // and therefore a bad solution. // // The position of each core is given by [solution]. solution[0] is the position // of the zeroth core. If, for example, solution[0] == 2 core zero can be found // at position 2. static double w_compute_energy(w_mapper_t *mapper, w_matrix_t *solution) { double energy; w_link_t *link; w_size_t i; w_coord_t begin, end; energy = 0.0; // Compute the distance between each connected core in the current solution. for (i = 0; i < mapper->links.size; ++i) { link = &mapper->links.data[i]; begin = w_get_coord(solution->elements[link->begin], mapper->cols); end = w_get_coord(solution->elements[link->end], mapper->cols); energy += w_manhattan_distance(begin, end); } return energy; } // Returns true if the cores [a] and [b] are allowed to swap positions based on // the tasks allocated to those cores and their constraints. static e_bool_t w_allow_swap(w_mapper_t *mapper, w_matrix_t *solution, w_core_id_t a, w_core_id_t b) { w_core_id_t pos_a, pos_b; w_task_id_t task_a, task_b; w_constraint_mask_t mask_a, mask_b; w_matrix_element_t fault_a, fault_b; pos_a = solution->elements[a]; pos_b = solution->elements[b]; task_a = mapper->allocation_matrix.elements[a]; task_b = mapper->allocation_matrix.elements[b]; mask_a = mapper->constraint_matrix.elements[pos_a]; mask_b = mapper->constraint_matrix.elements[pos_b]; fault_a = mapper->fault_matrix.elements[pos_a]; fault_b = mapper->fault_matrix.elements[pos_b]; if (task_a != 0) { if (fault_b != 0 || (mask_b & task_a) == 0) { return E_FALSE; } } if (task_b != 0) { if (fault_a != 0 || (mask_a & task_b) == 0) { return E_FALSE; } } return E_TRUE; } w_sa_config_t w_create_sa_config() { w_sa_config_t c; c.start_temperature = 1.0e3; c.stop_temperature = 1.0e-10; c.cooling_rate = 0.3e-3; c.partial = E_FALSE; c.seed = 0; return c; } // Get two indices [pa] and [pb] to swap. These indices are based on [choices]. // Returns true if the returned indices represent an allowed swap (that does not // violate design constraints.) static e_bool_t w_get_swap_indices( w_mapper_t *mapper, w_list_t *choices, w_list_t *swappable, w_matrix_t *current_solution, w_matrix_t *inverse_solution, pcg32_random_t *pcg, w_size_t *pa, // Out argument. Index in [current_solution]. w_size_t *pb // Out argument. Index in [current_solution]. ) { w_size_t i, a, b; w_core_id_t id; // Create a list of swappable indices. [choices] contain core IDs but we // need the position of the cores (their index in [current_solution].) swappable->size = choices->size; for (i = 0; i < choices->size; ++i) { id = choices->elements[i]; swappable->elements[i] = inverse_solution->elements[id]; } a = swappable->elements[w_random_range(swappable->size, pcg)]; b = swappable->elements[w_random_range(swappable->size, pcg)]; *pa = a; *pb = b; // Does the swap violate constraints? return w_allow_swap(mapper, current_solution, a, b); } // Swap index [a] and [b] in [current_solution]. Call this function again (with // the same arguments) to undo the swap. static void w_swap(w_matrix_t *current_solution, w_matrix_t *inverse_solution, w_size_t a, w_size_t b) { w_swap_matrix_elements(current_solution, a, b); w_swap_matrix_elements(inverse_solution, current_solution->elements[a], current_solution->elements[b]); } w_error_code_t w_assign_sa(w_mapper_t *mapper, w_sa_config_t *_config) { w_sa_config_t config = _config == NULL ? w_create_sa_config() : *_config; w_error_code_t error_code; double temperature = config.start_temperature; const double cooling_factor = 1.0 - config.cooling_rate; // Expected number of iterations under ideal conditions. const uint32_t expected_iterations = ceil((log(config.stop_temperature) - log(config.start_temperature)) / log(cooling_factor)); // If the number of failed iterations exceed this number, no solution was // found in a reasonable amount of time. const uint32_t max_failed_iterations = expected_iterations; uint32_t iteration_count = 0; // Number of performed iterations. uint32_t failure_count = 0; // Number of iterations that violated constraints. w_size_t i, a, b, position, task; // Temporary variables. w_core_id_t id; double accept = 0.0; // Acceptance probability. double neighbor_energy = 0.0; // Energy of new solution, not yet accepted. double current_energy = 0.0; // Energy of currently accepted solution. double lowest_energy = 0.0; // Lowest found energy (see lowest_solution.) e_bool_t allow_swap; // Is the swap allowed? Does it violate constraints? // These matrices holds the position of each core (same as // [mapper.mapping_matrix].) For example, element 0 holds the position of // core 0. Translates core ID to grid position. w_matrix_t current_solution = w_create_matrix(mapper->rows, mapper->cols); w_matrix_t lowest_solution = w_create_matrix(mapper->rows, mapper->cols); // This matrix holds the core ID at each position. For example, element 0 // holds the core ID at position 0. Translates grid position to core ID. w_matrix_t inverse_solution = w_create_matrix(mapper->rows, mapper->cols); // Initialize the random number generator. We could use time() here but // we'll let the user decide if that is useful. pcg32_random_t pcg = PCG32_INITIALIZER; pcg.state += config.seed + 2; // Lists all core IDs that we are allowed to swap. For partial remapping // this list is small; otherwise it contains all core IDs. w_list_t choices; w_init_list(&choices, mapper->num_cores); // Lists all indices in [current_solution] that we are allowed to swap. This // list is based on [choices] but changes with each swap. w_list_t swappable; w_init_list(&swappable, mapper->num_cores); // Temporary list of all spare cores in the assignment matrix. w_list_t spares; w_init_list(&spares, 0); if (w_verify_constraints(&mapper->constraint_matrix, &mapper->allocation_matrix) != E_OK) { printf("WARNING: Constraint violation in allocation matrix.\n"); } if (config.partial == E_FALSE) { // All cores are assigned during non-partial assignment. for (i = 0; i < mapper->num_cores; ++i) { w_push_back(&choices, i); } // Reset and forget about previous solutions. w_reset_mapping_matrix(mapper); w_copy_matrix(&mapper->assignment_matrix, &mapper->allocation_matrix); } else { // Only a limited number of cores are assigned during partial // assignment. These cores are added to [choices]. We only need to remap // assigned faulty cores. // TODO: Test if a valid assignment matrix exists. // NOTE: [spares] is a temporary list only used here. // Add all faulty cores to the list of choices, and then remove all // faulty non-assigned cores. w_find_not_in_matrix(&mapper->fault_matrix, &choices, 0); for (i = 0; i < choices.size; ++i) { id = choices.elements[i]; if (mapper->assignment_matrix.elements[id] == 0) { w_remove_at(&choices, i); --i; } } // Add all spare cores to the list of choices. w_find_in_matrix(&mapper->assignment_matrix, &spares, 0); for (i = 0; i < spares.size; ++i) { id = spares.elements[i]; if (mapper->fault_matrix.elements[id] == 0) { w_push_back(&choices, id); } } } // Operate on [current_solution] instead of [mapper.mapping_matrix] even // though they represent the same thing. w_copy_matrix(&current_solution, &mapper->mapping_matrix); // Construct the inverse of the [current_solution]. for (i = 0; i < mapper->num_cores; ++i) { position = current_solution.elements[i]; inverse_solution.elements[position] = i; } // Randomize the current solution. for (i = 2 * mapper->num_cores; i > 0; ++i) { w_get_swap_indices(mapper, &choices, &swappable, &current_solution, &inverse_solution, &pcg, &a, &b); w_swap(&current_solution, &inverse_solution, a, b); } // Store best known lowest-energy solution, its energy and the energy of the // current solution. w_copy_matrix(&lowest_solution, &current_solution); current_energy = w_compute_energy(mapper, &current_solution); lowest_energy = current_energy; printf("Start energy %.2f (expected iterations: %u)\n", lowest_energy, expected_iterations); // Simulate annealing until the target temperature is reached. while (temperature > config.stop_temperature) { ++iteration_count; // Swap the position of two random cores and test if that neighboring // solution is a better solution than the current one. allow_swap = w_get_swap_indices(mapper, &choices, &swappable, &current_solution, &inverse_solution, &pcg, &a, &b); // Does the swap violate constraints? if (allow_swap == E_FALSE) { // Abort if no solution can be found within a reasonable amount of // time. ++failure_count; if (failure_count > max_failed_iterations) { printf("ERROR: Unable to find solution after %u failed iterations.\n", failure_count); goto error; } continue; } // Perform the swap and compute the new energy. w_swap(&current_solution, &inverse_solution, a, b); neighbor_energy = w_compute_energy(mapper, &current_solution); // If the neighbor solution is worse than the current one there is still // a chance that it will be accepted. Compute that chance. accept = w_acceptance_propability(current_energy, neighbor_energy, temperature); if (accept < w_random01(&pcg)) { // Don't accept the solution. w_swap(&current_solution, &inverse_solution, a, b); } else { // Accept the solution. current_energy = neighbor_energy; // Did we find a lower energy solution than previously recorded? if (lowest_energy > current_energy) { lowest_energy = current_energy; w_copy_matrix(&lowest_solution, &current_solution); printf(" energy: %.2f, iterations: %u, temperature: %.2f\n", current_energy, iteration_count, temperature); } } // Reduce the temperature slowly. temperature *= cooling_factor; } printf("End energy %.2f (iterations: %u, failed: %u)\n", lowest_energy, iteration_count, failure_count); // Copy the best solution to a publicly accessible matrix. w_copy_matrix(&mapper->mapping_matrix, &lowest_solution); // Apply the solution. for (i = 0; i < mapper->num_cores; ++i) { position = mapper->mapping_matrix.elements[i]; task = mapper->allocation_matrix.elements[i]; mapper->assignment_matrix.elements[position] = task; } if (w_verify_constraints(&mapper->constraint_matrix, &mapper->assignment_matrix) != E_OK) { printf("ERROR: Constraint violation in assignment matrix.\n"); goto error; } if (w_verify_assignment(&mapper->fault_matrix, &mapper->assignment_matrix) != E_OK) { printf("ERROR: Faulty cores assigned in assignment matrix.\n"); goto error; } // The assignment was a success. goto success; success: error_code = E_OK; goto cleanup; error: error_code = E_ERR; goto cleanup; cleanup: w_free_list(&choices); w_free_list(&swappable); w_free_list(&spares); return error_code; } void w_set_partial_constraint_pattern(w_mapper_t *mapper) { const int num_spare_cols = 1; int row, col; w_coord_t coord; w_core_id_t id; for (col = num_spare_cols; col < mapper->cols; col += num_spare_cols + 1) { coord.col = col; for (row = 0; row < mapper->rows; ++row) { coord.row = row; id = w_get_core_id(coord, mapper->cols); mapper->constraint_matrix.elements[id] = 0; } } } //////////////////////////////////////////////////////////////////////////////// w_error_code_t w_load(e_epiphany_t *device, w_list_t *core_ids, char *executable) { const e_bool_t start_program = E_FALSE; int i; w_error_code_t status; w_coord_t coord; for (i = 0; i < core_ids->size; ++i) { coord = w_get_coord(core_ids->elements[i], device->cols); status = e_load(executable, device, coord.row, coord.col, start_program); if (status != E_OK) return status; } return E_OK; }
erikalveflo/parallella-remapper
include/remapping.h
<filename>include/remapping.h #pragma once #include "pcg.h" #include <e-hal.h> #include <e-loader.h> // Used for documentation purposes to brand functions that can fail. typedef int w_error_code_t; typedef uint16_t w_matrix_element_t; typedef uint16_t w_list_element_t; typedef uint16_t w_core_id_t; typedef uint16_t w_task_id_t; typedef uint16_t w_constraint_mask_t; typedef uint16_t w_size_t; enum { W_SIZE_MAX = (w_size_t)~0, // Used in contraint matrices to allow any task (unconstrained core). W_ALLOW_ANY = (w_matrix_element_t)~0, // Indicates that a [w_mapper_t.link_index] is unused. W_NO_LINK = W_SIZE_MAX, }; //////////////////////////////////////////////////////////////////////////////// // A w_matrix_t is a matrix stored as a one-dimensional array. Always free with // w_free_matrix() when done. typedef struct { w_size_t size; // Number of elements. w_size_t rows; // Number of rows. w_size_t cols; // Number of columns. w_matrix_element_t *elements; // Array of matrix elements. } w_matrix_t; // A w_list_t is a list/array with known capacity and size. Contrary to ordinary // C-arrays this list keeps track of its capacity and the number of elements // currently occupied. Always initialize with w_init_list() prior to use and // always free with w_free_list() when done. typedef struct { w_size_t capacity; // Number of elements the list can hold. w_size_t size; // Number of elements currently occupied. w_list_element_t *elements; // Array of list elements. } w_list_t; // A w_link_t represents a data link/connection between two cores. Connected // cores send data to each other. Links are stored as a linked list where [next] // is the index of the next element in the linked list. typedef struct { w_core_id_t begin; // Link begins at this core. w_core_id_t end; // Link ends at this core. w_size_t next; // Index of the next item in the linked list or W_NO_LINK. } w_link_t; // A w_link_collection_t is a dynamic collection of w_link_t. Links are stored // as a linked list where [indices] points to the first element in the list and // [data] holds all links in the collection. [indices] includes an element for // each core which defaults to W_NO_LINK for cores without links. typedef struct { w_size_t capacity; // Number of links [data] can hold. w_size_t size; // Number of occupied links in [data]. w_size_t *indices; // Maps a core ID to an element in [data] or W_NO_LINK. w_link_t *data; // A list of links. } w_link_collection_t; // All state information needed by the mapping system. typedef struct { w_size_t num_cores; // Number of cores in the device. w_size_t rows; // Number of rows in the device. w_size_t cols; // Number of columns in the device. w_link_collection_t links; // A collection of data links. // The allocation matrix defines the original (intended) location of all // tasks and the number of cores allocated for each task. For example, in // matrix [1 1; 0 0], a task 1 is allocated to core 0 and 1. Tasks should // use power of two numbers, such as 1, 2, 4, 8, ..., 2^N. Zero denotes // spare cores. w_matrix_t allocation_matrix; // The constraints matrix is used to constrain tasks to specific cores. // Tasks are either allowed on all cores or constrained to a specific number // of cores defined in the constraint matrix. The constraints are specified // as a bit mask. The matrix [0 0; 1 0] constrain task 1 to core 3; it does // not allow other tasks. w_matrix_t constraint_matrix; // Non-zero elements indicates faulty cores. For example, in matrix [1 0; 0 // 0] the zeroth core is faulty. w_matrix_t fault_matrix; // The assignment matrix maps a task to a core. This is the result of the // assignment algorithm. For example, in matrix [1 0; 2 2], core 0 should // load task 1, and core 2 and 3 should load task 2. w_matrix_t assignment_matrix; // The mapping matrix indicates the position of each core. For example, // mapping_matrix[0] is the position of the zeroth core. w_matrix_t mapping_matrix; } w_mapper_t; // A two-dimensional coordinate. typedef struct { w_core_id_t row; // Row. w_core_id_t col; // Column. } w_coord_t; // Configuration values for the simulated annealing assignment. typedef struct { double stop_temperature; // Initial temperature. double start_temperature; // Temperature when to stop. double cooling_rate; // Temperature cooling rate. e_bool_t partial; // Perform partial remapp? // Seed for the pseudo random number generator. Use time() to generate a // unique solution each second. uint32_t seed; } w_sa_config_t; //////////////////////////////////////////////////////////////////////////////// // Convert a core ID to coordinates given the number of columns in the device. w_coord_t w_get_coord(w_core_id_t id, w_size_t cols); // Convert coordinates to a core ID given the number of columns in the device. w_core_id_t w_get_core_id(w_coord_t coord, w_size_t cols); //////////////////////////////////////////////////////////////////////////////// // Returns the global address for a core (row, col). Host processor // implementation of e_get_global_address. unsigned w_get_global_address(e_epiphany_t *device, w_core_id_t id, unsigned offset); // Writes [size] number of bytes from [source] to device memory at [address] on // core [id]. w_error_code_t w_write(e_epiphany_t *device, w_core_id_t id, unsigned address, void *source, size_t size); // Reads [size] number of bytes to [target] from device memory at [address] on // core [id]. w_error_code_t w_read(e_epiphany_t *device, w_core_id_t id, unsigned address, void *target, size_t size); //////////////////////////////////////////////////////////////////////////////// // Initializes [list] with the capacity to hold the given number of elements. // Always call this function prior to using the list and prior to calling // w_free_list(). void w_init_list(w_list_t *list, w_size_t capacity); // Frees the memory allocated for [list]. void w_free_list(w_list_t *list); //////////////////////////////////////////////////////////////////////////////// // Returns a new matrix of size [rows] and [cols]. w_matrix_t w_create_matrix(w_size_t rows, w_size_t cols); // Frees the memory allocated for [matrix]. void w_free_matrix(w_matrix_t *matrix); // Fills [result] with the indices of all elements in [matrix] not equal to // [needle]. void w_find_not_in_matrix(w_matrix_t *matrix, w_list_t *result, w_matrix_element_t needle); // Fills [result] with the indices of all elements in [matrix] equal to // [needle]. void w_find_in_matrix(w_matrix_t *matrix, w_list_t *result, w_matrix_element_t needle); // Fills [result] with the indices of all elements in [matrix] with any bit in // common with [mask]. void w_find_mask_in_matrix(w_matrix_t *matrix, w_list_t *result, w_matrix_element_t mask); // Prints [matrix] to stdout. void w_print_matrix(w_matrix_t *matrix, const char *name); //////////////////////////////////////////////////////////////////////////////// // Creates a new mapper for a device with the supplied number of [rows] and // [cols]. w_mapper_t w_create_mapper(w_size_t rows, w_size_t cols); // Frees the memory allocated for the supplied [mapper]. void w_free_mapper(w_mapper_t *mapper); // Sets the allocation matrix of [mapper]. The number of elements in the // supplied matrix should correspond to the number of cores in the device. The // matrix elements are copied into a matrix owned by [mapper]. void w_set_allocation_matrix(w_mapper_t *mapper, w_matrix_element_t *allocation_matrix); // Sets the constraint matrix of [mapper]. The number of elements in the // supplied matrix should correspond to the number of cores in the device. The // matrix elements are copied into a matrix owned by [mapper]. void w_set_constraint_matrix(w_mapper_t *mapper, w_matrix_element_t *constraint_matrix); // Sets the fault matrix of [mapper]. The number of elements in the // supplied matrix should correspond to the number of cores in the device. The // matrix elements are copied into a matrix owned by [mapper]. void w_set_fault_matrix(w_mapper_t *mapper, w_matrix_element_t *fault_matrix); // Sets the assignment matrix of [mapper]. The number of elements in the // supplied matrix should correspond to the number of cores in the device. The // matrix elements are copied into a matrix owned by [mapper]. void w_set_assignment_matrix(w_mapper_t *mapper, w_matrix_element_t *assignment_matrix); // Adds a data link/connection from [begin] core to [end] core. The [begin] core // sends data to the [end] core. The link defines a connection between the two // cores which is used during assignment. void w_add_link(w_mapper_t *mapper, w_core_id_t begin, w_core_id_t end); //////////////////////////////////////////////////////////////////////////////// // Assigns a task to each core using a naive approach. This approach is fast but // does not consider links or other optimizations. w_error_code_t w_assign_naive(w_mapper_t *mapper); //////////////////////////////////////////////////////////////////////////////// // Returns the default simulated annealing configuration. These defaults will // not work well for all applications and should be tweaked to suite your needs. w_sa_config_t w_create_sa_config(); // Assigns a task to each core using simulated annealing. This approach is slow // but tries to optimize network distances, network utilization, and other // metrics defined by a cost function. This approach only works when links have // been added using w_add_link(). // // Configuration values are sent with the [config] pointer. If NULL the default // values returned by w_create_sa_config() are used. w_error_code_t w_assign_sa(w_mapper_t *mapper, w_sa_config_t *config); // Update the constraint matrix to reserve columns of spare cores for use with // partial remapping. Every second column is reserved, limiting the maximum // distance to a spare core to one. The reserved columns are 2, 5, 8, ..., 3+2n. void w_set_partial_constraint_pattern(w_mapper_t *mapper); //////////////////////////////////////////////////////////////////////////////// // Loads the [executable] onto each core in the list of [core_ids]. w_error_code_t w_load(e_epiphany_t *device, w_list_t *core_ids, char *executable);
erikalveflo/parallella-remapper
example/ping-pong/shared.h
<gh_stars>0 #pragma once #define _MAILBOX_ADDRESS 0x7000u typedef struct { char ping; char pong; } Mailbox;
erikalveflo/parallella-remapper
example/links/shared.h
<filename>example/links/shared.h #pragma once #define _MAILBOX_ADDRESS 0x7000u typedef struct { char counter; char go; char done; unsigned int next_mailbox; // Don't use a Mailbox pointer here. } Mailbox;
erikalveflo/parallella-remapper
example/links/e_main.c
<filename>example/links/e_main.c<gh_stars>0 #include "e_lib.h" #include "shared.h" int main(void) { volatile Mailbox *mailbox; volatile Mailbox *next; mailbox = (Mailbox *)_MAILBOX_ADDRESS; next = (Mailbox *)mailbox->next_mailbox; while (mailbox->go == 0) {} next->counter = mailbox->counter + 1; next->go = 1; mailbox->done = 1; return 0; }
erikalveflo/parallella-remapper
example/ping-pong/e_main.c
<filename>example/ping-pong/e_main.c #include "e_lib.h" #include "shared.h" int main(void) { volatile Mailbox *mailbox; mailbox = (Mailbox *)_MAILBOX_ADDRESS; while (mailbox->ping == 0) {} mailbox->pong = 1; return 0; }
erikalveflo/parallella-remapper
example/links/main.c
// // Links example. // // Copyright (c) 2015, <NAME>. // #include <stdlib.h> #include <stddef.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <sys/time.h> #include <stdint.h> #include <math.h> #include <assert.h> #include <e-hal.h> #include <e-loader.h> #include <remapping.h> #include "shared.h" // Allocate multiple cores for task 1. Use power of two (2, 4, 8...) when adding // additional tasks. A task is an Epiphany device program. w_matrix_element_t allocation_matrix[16] = { 1, 1, 1, 1, // Element 0 corresponds to core (0,0), element 1 to (0,1), and 0, 0, 0, 0, // element 4 to (1,0) etc. 0, 0, 0, 0, 0, 0, 0, 0, }; // Allow task 1 on all cores. This is a per core bit-mask. #define X W_ALLOW_ANY w_matrix_element_t constraint_matrix[16] = { X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, }; #undef X // Simulate that a core is faulty by setting its element to 1. Task 1 will be // assigned to a healthy core (any core with a zero.) w_matrix_element_t fault_matrix[16] = { 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; static void msleep(int ms) { usleep(1000 * ms); } static void connect_task1(w_mapper_t *mapper, w_list_t *tasks) { int i; w_core_id_t core_id, next_id; for (i = 0; i < tasks->size; ++i) { core_id = tasks->elements[i]; next_id = tasks->elements[(i + 1) % tasks->size]; w_add_link(mapper, core_id, next_id); } } // Initializes and setup all cores assigned to execute task 1. static void init_task1(e_epiphany_t *device, w_list_t *tasks) { int i; w_core_id_t core_id, next_id; Mailbox mailbox; for (i = 0; i < tasks->size; ++i) { core_id = tasks->elements[i]; next_id = tasks->elements[(i + 1) % tasks->size]; // This core should have a pointer to the next core's mailbox. memset(&mailbox, 0, sizeof(mailbox)); mailbox.next_mailbox = w_get_global_address(device, next_id, _MAILBOX_ADDRESS); w_write(device, core_id, _MAILBOX_ADDRESS, &mailbox, sizeof(mailbox)); } } int main(int argc, char *argv[]) { e_platform_t platform; e_epiphany_t device; w_mapper_t mapper; w_sa_config_t sa_config; w_list_t task1; w_core_id_t first_id, last_id; Mailbox mailbox; memset(&mailbox, 0, sizeof(mailbox)); w_init_list(&task1, 0); printf("=== Initializing system\n"); e_set_host_verbosity(H_D0); e_init(NULL); e_reset_system(); e_get_platform_info(&platform); printf("=== Creating workgroup\n"); e_open(&device, 0, 0, platform.rows, platform.cols); printf("=== Mapping device program\n"); e_reset_group(&device); // Initialize the mapping system: we will use this to automatically map our // application, to assign a device program to each core. mapper = w_create_mapper(platform.rows, platform.cols); // Tell the mapper about our application. It needs to know about allocated // tasks, constraints and faults are optional. By default the mapper assumes // no faults and no constraints. w_set_allocation_matrix(&mapper, allocation_matrix); w_set_constraint_matrix(&mapper, constraint_matrix); w_set_fault_matrix(&mapper, fault_matrix); // Find the ID of all cores allocated for task 1, and create a link between // each core. Links are used to indicate which tasks that communicate with // each other, and to minimize the distance between communicating tasks. w_find_in_matrix(&mapper.allocation_matrix, &task1, 1); connect_task1(&mapper, &task1); // Map the application using simulated annealing. This is will optimize our // poor allocation. sa_config = w_create_sa_config(); if (w_assign_sa(&mapper, &sa_config) != E_OK) { printf("ERROR: Assignment failed.\n"); return 1; } w_print_matrix(&mapper.assignment_matrix, "Assignment"); w_print_matrix(&mapper.mapping_matrix, "Mapping"); // Find the ID of all cores assigned to task 1. w_find_in_matrix(&mapper.assignment_matrix, &task1, 1); first_id = task1.elements[0]; last_id = task1.elements[task1.size - 1]; printf("=== Setting initial conditions\n"); init_task1(&device, &task1); printf("=== Loading device program\n"); // Load the device program onto all cores assigned to task 1. if (w_load(&device, &task1, "e_main.srec") != E_OK) { printf("ERROR: Unable to load device program.\n"); return 1; } printf("=== Starting device\n"); e_start_group(&device); printf("=== Starting counter\n"); mailbox.go = 1; w_write(&device, first_id, _MAILBOX_ADDRESS, &mailbox, sizeof(mailbox)); printf("=== Waiting for last core\n"); do { msleep(100); w_read(&device, last_id, _MAILBOX_ADDRESS, &mailbox, sizeof(mailbox)); } while (mailbox.done == 0); printf("Counted to %i (expected %i)\n", mailbox.counter, task1.size - 1); printf("=== Finalizing\n"); w_free_mapper(&mapper); w_free_list(&task1); e_close(&device); e_finalize(); printf("=== Done\n"); return 0; }
felixerdy/circuitpython
supervisor/shared/external_flash/external_flash.c
<reponame>felixerdy/circuitpython /* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2016, 2017 <NAME> for Adafruit Industries * * 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 "supervisor/shared/external_flash/external_flash.h" #include <stdint.h> #include <string.h> #include "supervisor/flash.h" #include "supervisor/spi_flash_api.h" #include "supervisor/shared/external_flash/common_commands.h" #include "extmod/vfs.h" #include "extmod/vfs_fat.h" #include "py/misc.h" #include "py/obj.h" #include "py/runtime.h" #include "lib/oofatfs/ff.h" #include "shared-bindings/microcontroller/__init__.h" #include "supervisor/memory.h" #include "supervisor/shared/rgb_led_status.h" #define NO_SECTOR_LOADED 0xFFFFFFFF // The currently cached sector in the cache, ram or flash based. static uint32_t current_sector; STATIC const external_flash_device possible_devices[] = {EXTERNAL_FLASH_DEVICES}; #define EXTERNAL_FLASH_DEVICE_COUNT MP_ARRAY_SIZE(possible_devices) static const external_flash_device* flash_device = NULL; // Track which blocks (up to 32) in the current sector currently live in the // cache. static uint32_t dirty_mask; static supervisor_allocation* supervisor_cache = NULL; // Wait until both the write enable and write in progress bits have cleared. static bool wait_for_flash_ready(void) { bool ok = true; // Both the write enable and write in progress bits should be low. if (flash_device->no_ready_bit){ // For NVM without a ready bit in status register return ok; } uint8_t read_status_response[1] = {0x00}; do { ok = spi_flash_read_command(CMD_READ_STATUS, read_status_response, 1); } while (ok && (read_status_response[0] & 0x3) != 0); return ok; } // Turn on the write enable bit so we can program and erase the flash. static bool write_enable(void) { return spi_flash_command(CMD_ENABLE_WRITE); } // Read data_length's worth of bytes starting at address into data. static bool read_flash(uint32_t address, uint8_t* data, uint32_t data_length) { if (flash_device == NULL) { return false; } if (!wait_for_flash_ready()) { return false; } return spi_flash_read_data(address, data, data_length); } // Writes data_length's worth of bytes starting at address from data. Assumes // that the sector that address resides in has already been erased. So make sure // to run erase_sector. static bool write_flash(uint32_t address, const uint8_t* data, uint32_t data_length) { if (flash_device == NULL) { return false; } // Don't bother writing if the data is all 1s. Thats equivalent to the flash // state after an erase. if (!flash_device->no_erase_cmd){ // Only do this if the device has an erase command bool all_ones = true; for (uint16_t i = 0; i < data_length; i++) { if (data[i] != 0xff) { all_ones = false; break; } } if (all_ones) { return true; } } for (uint32_t bytes_written = 0; bytes_written < data_length; bytes_written += SPI_FLASH_PAGE_SIZE) { if (!wait_for_flash_ready() || !write_enable()) { return false; } if (!spi_flash_write_data(address + bytes_written, (uint8_t*) data + bytes_written, SPI_FLASH_PAGE_SIZE)) { return false; } } return true; } static bool page_erased(uint32_t sector_address) { // Check the first few bytes to catch the common case where there is data // without using a bunch of memory. if (flash_device->no_erase_cmd){ // skip this if device doesn't have an erase command. return true; } uint8_t short_buffer[4]; if (read_flash(sector_address, short_buffer, 4)) { for (uint16_t i = 0; i < 4; i++) { if (short_buffer[i] != 0xff) { return false; } } } else { return false; } // Now check the full length. uint8_t full_buffer[FILESYSTEM_BLOCK_SIZE]; if (read_flash(sector_address, full_buffer, FILESYSTEM_BLOCK_SIZE)) { for (uint16_t i = 0; i < FILESYSTEM_BLOCK_SIZE; i++) { if (short_buffer[i] != 0xff) { return false; } } } else { return false; } return true; } // Erases the given sector. Make sure you copied all of the data out of it you // need! Also note, sector_address is really 24 bits. static bool erase_sector(uint32_t sector_address) { // Before we erase the sector we need to wait for any writes to finish and // and then enable the write again. if (flash_device->no_erase_cmd){ // skip this if device doesn't have an erase command. return true; } if (!wait_for_flash_ready() || !write_enable()) { return false; } if (flash_device->no_erase_cmd) { return true; } spi_flash_sector_command(CMD_SECTOR_ERASE, sector_address); return true; } // Sector is really 24 bits. static bool copy_block(uint32_t src_address, uint32_t dest_address) { // Copy page by page to minimize RAM buffer. uint16_t page_size = SPI_FLASH_PAGE_SIZE; uint8_t buffer[page_size]; for (uint32_t i = 0; i < FILESYSTEM_BLOCK_SIZE / page_size; i++) { if (!read_flash(src_address + i * page_size, buffer, page_size)) { return false; } if (!write_flash(dest_address + i * page_size, buffer, page_size)) { return false; } } return true; } void supervisor_flash_init(void) { if (flash_device != NULL) { return; } // Delay to give the SPI Flash time to get going. // TODO(tannewt): Only do this when we know power was applied vs a reset. uint16_t max_start_up_delay_us = 0; for (uint8_t i = 0; i < EXTERNAL_FLASH_DEVICE_COUNT; i++) { if (possible_devices[i].start_up_time_us > max_start_up_delay_us) { max_start_up_delay_us = possible_devices[i].start_up_time_us; } } common_hal_mcu_delay_us(max_start_up_delay_us); spi_flash_init(); #ifdef EXTERNAL_FLASH_NO_JEDEC // For NVM that don't have JEDEC response spi_flash_command(CMD_WAKE); for (uint8_t i = 0; i < EXTERNAL_FLASH_DEVICE_COUNT; i++) { const external_flash_device* possible_device = &possible_devices[i]; flash_device = possible_device; break; } #else // The response will be 0xff if the flash needs more time to start up. uint8_t jedec_id_response[3] = {0xff, 0xff, 0xff}; while (jedec_id_response[0] == 0xff) { spi_flash_read_command(CMD_READ_JEDEC_ID, jedec_id_response, 3); } for (uint8_t i = 0; i < EXTERNAL_FLASH_DEVICE_COUNT; i++) { const external_flash_device* possible_device = &possible_devices[i]; if (jedec_id_response[0] == possible_device->manufacturer_id && jedec_id_response[1] == possible_device->memory_type && jedec_id_response[2] == possible_device->capacity) { flash_device = possible_device; break; } } #endif if (flash_device == NULL) { return; } // We don't know what state the flash is in so wait for any remaining writes and then reset. uint8_t read_status_response[1] = {0x00}; // The write in progress bit should be low. do { spi_flash_read_command(CMD_READ_STATUS, read_status_response, 1); } while ((read_status_response[0] & 0x1) != 0); if (!flash_device->single_status_byte) { // The suspended write/erase bit should be low. do { spi_flash_read_command(CMD_READ_STATUS2, read_status_response, 1); } while ((read_status_response[0] & 0x80) != 0); } if (!(flash_device->no_reset_cmd)){ spi_flash_command(CMD_ENABLE_RESET); spi_flash_command(CMD_RESET); } // Wait 30us for the reset common_hal_mcu_delay_us(30); spi_flash_init_device(flash_device); // Activity LED for flash writes. #ifdef MICROPY_HW_LED_MSC gpio_set_pin_function(SPI_FLASH_CS_PIN, GPIO_PIN_FUNCTION_OFF); gpio_set_pin_direction(MICROPY_HW_LED_MSC, GPIO_DIRECTION_OUT); // There's already a pull-up on the board. gpio_set_pin_level(MICROPY_HW_LED_MSC, false); #endif if (flash_device->has_sector_protection) { write_enable(); // Turn off sector protection uint8_t data[1] = {0x00}; spi_flash_write_command(CMD_WRITE_STATUS_BYTE1, data, 1); } // Turn off writes in case this is a microcontroller only reset. spi_flash_command(CMD_DISABLE_WRITE); wait_for_flash_ready(); current_sector = NO_SECTOR_LOADED; dirty_mask = 0; MP_STATE_VM(flash_ram_cache) = NULL; } // The size of each individual block. uint32_t supervisor_flash_get_block_size(void) { return FILESYSTEM_BLOCK_SIZE; } // The total number of available blocks. uint32_t supervisor_flash_get_block_count(void) { // We subtract one erase sector size because we may use it as a staging area // for writes. return (flash_device->total_size - SPI_FLASH_ERASE_SIZE) / FILESYSTEM_BLOCK_SIZE; } // Flush the cache that was written to the scratch portion of flash. Only used // when ram is tight. static bool flush_scratch_flash(void) { if (current_sector == NO_SECTOR_LOADED) { return true; } // First, copy out any blocks that we haven't touched from the sector we've // cached. bool copy_to_scratch_ok = true; uint32_t scratch_sector = flash_device->total_size - SPI_FLASH_ERASE_SIZE; for (uint8_t i = 0; i < SPI_FLASH_ERASE_SIZE / FILESYSTEM_BLOCK_SIZE; i++) { if ((dirty_mask & (1 << i)) == 0) { copy_to_scratch_ok = copy_to_scratch_ok && copy_block(current_sector + i * FILESYSTEM_BLOCK_SIZE, scratch_sector + i * FILESYSTEM_BLOCK_SIZE); } } if (!copy_to_scratch_ok) { // TODO(tannewt): Do more here. We opted to not erase and copy bad data // in. We still risk losing the data written to the scratch sector. return false; } // Second, erase the current sector. erase_sector(current_sector); // Finally, copy the new version into it. for (uint8_t i = 0; i < SPI_FLASH_ERASE_SIZE / FILESYSTEM_BLOCK_SIZE; i++) { copy_block(scratch_sector + i * FILESYSTEM_BLOCK_SIZE, current_sector + i * FILESYSTEM_BLOCK_SIZE); } return true; } // Attempts to allocate a new set of page buffers for caching a full sector in // ram. Each page is allocated separately so that the GC doesn't need to provide // one huge block. We can free it as we write if we want to also. static bool allocate_ram_cache(void) { uint8_t blocks_per_sector = SPI_FLASH_ERASE_SIZE / FILESYSTEM_BLOCK_SIZE; uint8_t pages_per_block = FILESYSTEM_BLOCK_SIZE / SPI_FLASH_PAGE_SIZE; uint32_t table_size = blocks_per_sector * pages_per_block * sizeof(uint32_t); // Attempt to allocate outside the heap first. supervisor_cache = allocate_memory(table_size + SPI_FLASH_ERASE_SIZE, false, false); if (supervisor_cache != NULL) { MP_STATE_VM(flash_ram_cache) = (uint8_t **) supervisor_cache->ptr; uint8_t* page_start = (uint8_t *) supervisor_cache->ptr + table_size; for (uint8_t i = 0; i < blocks_per_sector; i++) { for (uint8_t j = 0; j < pages_per_block; j++) { uint32_t offset = i * pages_per_block + j; MP_STATE_VM(flash_ram_cache)[offset] = page_start + offset * SPI_FLASH_PAGE_SIZE; } } return true; } if (MP_STATE_MEM(gc_pool_start) == 0) { return false; } MP_STATE_VM(flash_ram_cache) = m_malloc_maybe(blocks_per_sector * pages_per_block * sizeof(uint32_t), false); if (MP_STATE_VM(flash_ram_cache) == NULL) { return false; } // Declare i and j outside the loops in case we fail to allocate everything // we need. In that case we'll give it back. uint8_t i = 0; uint8_t j = 0; bool success = true; for (i = 0; i < blocks_per_sector; i++) { for (j = 0; j < pages_per_block; j++) { uint8_t *page_cache = m_malloc_maybe(SPI_FLASH_PAGE_SIZE, false); if (page_cache == NULL) { success = false; break; } MP_STATE_VM(flash_ram_cache)[i * pages_per_block + j] = page_cache; } if (!success) { break; } } // We couldn't allocate enough so give back what we got. if (!success) { // We add 1 so that we delete 0 when i is 1. Going to zero (i >= 0) // would never stop because i is unsigned. i++; for (; i > 0; i--) { for (; j > 0; j--) { m_free(MP_STATE_VM(flash_ram_cache)[(i - 1) * pages_per_block + (j - 1)]); } j = pages_per_block; } m_free(MP_STATE_VM(flash_ram_cache)); MP_STATE_VM(flash_ram_cache) = NULL; } return success; } static void release_ram_cache(void) { if (supervisor_cache != NULL) { free_memory(supervisor_cache); supervisor_cache = NULL; } else if (MP_STATE_MEM(gc_pool_start)) { m_free(MP_STATE_VM(flash_ram_cache)); } MP_STATE_VM(flash_ram_cache) = NULL; } // Flush the cached sector from ram onto the flash. We'll free the cache unless // keep_cache is true. static bool flush_ram_cache(bool keep_cache) { if (current_sector == NO_SECTOR_LOADED) { if (!keep_cache) { release_ram_cache(); } return true; } // First, copy out any blocks that we haven't touched from the sector // we've cached. If we don't do this we'll erase the data during the sector // erase below. bool copy_to_ram_ok = true; uint8_t pages_per_block = FILESYSTEM_BLOCK_SIZE / SPI_FLASH_PAGE_SIZE; for (uint8_t i = 0; i < SPI_FLASH_ERASE_SIZE / FILESYSTEM_BLOCK_SIZE; i++) { if ((dirty_mask & (1 << i)) == 0) { for (uint8_t j = 0; j < pages_per_block; j++) { copy_to_ram_ok = read_flash( current_sector + (i * pages_per_block + j) * SPI_FLASH_PAGE_SIZE, MP_STATE_VM(flash_ram_cache)[i * pages_per_block + j], SPI_FLASH_PAGE_SIZE); if (!copy_to_ram_ok) { break; } } } if (!copy_to_ram_ok) { break; } } if (!copy_to_ram_ok) { return false; } // Second, erase the current sector. erase_sector(current_sector); // Lastly, write all the data in ram that we've cached. for (uint8_t i = 0; i < SPI_FLASH_ERASE_SIZE / FILESYSTEM_BLOCK_SIZE; i++) { for (uint8_t j = 0; j < pages_per_block; j++) { write_flash(current_sector + (i * pages_per_block + j) * SPI_FLASH_PAGE_SIZE, MP_STATE_VM(flash_ram_cache)[i * pages_per_block + j], SPI_FLASH_PAGE_SIZE); if (!keep_cache && supervisor_cache == NULL && MP_STATE_MEM(gc_pool_start)) { m_free(MP_STATE_VM(flash_ram_cache)[i * pages_per_block + j]); } } } // We're done with the cache for now so give it back. if (!keep_cache) { release_ram_cache(); } return true; } // Delegates to the correct flash flush method depending on the existing cache. // TODO Don't blink the status indicator if we don't actually do any writing (hard to tell right now). static void spi_flash_flush_keep_cache(bool keep_cache) { #ifdef MICROPY_HW_LED_MSC port_pin_set_output_level(MICROPY_HW_LED_MSC, true); #endif temp_status_color(ACTIVE_WRITE); // If we've cached to the flash itself flush from there. if (MP_STATE_VM(flash_ram_cache) == NULL) { flush_scratch_flash(); } else { flush_ram_cache(keep_cache); } current_sector = NO_SECTOR_LOADED; clear_temp_status(); #ifdef MICROPY_HW_LED_MSC port_pin_set_output_level(MICROPY_HW_LED_MSC, false); #endif } void supervisor_external_flash_flush(void) { spi_flash_flush_keep_cache(true); } void supervisor_flash_release_cache(void) { spi_flash_flush_keep_cache(false); } static int32_t convert_block_to_flash_addr(uint32_t block) { if (0 <= block && block < supervisor_flash_get_block_count()) { // a block in partition 1 return block * FILESYSTEM_BLOCK_SIZE; } // bad block return -1; } bool external_flash_read_block(uint8_t *dest, uint32_t block) { int32_t address = convert_block_to_flash_addr(block); if (address == -1) { // bad block number return false; } // Mask out the lower bits that designate the address within the sector. uint32_t this_sector = address & (~(SPI_FLASH_ERASE_SIZE - 1)); uint8_t block_index = (address / FILESYSTEM_BLOCK_SIZE) % (SPI_FLASH_ERASE_SIZE / FILESYSTEM_BLOCK_SIZE); uint8_t mask = 1 << (block_index); // We're reading from the currently cached sector. if (current_sector == this_sector && (mask & dirty_mask) > 0) { if (MP_STATE_VM(flash_ram_cache) != NULL) { uint8_t pages_per_block = FILESYSTEM_BLOCK_SIZE / SPI_FLASH_PAGE_SIZE; for (int i = 0; i < pages_per_block; i++) { memcpy(dest + i * SPI_FLASH_PAGE_SIZE, MP_STATE_VM(flash_ram_cache)[block_index * pages_per_block + i], SPI_FLASH_PAGE_SIZE); } return true; } else { uint32_t scratch_address = flash_device->total_size - SPI_FLASH_ERASE_SIZE + block_index * FILESYSTEM_BLOCK_SIZE; return read_flash(scratch_address, dest, FILESYSTEM_BLOCK_SIZE); } } return read_flash(address, dest, FILESYSTEM_BLOCK_SIZE); } bool external_flash_write_block(const uint8_t *data, uint32_t block) { // Non-MBR block, copy to cache int32_t address = convert_block_to_flash_addr(block); if (address == -1) { // bad block number return false; } // Wait for any previous writes to finish. wait_for_flash_ready(); // Mask out the lower bits that designate the address within the sector. uint32_t this_sector = address & (~(SPI_FLASH_ERASE_SIZE - 1)); uint8_t block_index = (address / FILESYSTEM_BLOCK_SIZE) % (SPI_FLASH_ERASE_SIZE / FILESYSTEM_BLOCK_SIZE); uint8_t mask = 1 << (block_index); // Flush the cache if we're moving onto a sector or we're writing the // same block again. if (current_sector != this_sector || (mask & dirty_mask) > 0) { // Check to see if we'd write to an erased page. In that case we // can write directly. if (page_erased(address)) { return write_flash(address, data, FILESYSTEM_BLOCK_SIZE); } if (current_sector != NO_SECTOR_LOADED) { supervisor_flash_flush(); } if (MP_STATE_VM(flash_ram_cache) == NULL && !allocate_ram_cache()) { erase_sector(flash_device->total_size - SPI_FLASH_ERASE_SIZE); wait_for_flash_ready(); } current_sector = this_sector; dirty_mask = 0; } dirty_mask |= mask; // Copy the block to the appropriate cache. if (MP_STATE_VM(flash_ram_cache) != NULL) { uint8_t pages_per_block = FILESYSTEM_BLOCK_SIZE / SPI_FLASH_PAGE_SIZE; for (int i = 0; i < pages_per_block; i++) { memcpy(MP_STATE_VM(flash_ram_cache)[block_index * pages_per_block + i], data + i * SPI_FLASH_PAGE_SIZE, SPI_FLASH_PAGE_SIZE); } return true; } else { uint32_t scratch_address = flash_device->total_size - SPI_FLASH_ERASE_SIZE + block_index * FILESYSTEM_BLOCK_SIZE; return write_flash(scratch_address, data, FILESYSTEM_BLOCK_SIZE); } } mp_uint_t supervisor_flash_read_blocks(uint8_t *dest, uint32_t block_num, uint32_t num_blocks) { for (size_t i = 0; i < num_blocks; i++) { if (!external_flash_read_block(dest + i * FILESYSTEM_BLOCK_SIZE, block_num + i)) { return 1; // error } } return 0; // success } mp_uint_t supervisor_flash_write_blocks(const uint8_t *src, uint32_t block_num, uint32_t num_blocks) { for (size_t i = 0; i < num_blocks; i++) { if (!external_flash_write_block(src + i * FILESYSTEM_BLOCK_SIZE, block_num + i)) { return 1; // error } } return 0; // success }
felixerdy/circuitpython
ports/raspberrypi/common-hal/nvm/ByteArray.c
/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2020 microDev * * 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 "common-hal/nvm/ByteArray.h" #include <string.h> #include "py/runtime.h" #include "src/rp2_common/hardware_flash/include/hardware/flash.h" extern uint32_t __flash_binary_start; static const uint32_t flash_binary_start = (uint32_t) &__flash_binary_start; #define RMV_OFFSET(addr) addr - flash_binary_start uint32_t common_hal_nvm_bytearray_get_length(nvm_bytearray_obj_t* self) { return self->len; } static void write_page(uint32_t page_addr, uint32_t offset, uint32_t len, uint8_t* bytes) { // Write a whole page to flash, buffering it first and then erasing and rewriting it // since we can only write a whole page at a time. if (offset == 0 && len == FLASH_PAGE_SIZE) { flash_range_program(RMV_OFFSET(page_addr), bytes, FLASH_PAGE_SIZE); } else { uint8_t buffer[FLASH_PAGE_SIZE]; memcpy(buffer, (uint8_t*) page_addr, FLASH_PAGE_SIZE); memcpy(buffer + offset, bytes, len); flash_range_program(RMV_OFFSET(page_addr), buffer, FLASH_PAGE_SIZE); } } static void erase_and_write_sector(uint32_t address, uint32_t len, uint8_t* bytes) { // Write a whole sector to flash, buffering it first and then erasing and rewriting it // since we can only erase a whole sector at a time. uint8_t buffer[FLASH_SECTOR_SIZE]; memcpy(buffer, (uint8_t*) CIRCUITPY_INTERNAL_NVM_START_ADDR, FLASH_SECTOR_SIZE); memcpy(buffer + address, bytes, len); flash_range_erase(RMV_OFFSET(CIRCUITPY_INTERNAL_NVM_START_ADDR), FLASH_SECTOR_SIZE); flash_range_program(RMV_OFFSET(CIRCUITPY_INTERNAL_NVM_START_ADDR), buffer, FLASH_SECTOR_SIZE); } void common_hal_nvm_bytearray_get_bytes(nvm_bytearray_obj_t* self, uint32_t start_index, uint32_t len, uint8_t* values) { memcpy(values, self->start_address + start_index, len); } bool common_hal_nvm_bytearray_set_bytes(nvm_bytearray_obj_t* self, uint32_t start_index, uint8_t* values, uint32_t len) { uint8_t values_in[len]; common_hal_nvm_bytearray_get_bytes(self, start_index, len, values_in); bool all_ones = true; for (uint32_t i = 0; i < len; i++) { if (values_in[i] != UINT8_MAX) { all_ones = false; break; } } if (all_ones) { uint32_t address = (uint32_t) self->start_address + start_index; uint32_t offset = address % FLASH_PAGE_SIZE; uint32_t page_addr = address - offset; while (len) { uint32_t write_len = MIN(len, FLASH_PAGE_SIZE - offset); write_page(page_addr, offset, write_len, values); len -= write_len; values += write_len; page_addr += FLASH_PAGE_SIZE; offset = 0; } } else { erase_and_write_sector(start_index, len, values); } return true; }
felixerdy/circuitpython
shared-bindings/bitmaptools/__init__.c
<reponame>felixerdy/circuitpython /* * This file is part of the Micro Python project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2021 <NAME> * * 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 "shared-bindings/displayio/Bitmap.h" #include "shared-bindings/bitmaptools/__init__.h" #include <stdint.h> #include "py/obj.h" #include "py/runtime.h" //| """Collection of bitmap manipulation tools""" //| STATIC int16_t validate_point(mp_obj_t point, int16_t default_value) { // Checks if point is None and returns default_value, otherwise decodes integer value if ( point == mp_const_none ) { return default_value; } return mp_obj_get_int(point); } STATIC void extract_tuple(mp_obj_t xy_tuple, int16_t *x, int16_t *y, int16_t x_default, int16_t y_default) { // Helper function for rotozoom // Extract x,y values from a tuple or default if None if ( xy_tuple == mp_const_none ) { *x = x_default; *y = y_default; } else if ( !MP_OBJ_IS_OBJ(xy_tuple) ) { mp_raise_ValueError(translate("clip point must be (x,y) tuple")); } else { mp_obj_t* items; mp_obj_get_array_fixed_n(xy_tuple, 2, &items); *x = mp_obj_get_int(items[0]); *y = mp_obj_get_int(items[1]); } } STATIC void validate_clip_region(displayio_bitmap_t *bitmap, mp_obj_t clip0_tuple, int16_t *clip0_x, int16_t *clip0_y, mp_obj_t clip1_tuple, int16_t *clip1_x, int16_t *clip1_y) { // Helper function for rotozoom // 1. Extract the clip x,y points from the two clip tuples // 2. Rearrange values such that clip0_ < clip1_ // 3. Constrain the clip points to within the bitmap extract_tuple(clip0_tuple, clip0_x, clip0_y, 0, 0); extract_tuple(clip1_tuple, clip1_x, clip1_y, bitmap->width, bitmap->height); // Ensure the value for clip0 is less than clip1 (for both x and y) if ( *clip0_x > *clip1_x ) { int16_t temp_value = *clip0_x; // swap values *clip0_x = *clip1_x; *clip1_x = temp_value; } if ( *clip0_y > *clip1_y ) { int16_t temp_value = *clip0_y; // swap values *clip0_y = *clip1_y; *clip1_y = temp_value; } // Constrain the clip window to within the bitmap boundaries if (*clip0_x < 0) { *clip0_x = 0; } if (*clip0_y < 0) { *clip0_y = 0; } if (*clip0_x > bitmap->width) { *clip0_x = bitmap->width; } if (*clip0_y > bitmap->height) { *clip0_y = bitmap->height; } if (*clip1_x < 0) { *clip1_x = 0; } if (*clip1_y < 0) { *clip1_y = 0; } if (*clip1_x > bitmap->width) { *clip1_x = bitmap->width; } if (*clip1_y > bitmap->height) { *clip1_y = bitmap->height; } } //| //| def rotozoom( //| dest_bitmap: displayio.Bitmap, source_bitmap: displayio.Bitmap, //| *, //| ox: int, oy: int, dest_clip0: Tuple[int, int], dest_clip1: Tuple[int, int], //| px: int, py: int, source_clip0: Tuple[int, int], source_clip1: Tuple[int, int], //| angle: float, scale: float, skip_index: int) -> None: //| """Inserts the source bitmap region into the destination bitmap with rotation //| (angle), scale and clipping (both on source and destination bitmaps). //| //| :param bitmap dest_bitmap: Destination bitmap that will be copied into //| :param bitmap source_bitmap: Source bitmap that contains the graphical region to be copied //| :param int ox: Horizontal pixel location in destination bitmap where source bitmap //| point (px,py) is placed //| :param int oy: Vertical pixel location in destination bitmap where source bitmap //| point (px,py) is placed //| :param Tuple[int,int] dest_clip0: First corner of rectangular destination clipping //| region that constrains region of writing into destination bitmap //| :param Tuple[int,int] dest_clip1: Second corner of rectangular destination clipping //| region that constrains region of writing into destination bitmap //| :param int px: Horizontal pixel location in source bitmap that is placed into the //| destination bitmap at (ox,oy) //| :param int py: Vertical pixel location in source bitmap that is placed into the //| destination bitmap at (ox,oy) //| :param Tuple[int,int] source_clip0: First corner of rectangular source clipping //| region that constrains region of reading from the source bitmap //| :param Tuple[int,int] source_clip1: Second corner of rectangular source clipping //| region that constrains region of reading from the source bitmap //| :param float angle: Angle of rotation, in radians (positive is clockwise direction) //| :param float scale: Scaling factor //| :param int skip_index: Bitmap palette index in the source that will not be copied, //| set to None to copy all pixels""" //| ... //| STATIC mp_obj_t bitmaptools_obj_rotozoom(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args){ enum {ARG_dest_bitmap, ARG_source_bitmap, ARG_ox, ARG_oy, ARG_dest_clip0, ARG_dest_clip1, ARG_px, ARG_py, ARG_source_clip0, ARG_source_clip1, ARG_angle, ARG_scale, ARG_skip_index}; static const mp_arg_t allowed_args[] = { {MP_QSTR_dest_bitmap, MP_ARG_REQUIRED | MP_ARG_OBJ}, {MP_QSTR_source_bitmap, MP_ARG_REQUIRED | MP_ARG_OBJ}, {MP_QSTR_ox, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, // None convert to destination->width / 2 {MP_QSTR_oy, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, // None convert to destination->height / 2 {MP_QSTR_dest_clip0, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, {MP_QSTR_dest_clip1, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, {MP_QSTR_px, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, // None convert to source->width / 2 {MP_QSTR_py, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, // None convert to source->height / 2 {MP_QSTR_source_clip0, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, {MP_QSTR_source_clip1, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, {MP_QSTR_angle, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, // None convert to 0.0 {MP_QSTR_scale, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, // None convert to 1.0 {MP_QSTR_skip_index, MP_ARG_OBJ | MP_ARG_KW_ONLY, {.u_obj=mp_const_none} }, }; mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); displayio_bitmap_t *destination = MP_OBJ_TO_PTR(args[ARG_dest_bitmap].u_obj); // the destination bitmap displayio_bitmap_t *source = MP_OBJ_TO_PTR(args[ARG_source_bitmap].u_obj); // the source bitmap // ensure that the destination bitmap has at least as many `bits_per_value` as the source if (destination->bits_per_value < source->bits_per_value) { mp_raise_ValueError(translate("source palette too large")); } // Confirm the destination location target (ox,oy); if None, default to bitmap midpoint int16_t ox, oy; ox = validate_point(args[ARG_ox].u_obj, destination->width / 2); oy = validate_point(args[ARG_oy].u_obj, destination->height / 2); // Confirm the source location target (px,py); if None, default to bitmap midpoint int16_t px, py; px = validate_point(args[ARG_px].u_obj, source->width / 2); py = validate_point(args[ARG_py].u_obj, source->height / 2); // Validate the clipping regions for the destination bitmap int16_t dest_clip0_x, dest_clip0_y, dest_clip1_x, dest_clip1_y; validate_clip_region(destination, args[ARG_dest_clip0].u_obj, &dest_clip0_x, &dest_clip0_y, args[ARG_dest_clip1].u_obj, &dest_clip1_x, &dest_clip1_y); // Validate the clipping regions for the source bitmap int16_t source_clip0_x, source_clip0_y, source_clip1_x, source_clip1_y; validate_clip_region(source, args[ARG_source_clip0].u_obj, &source_clip0_x, &source_clip0_y, args[ARG_source_clip1].u_obj, &source_clip1_x, &source_clip1_y); // Confirm the angle value float angle=0.0; if ( args[ARG_angle].u_obj != mp_const_none ) { angle = mp_obj_get_float(args[ARG_angle].u_obj); } // Confirm the scale value float scale=1.0; if ( args[ARG_scale].u_obj != mp_const_none ) { scale = mp_obj_get_float(args[ARG_scale].u_obj); } if (scale < 0) { // ensure scale >= 0 scale = 1.0; } uint32_t skip_index; bool skip_index_none; // Flag whether input skip_value was None if (args[ARG_skip_index].u_obj == mp_const_none ) { skip_index = 0; skip_index_none = true; } else { skip_index = mp_obj_get_int(args[ARG_skip_index].u_obj); skip_index_none = false; } common_hal_bitmaptools_rotozoom(destination, ox, oy, dest_clip0_x, dest_clip0_y, dest_clip1_x, dest_clip1_y, source, px, py, source_clip0_x, source_clip0_y, source_clip1_x, source_clip1_y, angle, scale, skip_index, skip_index_none); return mp_const_none; } MP_DEFINE_CONST_FUN_OBJ_KW(bitmaptools_rotozoom_obj, 0, bitmaptools_obj_rotozoom); // requires at least 2 arguments (destination bitmap and source bitmap) STATIC const mp_rom_map_elem_t bitmaptools_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_rotozoom), MP_ROM_PTR(&bitmaptools_rotozoom_obj) }, }; STATIC MP_DEFINE_CONST_DICT(bitmaptools_module_globals, bitmaptools_module_globals_table); const mp_obj_module_t bitmaptools_module = { .base = {&mp_type_module }, .globals = (mp_obj_dict_t*)&bitmaptools_module_globals, };
felixerdy/circuitpython
ports/raspberrypi/boards/pimoroni_tiny2040/mpconfigboard.h
<filename>ports/raspberrypi/boards/pimoroni_tiny2040/mpconfigboard.h<gh_stars>0 #define MICROPY_HW_BOARD_NAME "Pimoroni Tiny 2040" #define MICROPY_HW_MCU_NAME "rp2040" #define MICROPY_HW_LED_R (&pin_GPIO18) #define MICROPY_HW_LED_G (&pin_GPIO19) #define MICROPY_HW_LED_B (&pin_GPIO20) #define MICROPY_HW_USER_SW (&pin_GPIO23) #define TOTAL_FLASH_SIZE (8 * 1024 * 1024) // These pins are unconnected #define IGNORE_PIN_GPIO8 1 #define IGNORE_PIN_GPIO9 1 #define IGNORE_PIN_GPIO10 1 #define IGNORE_PIN_GPIO11 1 #define IGNORE_PIN_GPIO12 1 #define IGNORE_PIN_GPIO13 1 #define IGNORE_PIN_GPIO14 1 #define IGNORE_PIN_GPIO15 1 #define IGNORE_PIN_GPIO16 1 #define IGNORE_PIN_GPIO17 1 #define IGNORE_PIN_GPIO21 1 #define IGNORE_PIN_GPIO22 1 #define IGNORE_PIN_GPIO24 1 #define IGNORE_PIN_GPIO25 1
felixerdy/circuitpython
shared-module/bitops/__init__.c
<reponame>felixerdy/circuitpython<gh_stars>0 /* * This file is part of the Circuit Python project, https://github.com/adafruit/circuitpython * * The MIT License (MIT) * * Copyright (c) 2021 <NAME> for Adafruit Industries * * 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 "shared-bindings/bitops/__init__.h" #include <stdint.h> #include <stdlib.h> #include <string.h> #ifdef __GNUC__ #define FALLTHROUGH __attribute__((fallthrough)) #else #define FALLTHROUGH ((void)0) /* FALLTHROUGH */ #endif // adapted from "Hacker's Delight" - Figure 7-2 Transposing an 8x8-bit matrix // basic idea is: // > First, treat the 8x8-bit matrix as 16 2x2-bit matrices, and transpose each // > of the 16 2x2-bit matrices. Second, treat the matrix as four 2x2 submatrices // > whose elements are 2x2-bit matrices and transpose each of the four 2x2 // > submatrices. Finally, treat the matrix as a 2x2 matrix whose elements are // > 4x4-bit matrices, and transpose the 2x2 matrix. These transformations are // > illustrated below. // We want a different definition of bit/byte order, deal with strides differently, etc. // so the code is heavily re-worked compared to the original. static void transpose_var(uint32_t *result, const uint8_t *src, int src_stride, int num_strands) { uint32_t x = 0, y = 0, t; src += (num_strands-1) * src_stride; switch(num_strands) { case 7: x |= *src << 16; src -= src_stride; FALLTHROUGH; case 6: x |= *src << 8; src -= src_stride; FALLTHROUGH; case 5: x |= *src; src -= src_stride; FALLTHROUGH; case 4: y |= *src << 24; src -= src_stride; FALLTHROUGH; case 3: y |= *src << 16; src -= src_stride; FALLTHROUGH; case 2: y |= *src << 8; src -= src_stride; y |= *src; } t = (x ^ (x >> 7)) & 0x00AA00AA; x = x ^ t ^ (t << 7); t = (y ^ (y >> 7)) & 0x00AA00AA; y = y ^ t ^ (t << 7); t = (x ^ (x >>14)) & 0x0000CCCC; x = x ^ t ^ (t <<14); t = (y ^ (y >>14)) & 0x0000CCCC; y = y ^ t ^ (t <<14); t = (x & 0xF0F0F0F0) | ((y >> 4) & 0x0F0F0F0F); y = ((x << 4) & 0xF0F0F0F0) | (y & 0x0F0F0F0F); x = t; #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ x = __builtin_bswap32(x); y = __builtin_bswap32(y); #endif result[0] = x; result[1] = y; } static void transpose_8(uint32_t *result, const uint8_t *src, int src_stride) { uint32_t x, y, t; y = *src; src += src_stride; y |= (*src << 8); src += src_stride; y |= (*src << 16); src += src_stride; y |= (*src << 24); src += src_stride; x = *src; src += src_stride; x |= (*src << 8); src += src_stride; x |= (*src << 16); src += src_stride; x |= (*src << 24); src += src_stride; t = (x ^ (x >> 7)) & 0x00AA00AA; x = x ^ t ^ (t << 7); t = (y ^ (y >> 7)) & 0x00AA00AA; y = y ^ t ^ (t << 7); t = (x ^ (x >>14)) & 0x0000CCCC; x = x ^ t ^ (t <<14); t = (y ^ (y >>14)) & 0x0000CCCC; y = y ^ t ^ (t <<14); t = (x & 0xF0F0F0F0) | ((y >> 4) & 0x0F0F0F0F); y = ((x << 4) & 0xF0F0F0F0) | (y & 0x0F0F0F0F); x = t; #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ x = __builtin_bswap32(x); y = __builtin_bswap32(y); #endif result[0] = x; result[1] = y; } static void bit_transpose_8(uint32_t *result, const uint8_t *src, size_t src_stride, size_t n) { for(size_t i=0; i<n; i++) { transpose_8(result, src, src_stride); result += 2; src += 1; } } static void bit_transpose_var(uint32_t *result, const uint8_t *src, size_t src_stride, size_t n, int num_strands) { for(size_t i=0; i<n; i++) { transpose_var(result, src, src_stride, num_strands); result += 2; src += 1; } } void common_hal_bitops_bit_transpose(uint8_t *result, const uint8_t *src, size_t inlen, size_t num_strands) { if(num_strands == 8) { bit_transpose_8((uint32_t*)(void*)result, src, inlen/8, inlen/8); } else { bit_transpose_var((uint32_t*)(void*)result, src, inlen/num_strands, inlen/num_strands, num_strands); } }
felixerdy/circuitpython
ports/raspberrypi/common-hal/audiobusio/I2SOut.c
<reponame>felixerdy/circuitpython /* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2021 <NAME> for Adafruit Industries * * 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 <stdint.h> #include <string.h> #include "mpconfigport.h" #include "py/gc.h" #include "py/mperrno.h" #include "py/runtime.h" #include "common-hal/audiobusio/I2SOut.h" #include "shared-bindings/audiobusio/I2SOut.h" #include "shared-bindings/microcontroller/Pin.h" #include "shared-module/audiocore/__init__.h" #include "bindings/rp2pio/StateMachine.h" #include "supervisor/shared/translate.h" const uint16_t i2s_program[] = { // ; Load the next set of samples // ; /--- LRCLK // ; |/-- BCLK // ; || // pull noblock side 0b01 ; Loads OSR with the next FIFO value or X 0x8880, // mov x osr side 0b01 ; Save the new value in case we need it again 0xa827, // set y 14 side 0b01 0xe84e, // bitloop1: // out pins 1 side 0b00 [2] 0x6201, // jmp y-- bitloop1 side 0b01 [2] 0x0a83, // out pins 1 side 0b10 [2] 0x7201, // set y 14 side 0b11 [2] 0xfa4e, // bitloop0: // out pins 1 side 0b10 [2] 0x7201, // jmp y-- bitloop0 side 0b11 [2] 0x1a87, // out pins 1 side 0b00 [2] 0x6201 }; const uint16_t i2s_program_left_justified[] = { // ; Load the next set of samples // ; /--- LRCLK // ; |/-- BCLK // ; || // pull noblock side 0b11 ; Loads OSR with the next FIFO value or X 0x9880, // mov x osr side 0b11 ; Save the new value in case we need it again 0xb827, // set y 14 side 0b11 0xf84e, // bitloop1: // out pins 1 side 0b00 [2] 0x6201, // jmp y-- bitloop1 side 0b01 [2] 0x0a83, // out pins 1 side 0b10 [2] 0x6201, // set y 14 side 0b01 [2] 0xea4e, // bitloop0: // out pins 1 side 0b10 [2] 0x7201, // jmp y-- bitloop0 side 0b11 [2] 0x1a87, // out pins 1 side 0b10 [2] 0x7201 }; void i2sout_reset(void) { } // Caller validates that pins are free. void common_hal_audiobusio_i2sout_construct(audiobusio_i2sout_obj_t* self, const mcu_pin_obj_t* bit_clock, const mcu_pin_obj_t* word_select, const mcu_pin_obj_t* data, bool left_justified) { if (bit_clock->number != word_select->number - 1) { mp_raise_ValueError(translate("Bit clock and word select must be sequential pins")); } const uint16_t* program = i2s_program; size_t program_len = sizeof(i2s_program) / sizeof(i2s_program[0]); if (left_justified) { program = i2s_program_left_justified; program_len = sizeof(i2s_program_left_justified) / sizeof(i2s_program_left_justified[0]);; } // Use the state machine to manage pins. common_hal_rp2pio_statemachine_construct(&self->state_machine, program, program_len, 44100 * 32 * 6, // Clock at 44.1 khz to warm the DAC up. NULL, 0, data, 1, 0, 0xffffffff, // out pin NULL, 0, // in pins 0, 0, // in pulls NULL, 0, 0, 0x1f, // set pins bit_clock, 2, 0, 0x1f, // sideset pins true, // exclusive pin use false, 32, false, // shift out left to start with MSB false, // Wait for txstall false, 32, false); // in settings self->playing = false; audio_dma_init(&self->dma); } bool common_hal_audiobusio_i2sout_deinited(audiobusio_i2sout_obj_t* self) { return common_hal_rp2pio_statemachine_deinited(&self->state_machine); } void common_hal_audiobusio_i2sout_deinit(audiobusio_i2sout_obj_t* self) { if (common_hal_audiobusio_i2sout_deinited(self)) { return; } common_hal_rp2pio_statemachine_deinit(&self->state_machine); } void common_hal_audiobusio_i2sout_play(audiobusio_i2sout_obj_t* self, mp_obj_t sample, bool loop) { if (common_hal_audiobusio_i2sout_get_playing(self)) { common_hal_audiobusio_i2sout_stop(self); } uint8_t bits_per_sample = audiosample_bits_per_sample(sample); // Make sure we transmit a minimum of 16 bits. // TODO: Maybe we need an intermediate object to upsample instead. This is // only needed for some I2S devices that expect at least 8. if (bits_per_sample < 16) { bits_per_sample = 16; } // We always output stereo so output twice as many bits. uint16_t bits_per_sample_output = bits_per_sample * 2; size_t clocks_per_bit = 6; uint32_t frequency = bits_per_sample_output * audiosample_sample_rate(sample); common_hal_rp2pio_statemachine_set_frequency(&self->state_machine, clocks_per_bit * frequency); common_hal_rp2pio_statemachine_restart(&self->state_machine); uint8_t channel_count = audiosample_channel_count(sample); if (channel_count > 2) { mp_raise_ValueError(translate("Too many channels in sample.")); } audio_dma_result result = audio_dma_setup_playback( &self->dma, sample, loop, false, // single channel 0, // audio channel true, // output signed bits_per_sample, (uint32_t) &self->state_machine.pio->txf[self->state_machine.state_machine], // output register self->state_machine.tx_dreq); // data request line if (result == AUDIO_DMA_DMA_BUSY) { common_hal_audiobusio_i2sout_stop(self); mp_raise_RuntimeError(translate("No DMA channel found")); } else if (result == AUDIO_DMA_MEMORY_ERROR) { common_hal_audiobusio_i2sout_stop(self); mp_raise_RuntimeError(translate("Unable to allocate buffers for signed conversion")); } // Turn on the state machine's clock. self->playing = true; } void common_hal_audiobusio_i2sout_pause(audiobusio_i2sout_obj_t* self) { audio_dma_pause(&self->dma); } void common_hal_audiobusio_i2sout_resume(audiobusio_i2sout_obj_t* self) { // Maybe: Clear any overrun/underrun errors audio_dma_resume(&self->dma); } bool common_hal_audiobusio_i2sout_get_paused(audiobusio_i2sout_obj_t* self) { return audio_dma_get_paused(&self->dma); } void common_hal_audiobusio_i2sout_stop(audiobusio_i2sout_obj_t* self) { audio_dma_stop(&self->dma); common_hal_rp2pio_statemachine_stop(&self->state_machine); self->playing = false; } bool common_hal_audiobusio_i2sout_get_playing(audiobusio_i2sout_obj_t* self) { bool playing = audio_dma_get_playing(&self->dma); if (!playing && self->playing) { common_hal_audiobusio_i2sout_stop(self); } return playing; }
felixerdy/circuitpython
ports/raspberrypi/boards/adafruit_feather_rp2040/mpconfigboard.h
#define MICROPY_HW_BOARD_NAME "Adafruit Feather RP2040" #define MICROPY_HW_MCU_NAME "rp2040" #define MICROPY_HW_NEOPIXEL (&pin_GPIO16) #define DEFAULT_I2C_BUS_SCL (&pin_GPIO3) #define DEFAULT_I2C_BUS_SDA (&pin_GPIO2) #define DEFAULT_SPI_BUS_SCK (&pin_GPIO18) #define DEFAULT_SPI_BUS_MOSI (&pin_GPIO19) #define DEFAULT_SPI_BUS_MISO (&pin_GPIO20) #define DEFAULT_UART_BUS_RX (&pin_GPIO1) #define DEFAULT_UART_BUS_TX (&pin_GPIO0) // Flash chip is GD25Q64 connected over QSPI #define TOTAL_FLASH_SIZE (8 * 1024 * 1024)
felixerdy/circuitpython
shared-module/displayio/TileGrid.c
/* * This file is part of the Micro Python project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2018 <NAME> for Adafruit Industries * * 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 "shared-bindings/displayio/TileGrid.h" #include "py/runtime.h" #include "shared-bindings/displayio/Bitmap.h" #include "shared-bindings/displayio/ColorConverter.h" #include "shared-bindings/displayio/OnDiskBitmap.h" #include "shared-bindings/displayio/Palette.h" #include "shared-bindings/displayio/Shape.h" void common_hal_displayio_tilegrid_construct(displayio_tilegrid_t *self, mp_obj_t bitmap, uint16_t bitmap_width_in_tiles, uint16_t bitmap_height_in_tiles, mp_obj_t pixel_shader, uint16_t width, uint16_t height, uint16_t tile_width, uint16_t tile_height, uint16_t x, uint16_t y, uint8_t default_tile) { uint32_t total_tiles = width * height; // Sprites will only have one tile so save a little memory by inlining values in the pointer. uint8_t inline_tiles = sizeof(uint8_t*); if (total_tiles <= inline_tiles) { self->tiles = 0; // Pack values into the pointer since there are only a few. for (uint32_t i = 0; i < inline_tiles; i++) { ((uint8_t*) &self->tiles)[i] = default_tile; } self->inline_tiles = true; } else { self->tiles = (uint8_t*) m_malloc(total_tiles, false); for (uint32_t i = 0; i < total_tiles; i++) { self->tiles[i] = default_tile; } self->inline_tiles = false; } self->bitmap_width_in_tiles = bitmap_width_in_tiles; self->tiles_in_bitmap = bitmap_width_in_tiles * bitmap_height_in_tiles; self->width_in_tiles = width; self->height_in_tiles = height; self->x = x; self->y = y; self->pixel_width = width * tile_width; self->pixel_height = height * tile_height; self->tile_width = tile_width; self->tile_height = tile_height; self->bitmap = bitmap; self->pixel_shader = pixel_shader; self->in_group = false; self->hidden = false; self->hidden_by_parent = false; self->previous_area.x1 = 0xffff; self->previous_area.x2 = self->previous_area.x1; self->flip_x = false; self->flip_y = false; self->transpose_xy = false; self->absolute_transform = NULL; } bool common_hal_displayio_tilegrid_get_hidden(displayio_tilegrid_t* self) { return self->hidden; } void common_hal_displayio_tilegrid_set_hidden(displayio_tilegrid_t* self, bool hidden) { self->hidden = hidden; if(!hidden){ self->full_change = true; } } void displayio_tilegrid_set_hidden_by_parent(displayio_tilegrid_t *self, bool hidden) { self->hidden_by_parent = hidden; if(!hidden){ self->full_change = true; } } bool displayio_tilegrid_get_previous_area(displayio_tilegrid_t *self, displayio_area_t* area) { if (self->previous_area.x1 == self->previous_area.x2) { return false; } displayio_area_copy(&self->previous_area, area); return true; } void _update_current_x(displayio_tilegrid_t *self) { uint16_t width; if (self->transpose_xy) { width = self->pixel_height; } else { width = self->pixel_width; } // If there's no transform, substitute an identity transform so the calculations will work. const displayio_buffer_transform_t* absolute_transform = self->absolute_transform == NULL ? &null_transform : self->absolute_transform; if (absolute_transform->transpose_xy) { self->current_area.y1 = absolute_transform->y + absolute_transform->dy * self->x; self->current_area.y2 = absolute_transform->y + absolute_transform->dy * (self->x + width); if (self->current_area.y2 < self->current_area.y1) { int16_t temp = self->current_area.y2; self->current_area.y2 = self->current_area.y1; self->current_area.y1 = temp; } } else { self->current_area.x1 = absolute_transform->x + absolute_transform->dx * self->x; self->current_area.x2 = absolute_transform->x + absolute_transform->dx * (self->x + width); if (self->current_area.x2 < self->current_area.x1) { int16_t temp = self->current_area.x2; self->current_area.x2 = self->current_area.x1; self->current_area.x1 = temp; } } } void _update_current_y(displayio_tilegrid_t *self) { uint16_t height; if (self->transpose_xy) { height = self->pixel_width; } else { height = self->pixel_height; } // If there's no transform, substitute an identity transform so the calculations will work. const displayio_buffer_transform_t* absolute_transform = self->absolute_transform == NULL ? &null_transform : self->absolute_transform; if (absolute_transform->transpose_xy) { self->current_area.x1 = absolute_transform->x + absolute_transform->dx * self->y; self->current_area.x2 = absolute_transform->x + absolute_transform->dx * (self->y + height); if (self->current_area.x2 < self->current_area.x1) { int16_t temp = self->current_area.x2; self->current_area.x2 = self->current_area.x1; self->current_area.x1 = temp; } } else { self->current_area.y1 = absolute_transform->y + absolute_transform->dy * self->y; self->current_area.y2 = absolute_transform->y + absolute_transform->dy * (self->y + height); if (self->current_area.y2 < self->current_area.y1) { int16_t temp = self->current_area.y2; self->current_area.y2 = self->current_area.y1; self->current_area.y1 = temp; } } } void displayio_tilegrid_update_transform(displayio_tilegrid_t *self, const displayio_buffer_transform_t* absolute_transform) { self->in_group = absolute_transform != NULL; self->absolute_transform = absolute_transform; if (absolute_transform != NULL) { self->moved = true; _update_current_x(self); _update_current_y(self); } } mp_int_t common_hal_displayio_tilegrid_get_x(displayio_tilegrid_t *self) { return self->x; } void common_hal_displayio_tilegrid_set_x(displayio_tilegrid_t *self, mp_int_t x) { if (self->x == x) { return; } self->moved = true; self->x = x; if (self->absolute_transform != NULL) { _update_current_x(self); } } mp_int_t common_hal_displayio_tilegrid_get_y(displayio_tilegrid_t *self) { return self->y; } void common_hal_displayio_tilegrid_set_y(displayio_tilegrid_t *self, mp_int_t y) { if (self->y == y) { return; } self->moved = true; self->y = y; if (self->absolute_transform != NULL) { _update_current_y(self); } } mp_obj_t common_hal_displayio_tilegrid_get_pixel_shader(displayio_tilegrid_t *self) { return self->pixel_shader; } void common_hal_displayio_tilegrid_set_pixel_shader(displayio_tilegrid_t *self, mp_obj_t pixel_shader) { self->pixel_shader = pixel_shader; self->full_change = true; } uint16_t common_hal_displayio_tilegrid_get_width(displayio_tilegrid_t *self) { return self->width_in_tiles; } uint16_t common_hal_displayio_tilegrid_get_height(displayio_tilegrid_t *self) { return self->height_in_tiles; } uint8_t common_hal_displayio_tilegrid_get_tile(displayio_tilegrid_t *self, uint16_t x, uint16_t y) { uint8_t* tiles = self->tiles; if (self->inline_tiles) { tiles = (uint8_t*) &self->tiles; } if (tiles == NULL) { return 0; } return tiles[y * self->width_in_tiles + x]; } void common_hal_displayio_tilegrid_set_tile(displayio_tilegrid_t *self, uint16_t x, uint16_t y, uint8_t tile_index) { if (tile_index >= self->tiles_in_bitmap) { mp_raise_ValueError(translate("Tile index out of bounds")); } uint8_t* tiles = self->tiles; if (self->inline_tiles) { tiles = (uint8_t*) &self->tiles; } if (tiles == NULL) { return; } tiles[y * self->width_in_tiles + x] = tile_index; displayio_area_t temp_area; displayio_area_t* tile_area; if (!self->partial_change) { tile_area = &self->dirty_area; } else { tile_area = &temp_area; } int16_t tx = (x - self->top_left_x) % self->width_in_tiles; if (tx < 0) { tx += self->width_in_tiles; } tile_area->x1 = tx * self->tile_width; tile_area->x2 = tile_area->x1 + self->tile_width; int16_t ty = (y - self->top_left_y) % self->height_in_tiles; if (ty < 0) { ty += self->height_in_tiles; } tile_area->y1 = ty * self->tile_height; tile_area->y2 = tile_area->y1 + self->tile_height; if (self->partial_change) { displayio_area_expand(&self->dirty_area, &temp_area); } self->partial_change = true; } bool common_hal_displayio_tilegrid_get_flip_x(displayio_tilegrid_t *self) { return self->flip_x; } void common_hal_displayio_tilegrid_set_flip_x(displayio_tilegrid_t *self, bool flip_x) { if (self->flip_x == flip_x) { return; } self->flip_x = flip_x; self->full_change = true; } bool common_hal_displayio_tilegrid_get_flip_y(displayio_tilegrid_t *self) { return self->flip_y; } void common_hal_displayio_tilegrid_set_flip_y(displayio_tilegrid_t *self, bool flip_y) { if (self->flip_y == flip_y) { return; } self->flip_y = flip_y; self->full_change = true; } bool common_hal_displayio_tilegrid_get_transpose_xy(displayio_tilegrid_t *self) { return self->transpose_xy; } void common_hal_displayio_tilegrid_set_transpose_xy(displayio_tilegrid_t *self, bool transpose_xy) { if (self->transpose_xy == transpose_xy) { return; } self->transpose_xy = transpose_xy; // Square TileGrids do not change dimensions when transposed. if (self->pixel_width == self->pixel_height) { self->full_change = true; return; } _update_current_x(self); _update_current_y(self); self->moved = true; } void common_hal_displayio_tilegrid_set_top_left(displayio_tilegrid_t *self, uint16_t x, uint16_t y) { self->top_left_x = x; self->top_left_y = y; self->full_change = true; } bool displayio_tilegrid_fill_area(displayio_tilegrid_t *self, const _displayio_colorspace_t* colorspace, const displayio_area_t* area, uint32_t* mask, uint32_t *buffer) { // If no tiles are present we have no impact. uint8_t* tiles = self->tiles; if (self->inline_tiles) { tiles = (uint8_t*) &self->tiles; } if (tiles == NULL) { return false; } bool hidden = self->hidden || self->hidden_by_parent; if (hidden) { return false; } displayio_area_t overlap; if (!displayio_area_compute_overlap(area, &self->current_area, &overlap)) { return false; } int16_t x_stride = 1; int16_t y_stride = displayio_area_width(area); bool flip_x = self->flip_x; bool flip_y = self->flip_y; if (self->transpose_xy != self->absolute_transform->transpose_xy) { bool temp_flip = flip_x; flip_x = flip_y; flip_y = temp_flip; } // How many pixels are outside of our area between us and the start of the row. uint16_t start = 0; if ((self->absolute_transform->dx < 0) != flip_x) { start += (area->x2 - area->x1 - 1) * x_stride; x_stride *= -1; } if ((self->absolute_transform->dy < 0) != flip_y) { start += (area->y2 - area->y1 - 1) * y_stride; y_stride *= -1; } // Track if this layer finishes filling in the given area. We can ignore any remaining // layers at that point. bool full_coverage = displayio_area_equal(area, &overlap); // TODO(tannewt): Skip coverage tracking if all pixels outside the overlap have already been // set and our palette is all opaque. // TODO(tannewt): Check to see if the pixel_shader has any transparency. If it doesn't then we // can either return full coverage or bulk update the mask. displayio_area_t transformed; displayio_area_transform_within(flip_x != (self->absolute_transform->dx < 0), flip_y != (self->absolute_transform->dy < 0), self->transpose_xy != self->absolute_transform->transpose_xy, &overlap, &self->current_area, &transformed); int16_t start_x = (transformed.x1 - self->current_area.x1); int16_t end_x = (transformed.x2 - self->current_area.x1); int16_t start_y = (transformed.y1 - self->current_area.y1); int16_t end_y = (transformed.y2 - self->current_area.y1); int16_t y_shift = 0; int16_t x_shift = 0; if ((self->absolute_transform->dx < 0) != flip_x) { x_shift = area->x2 - overlap.x2; } else { x_shift = overlap.x1 - area->x1; } if ((self->absolute_transform->dy < 0) != flip_y) { y_shift = area->y2 - overlap.y2; } else { y_shift = overlap.y1 - area->y1; } // This untransposes x and y so it aligns with bitmap rows. if (self->transpose_xy != self->absolute_transform->transpose_xy) { int16_t temp_stride = x_stride; x_stride = y_stride; y_stride = temp_stride; int16_t temp_shift = x_shift; x_shift = y_shift; y_shift = temp_shift; } uint8_t pixels_per_byte = 8 / colorspace->depth; displayio_input_pixel_t input_pixel; displayio_output_pixel_t output_pixel; for (input_pixel.y = start_y; input_pixel.y < end_y; ++input_pixel.y) { int16_t row_start = start + (input_pixel.y - start_y + y_shift) * y_stride; // in pixels int16_t local_y = input_pixel.y / self->absolute_transform->scale; for (input_pixel.x = start_x; input_pixel.x < end_x; ++input_pixel.x) { // Compute the destination pixel in the buffer and mask based on the transformations. int16_t offset = row_start + (input_pixel.x - start_x + x_shift) * x_stride; // in pixels // This is super useful for debugging out of range accesses. Uncomment to use. // if (offset < 0 || offset >= (int32_t) displayio_area_size(area)) { // asm("bkpt"); // } // Check the mask first to see if the pixel has already been set. if ((mask[offset / 32] & (1 << (offset % 32))) != 0) { continue; } int16_t local_x = input_pixel.x / self->absolute_transform->scale; uint16_t tile_location = ((local_y / self->tile_height + self->top_left_y) % self->height_in_tiles) * self->width_in_tiles + (local_x / self->tile_width + self->top_left_x) % self->width_in_tiles; input_pixel.tile = tiles[tile_location]; input_pixel.tile_x = (input_pixel.tile % self->bitmap_width_in_tiles) * self->tile_width + local_x % self->tile_width; input_pixel.tile_y = (input_pixel.tile / self->bitmap_width_in_tiles) * self->tile_height + local_y % self->tile_height; //uint32_t value = 0; output_pixel.pixel = 0; input_pixel.pixel = 0; // We always want to read bitmap pixels by row first and then transpose into the destination // buffer because most bitmaps are row associated. if (MP_OBJ_IS_TYPE(self->bitmap, &displayio_bitmap_type)) { input_pixel.pixel = common_hal_displayio_bitmap_get_pixel(self->bitmap, input_pixel.tile_x, input_pixel.tile_y); } else if (MP_OBJ_IS_TYPE(self->bitmap, &displayio_shape_type)) { input_pixel.pixel = common_hal_displayio_shape_get_pixel(self->bitmap, input_pixel.tile_x, input_pixel.tile_y); } else if (MP_OBJ_IS_TYPE(self->bitmap, &displayio_ondiskbitmap_type)) { input_pixel.pixel = common_hal_displayio_ondiskbitmap_get_pixel(self->bitmap, input_pixel.tile_x, input_pixel.tile_y); } output_pixel.opaque = true; if (self->pixel_shader == mp_const_none) { output_pixel.pixel = input_pixel.pixel; } else if (MP_OBJ_IS_TYPE(self->pixel_shader, &displayio_palette_type)) { output_pixel.opaque = displayio_palette_get_color(self->pixel_shader, colorspace, input_pixel.pixel, &output_pixel.pixel); } else if (MP_OBJ_IS_TYPE(self->pixel_shader, &displayio_colorconverter_type)) { displayio_colorconverter_convert(self->pixel_shader, colorspace, &input_pixel, &output_pixel); } if (!output_pixel.opaque) { // A pixel is transparent so we haven't fully covered the area ourselves. full_coverage = false; } else { mask[offset / 32] |= 1 << (offset % 32); if (colorspace->depth == 16) { *(((uint16_t*) buffer) + offset) = output_pixel.pixel; } else if (colorspace->depth == 8) { *(((uint8_t*) buffer) + offset) = output_pixel.pixel; } else if (colorspace->depth < 8) { // Reorder the offsets to pack multiple rows into a byte (meaning they share a column). if (!colorspace->pixels_in_byte_share_row) { uint16_t width = displayio_area_width(area); uint16_t row = offset / width; uint16_t col = offset % width; // Dividing by pixels_per_byte does truncated division even if we multiply it back out. offset = col * pixels_per_byte + (row / pixels_per_byte) * pixels_per_byte * width + row % pixels_per_byte; // Also useful for validating that the bitpacking worked correctly. // if (offset > displayio_area_size(area)) { // asm("bkpt"); // } } uint8_t shift = (offset % pixels_per_byte) * colorspace->depth; if (colorspace->reverse_pixels_in_byte) { // Reverse the shift by subtracting it from the leftmost shift. shift = (pixels_per_byte - 1) * colorspace->depth - shift; } ((uint8_t*)buffer)[offset / pixels_per_byte] |= output_pixel.pixel << shift; } } } } return full_coverage; } void displayio_tilegrid_finish_refresh(displayio_tilegrid_t *self) { bool first_draw = self->previous_area.x1 == self->previous_area.x2; bool hidden = self->hidden || self->hidden_by_parent; if (!first_draw && hidden) { self->previous_area.x2 = self->previous_area.x1; } else if (self->moved || first_draw) { displayio_area_copy(&self->current_area, &self->previous_area); } self->moved = false; self->full_change = false; self->partial_change = false; if (MP_OBJ_IS_TYPE(self->pixel_shader, &displayio_palette_type)) { displayio_palette_finish_refresh(self->pixel_shader); } else if (MP_OBJ_IS_TYPE(self->pixel_shader, &displayio_colorconverter_type)) { displayio_colorconverter_finish_refresh(self->pixel_shader); } if (MP_OBJ_IS_TYPE(self->bitmap, &displayio_bitmap_type)) { displayio_bitmap_finish_refresh(self->bitmap); } else if (MP_OBJ_IS_TYPE(self->bitmap, &displayio_shape_type)) { displayio_shape_finish_refresh(self->bitmap); } else if (MP_OBJ_IS_TYPE(self->bitmap, &displayio_ondiskbitmap_type)) { // OnDiskBitmap changes will trigger a complete reload so no need to // track changes. } // TODO(tannewt): We could double buffer changes to position and move them over here. // That way they won't change during a refresh and tear. } displayio_area_t* displayio_tilegrid_get_refresh_areas(displayio_tilegrid_t *self, displayio_area_t* tail) { bool first_draw = self->previous_area.x1 == self->previous_area.x2; bool hidden = self->hidden || self->hidden_by_parent; // Check hidden first because it trumps all other changes. if (hidden) { if (!first_draw) { self->previous_area.next = tail; return &self->previous_area; } else { return tail; } } else if (self->moved && !first_draw) { displayio_area_union(&self->previous_area, &self->current_area, &self->dirty_area); if (displayio_area_size(&self->dirty_area) <= 2U * self->pixel_width * self->pixel_height) { self->dirty_area.next = tail; return &self->dirty_area; } self->previous_area.next = tail; self->current_area.next = &self->previous_area; return &self->current_area; } // If we have an in-memory bitmap, then check it for modifications. if (MP_OBJ_IS_TYPE(self->bitmap, &displayio_bitmap_type)) { displayio_area_t* refresh_area = displayio_bitmap_get_refresh_areas(self->bitmap, tail); if (refresh_area != tail) { // Special case a TileGrid that shows a full bitmap and use its // dirty area. Copy it to ours so we can transform it. if (self->tiles_in_bitmap == 1) { displayio_area_copy(refresh_area, &self->dirty_area); self->partial_change = true; } else { self->full_change = true; } } } else if (MP_OBJ_IS_TYPE(self->bitmap, &displayio_shape_type)) { displayio_area_t* refresh_area = displayio_shape_get_refresh_areas(self->bitmap, tail); if (refresh_area != tail) { displayio_area_copy(refresh_area, &self->dirty_area); self->partial_change = true; } } self->full_change = self->full_change || (MP_OBJ_IS_TYPE(self->pixel_shader, &displayio_palette_type) && displayio_palette_needs_refresh(self->pixel_shader)) || (MP_OBJ_IS_TYPE(self->pixel_shader, &displayio_colorconverter_type) && displayio_colorconverter_needs_refresh(self->pixel_shader)); if (self->full_change || first_draw) { self->current_area.next = tail; return &self->current_area; } if (self->partial_change) { if (self->absolute_transform->transpose_xy) { int16_t x1 = self->dirty_area.x1; self->dirty_area.x1 = self->absolute_transform->x + self->absolute_transform->dx * (self->y + self->dirty_area.y1); self->dirty_area.y1 = self->absolute_transform->y + self->absolute_transform->dy * (self->x + x1); int16_t x2 = self->dirty_area.x2; self->dirty_area.x2 = self->absolute_transform->x + self->absolute_transform->dx * (self->y + self->dirty_area.y2); self->dirty_area.y2 = self->absolute_transform->y + self->absolute_transform->dy * (self->x + x2); } else { self->dirty_area.x1 = self->absolute_transform->x + self->absolute_transform->dx * (self->x + self->dirty_area.x1); self->dirty_area.y1 = self->absolute_transform->y + self->absolute_transform->dy * (self->y + self->dirty_area.y1); self->dirty_area.x2 = self->absolute_transform->x + self->absolute_transform->dx * (self->x + self->dirty_area.x2); self->dirty_area.y2 = self->absolute_transform->y + self->absolute_transform->dy * (self->y + self->dirty_area.y2); } if (self->dirty_area.y2 < self->dirty_area.y1) { int16_t temp = self->dirty_area.y2; self->dirty_area.y2 = self->dirty_area.y1; self->dirty_area.y1 = temp; } if (self->dirty_area.x2 < self->dirty_area.x1) { int16_t temp = self->dirty_area.x2; self->dirty_area.x2 = self->dirty_area.x1; self->dirty_area.x1 = temp; } self->dirty_area.next = tail; return &self->dirty_area; } return tail; }
felixerdy/circuitpython
shared-module/adafruit_bus_device/SPIDevice.c
<filename>shared-module/adafruit_bus_device/SPIDevice.c /* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2020 <NAME> * * 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 "shared-bindings/adafruit_bus_device/SPIDevice.h" #include "shared-bindings/busio/SPI.h" #include "shared-bindings/digitalio/DigitalInOut.h" #include "py/mperrno.h" #include "py/nlr.h" #include "py/runtime.h" void common_hal_adafruit_bus_device_spidevice_construct(adafruit_bus_device_spidevice_obj_t *self, busio_spi_obj_t *spi, digitalio_digitalinout_obj_t *cs, uint32_t baudrate, uint8_t polarity, uint8_t phase, uint8_t extra_clocks) { self->spi = spi; self->baudrate = baudrate; self->polarity = polarity; self->phase = phase; self->extra_clocks = extra_clocks; self->chip_select = cs; } mp_obj_t common_hal_adafruit_bus_device_spidevice_enter(adafruit_bus_device_spidevice_obj_t *self) { bool success = false; while (!success) { success = common_hal_busio_spi_try_lock(self->spi); RUN_BACKGROUND_TASKS; mp_handle_pending(); } common_hal_busio_spi_configure(self->spi, self->baudrate, self->polarity, self->phase, 8); if (self->chip_select != MP_OBJ_NULL) { common_hal_digitalio_digitalinout_set_value(MP_OBJ_TO_PTR(self->chip_select), false); } return self->spi; } void common_hal_adafruit_bus_device_spidevice_exit(adafruit_bus_device_spidevice_obj_t *self) { if (self->chip_select != MP_OBJ_NULL) { common_hal_digitalio_digitalinout_set_value(MP_OBJ_TO_PTR(self->chip_select), true); } if (self->extra_clocks > 0) { mp_buffer_info_t bufinfo; mp_obj_t buffer = mp_obj_new_bytearray_of_zeros(1); mp_get_buffer_raise(buffer, &bufinfo, MP_BUFFER_READ); ((uint8_t*)bufinfo.buf)[0] = 0xFF; uint8_t clocks = self->extra_clocks / 8; if ((self->extra_clocks % 8) != 0) clocks += 1; while (clocks > 0) { if (!common_hal_busio_spi_write(self->spi, ((uint8_t*)bufinfo.buf), 1)) { mp_raise_OSError(MP_EIO); } clocks--; } } common_hal_busio_spi_unlock(self->spi); }
felixerdy/circuitpython
ports/raspberrypi/boards/raspberry_pi_pico/mpconfigboard.h
<filename>ports/raspberrypi/boards/raspberry_pi_pico/mpconfigboard.h // LEDs // #define MICROPY_HW_LED_STATUS (&pin_PA17) #define MICROPY_HW_BOARD_NAME "Raspberry Pi Pico" #define MICROPY_HW_MCU_NAME "rp2040" // #define DEFAULT_I2C_BUS_SCL (&pin_PA23) // #define DEFAULT_I2C_BUS_SDA (&pin_PA22) // #define DEFAULT_SPI_BUS_SCK (&pin_PB11) // #define DEFAULT_SPI_BUS_MOSI (&pin_PB10) // #define DEFAULT_SPI_BUS_MISO (&pin_PA12) // #define DEFAULT_UART_BUS_RX (&pin_PA11) // #define DEFAULT_UART_BUS_TX (&pin_PA10) // Flash chip is W25Q16JVUXIQ connected over QSPI #define TOTAL_FLASH_SIZE (2 * 1024 * 1024)
felixerdy/circuitpython
shared-module/bitmaptools/__init__.c
/* * This file is part of the Micro Python project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2021 <NAME> * * 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 "shared-bindings/displayio/Bitmap.h" #include "py/runtime.h" #include "math.h" void common_hal_bitmaptools_rotozoom(displayio_bitmap_t *self, int16_t ox, int16_t oy, int16_t dest_clip0_x, int16_t dest_clip0_y, int16_t dest_clip1_x, int16_t dest_clip1_y, displayio_bitmap_t *source, int16_t px, int16_t py, int16_t source_clip0_x, int16_t source_clip0_y, int16_t source_clip1_x, int16_t source_clip1_y, float angle, float scale, uint32_t skip_index, bool skip_index_none) { // Copies region from source to the destination bitmap, including rotation, // scaling and clipping of either the source or destination regions // // *self: destination bitmap // ox: the (ox, oy) destination point where the source (px,py) point is placed // oy: // dest_clip0: (x,y) is the corner of the clip window on the destination bitmap // dest_clip1: (x,y) is the other corner of the clip window of the destination bitmap // *source: the source bitmap // px: the (px, py) point of rotation of the source bitmap // py: // source_clip0: (x,y) is the corner of the clip window on the source bitmap // source_clip1: (x,y) is the other of the clip window on the source bitmap // angle: angle of rotation in radians, positive is clockwise // scale: scale factor // skip_index: color index that should be ignored (and not copied over) // skip_index_none: if skip_index_none is True, then all color indexes should be copied // (that is, no color indexes should be skipped) // Copy complete "source" bitmap into "self" bitmap at location x,y in the "self" // Add a boolean to determine if all values are copied, or only if non-zero // If skip_value is encountered in the source bitmap, it will not be copied. // If skip_value is `None`, then all pixels are copied. // # Credit from https://github.com/wernsey/bitmap // # MIT License from // # * Copyright (c) 2017 <NAME> <<EMAIL>> // # // # * // # * #### `void bm_rotate_blit(Bitmap *dst, int ox, int oy, Bitmap *src, int px, int py, double angle, double scale);` // # * // # * Rotates a source bitmap `src` around a pivot point `px,py` and blits it onto a destination bitmap `dst`. // # * // # * The bitmap is positioned such that the point `px,py` on the source is at the offset `ox,oy` on the destination. // # * // # * The `angle` is clockwise, in radians. The bitmap is also scaled by the factor `scale`. // # // # void bm_rotate_blit(Bitmap *dst, int ox, int oy, Bitmap *src, int px, int py, double angle, double scale); // # /* // # Reference: // # "Fast Bitmap Rotation and Scaling" By <NAME>, Dr Dobbs' Journal, July 01, 2001 // # http://www.drdobbs.com/architecture-and-design/fast-bitmap-rotation-and-scaling/184416337 // # See also http://www.efg2.com/Lab/ImageProcessing/RotateScanline.htm // # */ if (self->read_only) { mp_raise_RuntimeError(translate("Read-only object")); } int16_t x,y; int16_t minx = dest_clip1_x; int16_t miny = dest_clip1_y; int16_t maxx = dest_clip0_x; int16_t maxy = dest_clip0_y; float sinAngle = sinf(angle); float cosAngle = cosf(angle); float dx, dy; /* Compute the position of where each corner on the source bitmap will be on the destination to get a bounding box for scanning */ dx = -cosAngle * px * scale + sinAngle * py * scale + ox; dy = -sinAngle * px * scale - cosAngle * py * scale + oy; if(dx < minx) minx = (int16_t)dx; if(dx > maxx) maxx = (int16_t)dx; if(dy < miny) miny = (int16_t)dy; if(dy > maxy) maxy = (int16_t)dy; dx = cosAngle * (source->width - px) * scale + sinAngle * py * scale + ox; dy = sinAngle * (source->width - px) * scale - cosAngle * py * scale + oy; if(dx < minx) minx = (int16_t)dx; if(dx > maxx) maxx = (int16_t)dx; if(dy < miny) miny = (int16_t)dy; if(dy > maxy) maxy = (int16_t)dy; dx = cosAngle * (source->width - px) * scale - sinAngle * (source->height - py) * scale + ox; dy = sinAngle * (source->width - px) * scale + cosAngle * (source->height - py) * scale + oy; if(dx < minx) minx = (int16_t)dx; if(dx > maxx) maxx = (int16_t)dx; if(dy < miny) miny = (int16_t)dy; if(dy > maxy) maxy = (int16_t)dy; dx = -cosAngle * px * scale - sinAngle * (source->height - py) * scale + ox; dy = -sinAngle * px * scale + cosAngle * (source->height - py) * scale + oy; if(dx < minx) minx = (int16_t)dx; if(dx > maxx) maxx = (int16_t)dx; if(dy < miny) miny = (int16_t)dy; if(dy > maxy) maxy = (int16_t)dy; /* Clipping */ if(minx < dest_clip0_x) minx = dest_clip0_x; if(maxx > dest_clip1_x - 1) maxx = dest_clip1_x - 1; if(miny < dest_clip0_y) miny = dest_clip0_y; if(maxy > dest_clip1_y - 1) maxy = dest_clip1_y - 1; float dvCol = cosAngle / scale; float duCol = sinAngle / scale; float duRow = dvCol; float dvRow = -duCol; float startu = px - (ox * dvCol + oy * duCol); float startv = py - (ox * dvRow + oy * duRow); float rowu = startu + miny * duCol; float rowv = startv + miny * dvCol; for(y = miny; y <= maxy; y++) { float u = rowu + minx * duRow; float v = rowv + minx * dvRow; for(x = minx; x <= maxx; x++) { if(u >= source_clip0_x && u < source_clip1_x && v >= source_clip0_y && v < source_clip1_y) { uint32_t c = common_hal_displayio_bitmap_get_pixel(source, u, v); if( (skip_index_none) || (c != skip_index) ) { common_hal_displayio_bitmap_set_pixel(self, x, y, c); } } u += duRow; v += dvRow; } rowu += duCol; rowv += dvCol; } }
felixerdy/circuitpython
supervisor/shared/display.c
/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2019 <NAME> for Adafruit Industries * * 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 "supervisor/shared/display.h" #include <string.h> #include "py/mpstate.h" #include "shared-bindings/displayio/Bitmap.h" #include "shared-bindings/displayio/Group.h" #include "shared-bindings/displayio/Palette.h" #include "shared-bindings/displayio/TileGrid.h" #include "supervisor/memory.h" #if CIRCUITPY_RGBMATRIX #include "shared-module/displayio/__init__.h" #endif #if CIRCUITPY_SHARPDISPLAY #include "shared-module/displayio/__init__.h" #include "shared-bindings/sharpdisplay/SharpMemoryFramebuffer.h" #include "shared-module/sharpdisplay/SharpMemoryFramebuffer.h" #endif extern size_t blinka_bitmap_data[]; extern displayio_bitmap_t blinka_bitmap; extern displayio_group_t circuitpython_splash; #if CIRCUITPY_TERMINALIO static supervisor_allocation* tilegrid_tiles = NULL; #endif void supervisor_start_terminal(uint16_t width_px, uint16_t height_px) { // Default the scale to 2 because we may show blinka without the terminal for // languages that don't have font support. uint8_t scale = 2; #if CIRCUITPY_TERMINALIO displayio_tilegrid_t* grid = &supervisor_terminal_text_grid; bool tall = height_px > width_px; uint16_t terminal_width_px = tall ? width_px : width_px - blinka_bitmap.width; uint16_t terminal_height_px = tall ? height_px - blinka_bitmap.height : height_px ; uint16_t width_in_tiles = terminal_width_px / grid->tile_width; // determine scale based on h if (width_in_tiles < 80) { scale = 1; } width_in_tiles = terminal_width_px / (grid->tile_width * scale); if (width_in_tiles < 1) { width_in_tiles = 1; } uint16_t height_in_tiles = terminal_height_px / (grid->tile_height * scale); uint16_t remaining_pixels = tall ? 0 : terminal_height_px % (grid->tile_height * scale); if (height_in_tiles < 1 || remaining_pixels > 0) { height_in_tiles += 1; } uint16_t total_tiles = width_in_tiles * height_in_tiles; // Reuse the previous allocation if possible if (tilegrid_tiles) { if (get_allocation_length(tilegrid_tiles) != align32_size(total_tiles)) { free_memory(tilegrid_tiles); tilegrid_tiles = NULL; } } if (!tilegrid_tiles) { tilegrid_tiles = allocate_memory(align32_size(total_tiles), false, true); if (!tilegrid_tiles) { return; } } uint8_t* tiles = (uint8_t*) tilegrid_tiles->ptr; grid->y = tall ? blinka_bitmap.height : 0; grid->x = tall ? 0 : blinka_bitmap.width; grid->top_left_y = 0; if (remaining_pixels > 0) { grid->y -= (grid->tile_height - remaining_pixels); } grid->width_in_tiles = width_in_tiles; grid->height_in_tiles = height_in_tiles; assert(width_in_tiles > 0); assert(height_in_tiles > 0); grid->pixel_width = width_in_tiles * grid->tile_width; grid->pixel_height = height_in_tiles * grid->tile_height; grid->tiles = tiles; grid->full_change = true; common_hal_terminalio_terminal_construct(&supervisor_terminal, grid, &supervisor_terminal_font); #endif circuitpython_splash.scale = scale; } void supervisor_stop_terminal(void) { #if CIRCUITPY_TERMINALIO if (tilegrid_tiles != NULL) { free_memory(tilegrid_tiles); tilegrid_tiles = NULL; supervisor_terminal_text_grid.tiles = NULL; } #endif } void supervisor_display_move_memory(void) { #if CIRCUITPY_TERMINALIO if (tilegrid_tiles != NULL) { supervisor_terminal_text_grid.tiles = (uint8_t*) tilegrid_tiles->ptr; } else { supervisor_terminal_text_grid.tiles = NULL; } #endif #if CIRCUITPY_DISPLAYIO for (uint8_t i = 0; i < CIRCUITPY_DISPLAY_LIMIT; i++) { #if CIRCUITPY_RGBMATRIX if (displays[i].rgbmatrix.base.type == &rgbmatrix_RGBMatrix_type) { rgbmatrix_rgbmatrix_obj_t * pm = &displays[i].rgbmatrix; common_hal_rgbmatrix_rgbmatrix_reconstruct(pm, NULL); } #endif #if CIRCUITPY_SHARPDISPLAY if (displays[i].bus_base.type == &sharpdisplay_framebuffer_type) { sharpdisplay_framebuffer_obj_t * sharp = &displays[i].sharpdisplay; common_hal_sharpdisplay_framebuffer_reconstruct(sharp); } #endif } #endif } size_t blinka_bitmap_data[32] = { 0x00000011, 0x11000000, 0x00000111, 0x53100000, 0x00000111, 0x56110000, 0x00000111, 0x11140000, 0x00000111, 0x20002000, 0x00000011, 0x13000000, 0x00000001, 0x11200000, 0x00000000, 0x11330000, 0x00000000, 0x01122000, 0x00001111, 0x44133000, 0x00032323, 0x24112200, 0x00111114, 0x44113300, 0x00323232, 0x34112200, 0x11111144, 0x44443300, 0x11111111, 0x11144401, 0x23232323, 0x21111110 }; displayio_bitmap_t blinka_bitmap = { .base = {.type = &displayio_bitmap_type }, .width = 16, .height = 16, .data = blinka_bitmap_data, .stride = 2, .bits_per_value = 4, .x_shift = 3, .x_mask = 0x7, .bitmask = 0xf, .read_only = true }; _displayio_color_t blinka_colors[7] = { { .rgb888 = 0x000000, .rgb565 = 0x0000, .luma = 0x00, .chroma = 0, .transparent = true }, { .rgb888 = 0x8428bc, .rgb565 = 0x8978, .luma = 0xff, // We cheat the luma here. It is actually 0x60 .hue = 184, .chroma = 148 }, { .rgb888 = 0xff89bc, .rgb565 = 0xFCB8, .luma = 0xb5, .hue = 222, .chroma = 118 }, { .rgb888 = 0x7beffe, .rgb565 = 0x869F, .luma = 0xe0, .hue = 124, .chroma = 131 }, { .rgb888 = 0x51395f, .rgb565 = 0x5A0D, .luma = 0x47, .hue = 185, .chroma = 38 }, { .rgb888 = 0xffffff, .rgb565 = 0xffff, .luma = 0xff, .chroma = 0 }, { .rgb888 = 0x0736a0, .rgb565 = 0x01f5, .luma = 0x44, .hue = 147, .chroma = 153 }, }; displayio_palette_t blinka_palette = { .base = {.type = &displayio_palette_type }, .colors = blinka_colors, .color_count = 7, .needs_refresh = false }; displayio_tilegrid_t blinka_sprite = { .base = {.type = &displayio_tilegrid_type }, .bitmap = &blinka_bitmap, .pixel_shader = &blinka_palette, .x = 0, .y = 0, .pixel_width = 16, .pixel_height = 16, .bitmap_width_in_tiles = 1, .width_in_tiles = 1, .height_in_tiles = 1, .tile_width = 16, .tile_height = 16, .top_left_x = 16, .top_left_y = 16, .tiles = 0, .partial_change = false, .full_change = false, .hidden = false, .hidden_by_parent = false, .moved = false, .inline_tiles = true, .in_group = true }; #if CIRCUITPY_TERMINALIO mp_obj_t members[] = { &blinka_sprite, &supervisor_terminal_text_grid, }; mp_obj_list_t splash_children = { .base = {.type = &mp_type_list }, .alloc = 2, .len = 2, .items = members, }; #else mp_obj_t members[] = { &blinka_sprite }; mp_obj_list_t splash_children = { .base = {.type = &mp_type_list }, .alloc = 1, .len = 1, .items = members, }; #endif displayio_group_t circuitpython_splash = { .base = {.type = &displayio_group_type }, .x = 0, .y = 0, .scale = 2, .members = &splash_children, .item_removed = false, .in_group = false, .hidden = false, .hidden_by_parent = false };
felixerdy/circuitpython
ports/raspberrypi/boards/pimoroni_picosystem/mpconfigboard.h
#define MICROPY_HW_BOARD_NAME "Pimoroni PicoSystem" #define MICROPY_HW_MCU_NAME "rp2040" #define MICROPY_HW_VBUS_DETECT (&pin_GPIO2) #define MICROPY_HW_LCD_RESET (&pin_GPIO4) #define MICROPY_HW_LCD_CS (&pin_GPIO5) #define MICROPY_HW_LCD_SCLK (&pin_GPIO6) #define MICROPY_HW_LCD_MOSI (&pin_GPIO7) #define MICROPY_HW_LCD_VSYNC (&pin_GPIO8) #define MICROPY_HW_LCD_DS (&pin_GPIO9) #define MICROPY_HW_AUDIO (&pin_GPIO11) #define MICROPY_HW_BACKLIGHT (&pin_GPIO12) #define MICROPY_HW_VBUS_DETECT (&pin_GPIO2) #define MICROPY_HW_LED_G (&pin_GPIO13) #define MICROPY_HW_LED_R (&pin_GPIO14) #define MICROPY_HW_LED_B (&pin_GPIO15) #define MICROPY_HW_SW_Y (&pin_GPIO16) #define MICROPY_HW_SW_X (&pin_GPIO17) #define MICROPY_HW_SW_A (&pin_GPIO18) #define MICROPY_HW_SW_B (&pin_GPIO19) #define MICROPY_HW_SW_DOWN (&pin_GPIO20) #define MICROPY_HW_SW_RIGHT (&pin_GPIO21) #define MICROPY_HW_SW_LEFT (&pin_GPIO22) #define MICROPY_HW_SW_UP (&pin_GPIO23) #define MICROPY_HW_CHARGE_STAT (&pin_GPIO24) #define MICROPY_HW_BAT_SENSE (&pin_GPIO26) #define DEFAULT_SPI_BUS_SCK (&pin_GPIO6) #define DEFAULT_SPI_BUS_MOSI (&pin_GPIO7) #define DEFAULT_UART_BUS_RX (&pin_GPIO1) #define DEFAULT_UART_BUS_TX (&pin_GPIO0) #define TOTAL_FLASH_SIZE (16 * 1024 * 1024) // These pins are unconnected #define IGNORE_PIN_GPIO3 1 #define IGNORE_PIN_GPIO10 1 #define IGNORE_PIN_GPIO25 1 #define IGNORE_PIN_GPIO27 1 #define IGNORE_PIN_GPIO28 1 #define IGNORE_PIN_GPIO29 1
felixerdy/circuitpython
py/builtinevex.c
<reponame>felixerdy/circuitpython<filename>py/builtinevex.c /* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * SPDX-FileCopyrightText: Copyright (c) 2013, 2014 <NAME> * * 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 <stdint.h> #include "py/objfun.h" #include "py/compile.h" #include "py/runtime.h" #include "py/builtin.h" #include "supervisor/shared/translate.h" #if MICROPY_PY_BUILTINS_COMPILE typedef struct _mp_obj_code_t { mp_obj_base_t base; mp_obj_t module_fun; } mp_obj_code_t; STATIC const mp_obj_type_t mp_type_code = { { &mp_type_type }, .name = MP_QSTR_code, }; STATIC mp_obj_t code_execute(mp_obj_code_t *self, mp_obj_dict_t *globals, mp_obj_dict_t *locals) { // save context and set new context mp_obj_dict_t *old_globals = mp_globals_get(); mp_obj_dict_t *old_locals = mp_locals_get(); mp_globals_set(globals); mp_locals_set(locals); // a bit of a hack: fun_bc will re-set globals, so need to make sure it's // the correct one if (MP_OBJ_IS_TYPE(self->module_fun, &mp_type_fun_bc)) { mp_obj_fun_bc_t *fun_bc = MP_OBJ_TO_PTR(self->module_fun); fun_bc->globals = globals; } // execute code nlr_buf_t nlr; if (nlr_push(&nlr) == 0) { mp_obj_t ret = mp_call_function_0(self->module_fun); nlr_pop(); mp_globals_set(old_globals); mp_locals_set(old_locals); return ret; } else { // exception; restore context and re-raise same exception mp_globals_set(old_globals); mp_locals_set(old_locals); nlr_jump(nlr.ret_val); } } STATIC mp_obj_t mp_builtin_compile(size_t n_args, const mp_obj_t *args) { (void)n_args; // get the source size_t str_len; const char *str = mp_obj_str_get_data(args[0], &str_len); // get the filename qstr filename = mp_obj_str_get_qstr(args[1]); // create the lexer mp_lexer_t *lex = mp_lexer_new_from_str_len(filename, str, str_len, 0); // get the compile mode qstr mode = mp_obj_str_get_qstr(args[2]); mp_parse_input_kind_t parse_input_kind; switch (mode) { case MP_QSTR_single: parse_input_kind = MP_PARSE_SINGLE_INPUT; break; case MP_QSTR_exec: parse_input_kind = MP_PARSE_FILE_INPUT; break; case MP_QSTR_eval: parse_input_kind = MP_PARSE_EVAL_INPUT; break; default: mp_raise_ValueError(translate("bad compile mode")); } mp_obj_code_t *code = m_new_obj(mp_obj_code_t); code->base.type = &mp_type_code; code->module_fun = mp_parse_compile_execute(lex, parse_input_kind, NULL, NULL); return MP_OBJ_FROM_PTR(code); } MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_builtin_compile_obj, 3, 6, mp_builtin_compile); #endif // MICROPY_PY_BUILTINS_COMPILE #if MICROPY_PY_BUILTINS_EVAL_EXEC STATIC mp_obj_t eval_exec_helper(size_t n_args, const mp_obj_t *args, mp_parse_input_kind_t parse_input_kind) { // work out the context mp_obj_dict_t *globals = mp_globals_get(); mp_obj_dict_t *locals = mp_locals_get(); for (size_t i = 1; i < 3 && i < n_args; ++i) { if (args[i] != mp_const_none) { if (!MP_OBJ_IS_TYPE(args[i], &mp_type_dict)) { mp_raise_TypeError(NULL); } locals = MP_OBJ_TO_PTR(args[i]); if (i == 1) { globals = locals; } } } #if MICROPY_PY_BUILTINS_COMPILE if (MP_OBJ_IS_TYPE(args[0], &mp_type_code)) { return code_execute(MP_OBJ_TO_PTR(args[0]), globals, locals); } #endif // Extract the source code. mp_buffer_info_t bufinfo; mp_get_buffer_raise(args[0], &bufinfo, MP_BUFFER_READ); // create the lexer // MP_PARSE_SINGLE_INPUT is used to indicate a file input mp_lexer_t *lex; if (MICROPY_PY_BUILTINS_EXECFILE && parse_input_kind == MP_PARSE_SINGLE_INPUT) { lex = mp_lexer_new_from_file(bufinfo.buf); parse_input_kind = MP_PARSE_FILE_INPUT; } else { lex = mp_lexer_new_from_str_len(MP_QSTR__lt_string_gt_, bufinfo.buf, bufinfo.len, 0); } return mp_parse_compile_execute(lex, parse_input_kind, globals, locals); } STATIC mp_obj_t mp_builtin_eval(size_t n_args, const mp_obj_t *args) { return eval_exec_helper(n_args, args, MP_PARSE_EVAL_INPUT); } MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_builtin_eval_obj, 1, 3, mp_builtin_eval); STATIC mp_obj_t mp_builtin_exec(size_t n_args, const mp_obj_t *args) { return eval_exec_helper(n_args, args, MP_PARSE_FILE_INPUT); } MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_builtin_exec_obj, 1, 3, mp_builtin_exec); #endif // MICROPY_PY_BUILTINS_EVAL_EXEC #if MICROPY_PY_BUILTINS_EXECFILE STATIC mp_obj_t mp_builtin_execfile(size_t n_args, const mp_obj_t *args) { // MP_PARSE_SINGLE_INPUT is used to indicate a file input return eval_exec_helper(n_args, args, MP_PARSE_SINGLE_INPUT); } MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_builtin_execfile_obj, 1, 3, mp_builtin_execfile); #endif
jonas054/printelbrot
mandelbrot.c
<gh_stars>1-10 #if 0 gcc -pthread -O2 -o mandelbrot mandelbrot.c && ./mandelbrot "$@" exit #endif // Good spots: // X:-2.349932e-01 Y:8.281560e-01 S:2.622605e-07 M:4644 #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <pthread.h> #include <sys/ioctl.h> #include <unistd.h> int window_height = 0; int window_width = 0; int** result; double size = 4.4; double y_offset = 0.1080729; double x_offset = -0.6386042; int max = 60; const int COLORS[] = { 18, // midnightblue, 19, // darkblue, 20, // mediumblue, 28, // darkgreen, 34, // forestgreen, 37, // darkcyan, 39, // dodgerblue, 43, // lightseagreen, 44, // darkturquoise, 45, // deepskyblue, 46, // lime, 48, // springgreen, 49, // mediumspringgreen, 51, // aqua, 55, // indigo, 59, // darkslategray, 61, // darkslateblue, 65, // darkolivegreen, 69, // royalblue, 72, // seagreen, 74, // steelblue, 77, // limegreen, 78, // mediumseagreen, 80, // mediumturquoise, 86, // turquoise, 88, // webmaroon, 90, // webpurple, 97, // rebeccapurple, 102, // dimgray, 104, // slateblue, 105, // mediumslateblue, 106, // olivedrab, 109, // cadetblue, 111, // cornflower, 115, // mediumaquamarine, 118, // lawngreen, 122, // aquamarine, 124, // brown, 127, // darkmagenta, 128, // darkviolet, 129, // purple, 130, // saddlebrown, 131, // sienna, 134, // darkorchid, 135, // blueviolet, 141, // mediumpurple, 142, // olive, 145, // darkgray, 149, // yellowgreen, 151, // darkseagreen, 153, // skyblue, 157, // lightgreen, 157, // palegreen, 160, // firebrick, 163, // mediumvioletred, 168, // maroon, 170, // mediumorchid, 172, // chocolate, 174, // indianred, 178, // darkgoldenrod, 179, // peru, 181, // rosybrown, 186, // darkkhaki, 187, // tan, 188, // gray, 189, // lightsteelblue, 191, // greenyellow, 195, // lightblue, 197, // crimson, 199, // deeppink, 201, // fuchsia, 202, // orangered, 209, // coral, 211, // palevioletred, 212, // hotpink, 213, // orchid, 214, // darkorange, 216, // darksalmon, 217, // lightcoral, 219, // violet, 223, // burlywood, 224, // lightpink, 225, // thistle, 226, // gold, 229, // khaki, 230, // bisque, 231, // aliceblue, 0, // black, 0, // black, 0 // black }; const int NR_OF_COLORS = sizeof(COLORS) / sizeof(COLORS[0]); const int NR_OF_THREADS = 7; // The central algorithm. Calculate zₙ+₁ = zₙ² + c until zₙ starts to grow // exponentially, which is when |zₙ| >= 2. Return the number of iterations // until we reach that point, or max if we break early. long iterations(double x, double y) { int count = 0; // The real and imaginary parts of z: zr and zi. Calulating the squares zr2 // and zi2 one time per loop is both an optimization and a convenience. double zr = 0, zi = 0, zr2 = 0, zi2 = 0; for (; zr2 + zi2 < 4.0 && count < max; ++count) { // (a+b)² = a² + 2ab + b², so... (zr+zi)² = zr² + 2 * zr * zi + zi² // The new zr and zi will be the real and imaginary parts of that result. zi = 2 * zr * zi + y; zr = zr2 - zi2 + x; zr2 = zr * zr; zi2 = zi * zi; } return count; } // Convert a position (pos) on the screen (full), either horizontally or // verically, into a floating point number, which is the real or imaginary // number the position represents. The scale factor is to compensate for the // non-square-ness of the pixels. double coordinate(double scale, int pos, int full, double offset) { return size * scale * (pos - full / 2.0) / full - offset; } // Called by each thread to fill in the thread's allotted slots in the result // matrix. void* executor(void* ptr) { long index = (long) ptr; for (int row = 0; row < window_height; ++row) { double y = coordinate(0.6, row, window_height, y_offset); for (int col = index; col < window_width; col += NR_OF_THREADS) { double x = coordinate(1.0, col, window_width, -x_offset); result[row][col] = (iterations(x, y) - 1) * NR_OF_COLORS / max; } } return NULL; } // Do the calulations for the entire picture in threads. void calculate() { pthread_t threads[NR_OF_THREADS]; for (long t = 0; t < NR_OF_THREADS; ++t) { if (pthread_create(&threads[t], NULL, executor, (void*) t)) { fprintf(stderr, "Error creating thread\n"); return; } } for (long t = 0; t < NR_OF_THREADS; ++t) { if (pthread_join(threads[t], NULL)) { fprintf(stderr, "Error joining thread\n"); return; } } } // Print the result. void draw() { printf("\033[0;0H"); // Set cursor at top left. for (int row = 0; row < window_height; row += 2) { int previous_fg = -1, previous_bg = -1; for (int col = 0; col < window_width; ++col) { int bg = COLORS[result[row][col]]; int fg = COLORS[result[row + 1][col]]; if (previous_bg == bg && previous_fg == fg) printf("▄"); else { printf("\e[38;5;%dm\e[48;5;%dm▄", fg, bg); previous_fg = fg; previous_bg = bg; } } printf("\e[0m\n"); } } // Find out the current number of rows and columns in the terminal, set global // variables, and reallocate the result matrix. void set_window_size() { struct winsize w; ioctl(STDOUT_FILENO, TIOCGWINSZ, &w); for (int row = 0; row < window_height; ++row) free(result[row]); if (window_height > 0) free(result); window_height = 2 * (w.ws_row - 1); window_width = w.ws_col; result = malloc(window_height * sizeof(int*)); for (int row = 0; row < window_height; ++row) result[row] = malloc(window_width * sizeof(int)); } int main(int argc, char** argv) { for (int ix = 1; ix < argc; ++ix) { const char* arg = argv[ix]; switch (arg[0]) { case 'X': sscanf(arg, "X:%le", &x_offset); break; case 'Y': sscanf(arg, "Y:%le", &y_offset); break; case 'S': sscanf(arg, "S:%le", &size); break; case 'M': sscanf(arg, "M:%d", &max); break; } } while (1) { char line[1024]; char legend[200]; set_window_size(); calculate(); draw(); sprintf(legend, "X:%.10f Y:%.10f S:%e M:%d [%dx%d]", x_offset, y_offset, size, max, window_width, window_height); printf("\e];%s\007", legend); printf("%s (U)p,(D)own,(L)eft,(R)ight,(I)n,(O)ut,(P)lus,(M)inus > ", legend); if (fgets(line, sizeof(line), stdin)) { for (const char* ptr = &line[0]; *ptr; ++ptr) { char c = tolower(*ptr); switch (c) { case 'u': case 'd': y_offset += (c == 'u') ? size/3 : -size/3; break; case 'l': case 'r': x_offset += (c == 'l') ? -size/3 : size/3; break; case 'i': case 'o': size *= (c == 'i') ? 0.5 : 2; c = (c == 'i') ? 'p' : 'm'; // Fall through case 'p': case 'm': max = (c == 'p') ? max * 5 / 4 : max * 4 / 5; break; } } } } }
605294156/XCModuleManager
XCModuleManager/XCModuleManager.h
// // XCModuleManager.h // // // Created by XiaoCheng on 05/08/2019. // Copyright © 2019 赵思集团. All rights reserved. // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN @import UIKit; @protocol XCModule <UIApplicationDelegate> @end @interface XCModuleManager : NSObject<UIApplicationDelegate> + (instancetype)sharedInstance; - (void)loadModulesWithPlistFile:(NSString *)plistFile; - (NSArray<id<XCModule>> *)allModules; @end NS_ASSUME_NONNULL_END
hananiahhsu/OpenCAD
XUXUCAM/CamCores/CamGeneration/cam_xmloutput.h
#ifndef CAM_XMLOUTPUT_H #define CAM_XMLOUTPUT_H /* ************************************ *** @<NAME> *** @2017.05.10 *** @NanJing,China *** @<EMAIL> ************************************ */ #endif // CAM_XMLOUTPUT_H
hananiahhsu/OpenCAD
XUXUCAM/CamCores/CamEng/cam_pen.h
#ifndef CAM_PEN_H #define CAM_PEN_H /* ************************************ *** @<NAME> *** @2017.05.10 *** @NanJing,China *** @<EMAIL> ************************************ */ class Cam_Pen { public: Cam_Pen() {} virtual~Cam_Pen(); public: }; #endif // CAM_PEN_H
hananiahhsu/OpenCAD
XUXUCAM/CamCores/CamEng/cam_entity.h
#ifndef CAM_ENTITY_H #define CAM_ENTITY_H #include "CamCores/CamEng/cam_entity_container.h" #include "CamCores/CamEng/cam_vector.h" /* ************************************ *** @<NAME> *** @2017.05.10 *** @NanJing,China *** @<EMAIL> ************************************ */ //Abstr virtual Class(interfaces supplied) class Cam_Entity { public: Cam_Entity(); Cam_Entity(Cam_Entity_Container* father=nullptr); virtual~Cam_Entity()=default; public: //All functions void Init(); virtual void InitId(); virtual Cam_Entity* Clone()const=0; virtual void DuplicateFather(Cam_Entity_Container* father); void CamResetBorders(); void CamSetBorders(); void CamScaleBorders(const Cam_Vector& bias); void CamMoveBorders(const Cam_Vector& ori,const Cam_Vector& ratio); public: //all variables protected: //Father or nullPtr(no father) Cam_Entity_Container *e_father; //Id of entity unsigned long int e_id; // }; #endif // CAM_ENTITY_H
hananiahhsu/OpenCAD
XUXUCAM/CamCores/CamEng/cam_layerlist.h
#ifndef CAM_LAYERLIST_H #define CAM_LAYERLIST_H /* ************************************ *** @<NAME> *** @2017.05.10 *** @NanJing,China *** @<EMAIL> ************************************ */ class Cam_LayerList { public: Cam_LayerList() {} virtual ~Cam_LayerList(); public: }; #endif // CAM_LAYERLIST_H
hananiahhsu/OpenCAD
XUXUCAM/CamCores/CamEng/cam_math.h
#ifndef CAM_MATH_H #define CAM_MATH_H #include <vector> class Cam_Vector; //class RS_VectorSolutions; class QString; class Cam_Math { private: Cam_Math() = delete; public: static int round(double v); static double pow(double x, double y); static Cam_Vector pow(Cam_Vector x, double y); static double rad2deg(double a); static double deg2rad(double a); static double rad2gra(double a); static double gra2rad(double a); static unsigned findGCD(unsigned a, unsigned b); static bool isAngleBetween(double a, double a1, double a2, bool reversed = false); //! \brief correct angle to be within [0, 2 Pi) static double correctAngle(double a); //! \brief correct angle to be undirectional [0, Pi) static double correctAngleU(double a); //! \brief angular difference static double getAngleDifference(double a1, double a2, bool reversed = false); /** * @brief getAngleDifferenceU abs of minimum angular differenct, unsigned version of angular difference * @param a1,a2 angles * @return the minimum of angular difference a1-a2 and a2-a1 */ static double getAngleDifferenceU(double a1, double a2); static double makeAngleReadable(double angle, bool readable=true, bool* corrected=nullptr); static bool isAngleReadable(double angle); static bool isSameDirection(double dir1, double dir2, double tol); //! \{ \brief evaluate a math string static double eval(const QString& expr, double def=0.0); static double eval(const QString& expr, bool* ok); //! \} static std::vector<double> quadraticSolver(const std::vector<double>& ce); static std::vector<double> cubicSolver(const std::vector<double>& ce); /** quartic solver * x^4 + ce[0] x^3 + ce[1] x^2 + ce[2] x + ce[3] = 0 @ce, a vector of size 4 contains the coefficient in order @return, a vector contains real roots **/ static std::vector<double> quarticSolver(const std::vector<double>& ce); /** quartic solver * ce[4] x^4 + ce[3] x^3 + ce[2] x^2 + ce[1] x + ce[0] = 0 @ce, a vector of size 5 contains the coefficient in order @return, a vector contains real roots **/ static std::vector<double> quarticSolverFull(const std::vector<double>& ce); //solver for linear equation set /** * Solve linear equation set *@param mt holds the augmented matrix *@param sn holds the solution *@param return true, if the equation set has a unique solution, return false otherwise * *@author: <NAME> */ static bool linearSolver(const std::vector<std::vector<double> >& m, std::vector<double>& sn); /** solver quadratic simultaneous equations of a set of two **/ /* solve the following quadratic simultaneous equations, * ma000 x^2 + ma011 y^2 - 1 =0 * ma100 x^2 + 2 ma101 xy + ma111 y^2 + mb10 x + mb11 y +mc1 =0 * *@m, a vector of size 8 contains coefficients in the strict order of: ma000 ma011 ma100 ma101 ma111 mb10 mb11 mc1 *@return a RS_VectorSolutions contains real roots (x,y) */ static RS_VectorSolutions simultaneousQuadraticSolver(const std::vector<double>& m); /** solver quadratic simultaneous equations of a set of two **/ /** solve the following quadratic simultaneous equations, * ma000 x^2 + ma001 xy + ma011 y^2 + mb00 x + mb01 y + mc0 =0 * ma100 x^2 + ma101 xy + ma111 y^2 + mb10 x + mb11 y + mc1 =0 * *@param m a vector of size 2 each contains a vector of size 6 coefficients in the strict order of: ma000 ma001 ma011 mb00 mb01 mc0 ma100 ma101 ma111 mb10 mb11 mc1 *@return a RS_VectorSolutions contains real roots (x,y) */ static RS_VectorSolutions simultaneousQuadraticSolverFull(const std::vector<std::vector<double> >& m); static RS_VectorSolutions simultaneousQuadraticSolverMixed(const std::vector<std::vector<double> >& m); /** \brief verify simultaneousQuadraticVerify a solution for simultaneousQuadratic *@param m the coefficient matrix *@param v a candidate to verify *@return true, for a valid solution **/ static bool simultaneousQuadraticVerify(const std::vector<std::vector<double> >& m, RS_Vector& v); /** wrapper for elliptic integral **/ /** * wrapper of elliptic integral of the second type, Legendre form *@k the elliptic modulus or eccentricity *@phi elliptic angle, must be within range of [0, M_PI] * *@\author: <NAME> */ static double ellipticIntegral_2(const double& k, const double& phi); static QString doubleToString(double value, double prec); static QString doubleToString(double value, int prec); static void test(); }; #endif // CAM_MATH_H
hananiahhsu/OpenCAD
XUXUCAM/dxfSrc/dl_creationadapter.h
/**************************************************************************** ** $Id: dl_creationadapter.h 8865 2008-02-04 18:54:02Z andrew $ ** ** Copyright (C) 2001-2003 RibbonSoft. All rights reserved. ** ** This file is part of the dxflib project. ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** ** Licensees holding valid dxflib Professional Edition licenses may use ** this file in accordance with the dxflib Commercial License ** Agreement provided with the Software. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.ribbonsoft.com for further details. ** ** Contact <EMAIL> if any conditions of this licensing are ** not clear to you. ** **********************************************************************/ #ifndef DL_CREATIONADAPTER_H #define DL_CREATIONADAPTER_H #include "dl_creationinterface.h" /** * An abstract adapter class for receiving DXF events when a DXF file is being read. * The methods in this class are empty. This class exists as convenience for creating * listener objects. * * @author <NAME> */ class DL_CreationAdapter : public DL_CreationInterface { public: DL_CreationAdapter() {} virtual ~DL_CreationAdapter() {} virtual void addLayer(const DL_LayerData&) {} virtual void addBlock(const DL_BlockData&) {} virtual void endBlock() {} virtual void addPoint(const DL_PointData&) {} virtual void addLine(const DL_LineData&) {} virtual void addArc(const DL_ArcData&) {} virtual void addCircle(const DL_CircleData&) {} virtual void addEllipse(const DL_EllipseData&) {} virtual void addPolyline(const DL_PolylineData&) {} virtual void addVertex(const DL_VertexData&) {} virtual void addSpline(const DL_SplineData&) {} virtual void addControlPoint(const DL_ControlPointData&) {} virtual void addKnot(const DL_KnotData&) {} virtual void addInsert(const DL_InsertData&) {} virtual void addMText(const DL_MTextData&) {} virtual void addMTextChunk(const char*) {} virtual void addText(const DL_TextData&) {} virtual void addDimAlign(const DL_DimensionData&, const DL_DimAlignedData&) {} virtual void addDimLinear(const DL_DimensionData&, const DL_DimLinearData&) {} virtual void addDimRadial(const DL_DimensionData&, const DL_DimRadialData&) {} virtual void addDimDiametric(const DL_DimensionData&, const DL_DimDiametricData&) {} virtual void addDimAngular(const DL_DimensionData&, const DL_DimAngularData&) {} virtual void addDimAngular3P(const DL_DimensionData&, const DL_DimAngular3PData&) {} virtual void addDimOrdinate(const DL_DimensionData&, const DL_DimOrdinateData&) {} virtual void addLeader(const DL_LeaderData&) {} virtual void addLeaderVertex(const DL_LeaderVertexData&) {} virtual void addHatch(const DL_HatchData&) {} virtual void addTrace(const DL_TraceData&) {} virtual void add3dFace(const DL_3dFaceData&) {} virtual void addSolid(const DL_SolidData&) {} virtual void addImage(const DL_ImageData&) {} virtual void linkImage(const DL_ImageDefData&) {} virtual void addHatchLoop(const DL_HatchLoopData&) {} virtual void addHatchEdge(const DL_HatchEdgeData&) {} virtual void endEntity() {} virtual void addComment(const char* comment) {} virtual void setVariableVector(const char*, double, double, double, int) {} virtual void setVariableString(const char*, const char*, int) {} virtual void setVariableInt(const char*, int, int) {} virtual void setVariableDouble(const char*, double, int) {} virtual void endSequence() {} }; #endif
hananiahhsu/OpenCAD
XUXUCAM/CamDxf/camleads.h
<reponame>hananiahhsu/OpenCAD #ifndef CAMLEADS_H #define CAMLEADS_H /* ************************************ *** @<NAME> *** @2017.05.10 *** @NanJing,China *** @<EMAIL> ************************************ */ #include "CamDxf/qpointfwithparent.h" #include "CamDxf/campart.h" #include <QtGui> #include <QGraphicsItem> //Forward declaration class Lead; class Loop; /// A line linking between the lead-in and lead-out class Edge : public QGraphicsItem { public: /** * construct an edge between the source and destination lead in/out * @param sourceLead the lead-in to link to * @param destLead the lead-out to link to */ Edge(Lead *sourceLead,Lead *destLead); ~Edge(); /** * called to update the edge parameters before repainting */ void adjust(); protected: QRectF boundingRect() const; void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); private: QSettings settings; Lead *source, *dest; /// the associated source lead posisition QPointF sourcePoint; /// for graphical representation of the laser path between lead-in/out //double leadRadiusMotion; /// the associated destiation lead posisition QPointF destPoint; /// the size of the arrow at the end of the edge qreal arrowSize; }; /// A QGraphicsEllipseItem represanting graphically the lead in/out class Lead: public QGraphicsItem { public : ///constructor for leads certain/uncertain /** * Construct a lead and attach it to loop * @param loop the loop the lead-in belongs to */ Lead (Loop *loop); /// @todo create a more meaningfull constructor /// Construct the the Lead out= lead touch and attach it to loop Lead(Loop *loop,int j ); virtual ~Lead(); void paint(QPainter *painter, const QStyleOptionGraphicsItem*, QWidget *); QRectF boundingRect() const {return myBoundingRect; } QPainterPath shape() const{QPainterPath path; path.addEllipse(myBoundingRect);return path;} int type() const { return Type; } QRectF myBoundingRect; enum { Type = UserType + 2 }; /// the lead can be an uncertain/certain lead-in (in which case it's drawn in a diferent color) or a lead-out enum Leadtype {LeadCertain=0x1,LeadUncertain=0x2,LeadTouch=0x3}; Q_DECLARE_FLAGS(leadTypes, Leadtype) Lead::leadTypes leadType; Loop *myLoop; /// the currtn lead position QPointFWithParent *myPos; /// the lead-out position QPointFWithParent leadTouch; /// the associated edge @see edge Edge *myEdge; /** * Set myedge to the given edge * @param edge */ void setEdge(Edge *edge){myEdge=edge;} ///the ellipse container (rectangle) QRectF laserRect; /// for graphical representation of the laser lead-in/out double leadRadius; QSettings settings; protected: /// called by QGraphicsItem to notify custom items that some part of the item's state changes. QVariant itemChange(GraphicsItemChange change, const QVariant &value); void mousePressEvent(QGraphicsSceneMouseEvent *event); void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); void mouseMoveEvent(QGraphicsSceneMouseEvent *event); //void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event); }; Q_DECLARE_OPERATORS_FOR_FLAGS(Lead::leadTypes) #endif // CAMLEADS_H
hananiahhsu/OpenCAD
XUXUCAM/CamUi/CamUiForms/cam_blockdlg.h
#ifndef CAM_BLOCKDLG_H #define CAM_BLOCKDLG_H /* ************************************ *** @<NAME> *** @2017.05.10 *** @NanJing,China *** @<EMAIL> ************************************ */ #endif // CAM_BLOCKDLG_H
hananiahhsu/OpenCAD
XUXUCAM/CamCores/CamInfo/cam_position.h
<filename>XUXUCAM/CamCores/CamInfo/cam_position.h #ifndef CAM_POSITION_H #define CAM_POSITION_H /* ************************************ *** @<NAME> *** @2017.05.10 *** @NanJing,China *** @<EMAIL> ************************************ */ #endif // CAM_POSITION_H
hananiahhsu/OpenCAD
XUXUCAM/CamCores/CamEng/cam_entity_container.h
<reponame>hananiahhsu/OpenCAD #ifndef CAM_ENTITY_CONTAINER_H #define CAM_ENTITY_CONTAINER_H /* ************************************ *** @<NAME> *** @2017.05.10 *** @NanJing,China *** @<EMAIL> ************************************ */ class Cam_Entity_Container { public: Cam_Entity_Container(); virtual ~Cam_Entity_Container(); }; #endif // CAM_ENTITY_CONTAINER_H
hananiahhsu/OpenCAD
XUXUCAM/CamUi/CamUiBasic/cam_workshop.h
#ifndef CAM_WORKSHOP_H #define CAM_WORKSHOP_H /* ************************************ *** @<NAME> *** @2017.05.10 *** @NanJing,China *** @<EMAIL> ************************************ */ #endif // CAM_WORKSHOP_H
hananiahhsu/OpenCAD
XUXUCAM/CamCores/CamDebug/cam_debug.h
<reponame>hananiahhsu/OpenCAD #ifndef CAM_DEBUG_H #define CAM_DEBUG_H #endif // CAM_DEBUG_H
hananiahhsu/OpenCAD
XUXUCAM/CamDxf/camscene.h
<gh_stars>10-100 #ifndef CAMSCENE_H #define CAMSCENE_H /* ************************************ *** @<NAME> *** @2017.05.10 *** @NanJing,China *** @<EMAIL> ************************************ */ #include <QtGui> #include <QWidget> #include <QGraphicsScene> #include <QGraphicsLineItem> #include <QGraphicsView> #include <QGraphicsSceneEvent> /// A special QGraphicsScene used for previewing a part or placing parts class CamScene: public QGraphicsScene { Q_OBJECT public: /// we use modes to track the approriate thing to do ZOOm selcetc lezad, select loops ,... inspired from qdiagramme example enum Mode { MoveItem, Zoom ,selectLoops,selectLeads}; /** * * @param preview if true the scene is used to preview the part, else it's for parts placement * @param parent the QGraphicsView parent */ CamScene(bool preview=true,QWidget *parent = 0); ///used for animating the cutter tool QBasicTimer timer; ///Penr of the line drawn when moving the tool QPen toolPen; ///@todo: use shape to detect if some parts are otu of the sheet within a margin. /// Rectangle representing the sheet metal bounds if preview isn't set ///@see preview QGraphicsRectItem *sheetRect; void setMode(Mode mode){myMode=mode;} /** * Set the sheetRect rectangle * @param rect new Sheetrect value */ void setSheetRect(); /** * Moves the Pixmap of the cutter tool to the specfied point * @param endPoint Point coordinates to move the tool to */ void moveTool(QPointF endPoint); public slots: // /** * Start the animation of the cutter OR Clean the scene * @param end if set Clean the scen else start the animation */ void cleanUpAnim(bool end=false); /** * Zoom to show all the parts in the scene */ void zoomFit(); /** * Zoom in / out by a factor * @param in if set to true Zoom in else zoom Out */ void zoom(bool in=true); protected: void mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent); //void mouseMoveEvent(QGraphicsSceneMouseEvent *mouseEvent); void mouseReleaseEvent(QGraphicsSceneMouseEvent *mouseEvent); void wheelEvent(QGraphicsSceneWheelEvent *mouseEvent); void timerEvent(QTimerEvent *event); signals: /** * Used to track the loop being drawn in animation mode * @param currentLoop The loop pos to draw */ void progressionDone(const int currentLoop); /// inform the mainUi that the retc zoom had been drawn void zoomRect(QPointF p1,QPointF p2); private: Mode myMode; ///access The application config settings for colors/preferences QSettings settings; /// to track the selection (not in preview mode) bool selectedSome; /// @note: a sheet can be for part previews or for parts placing( sheet metal) /**If set the sheet is for part preview else its for parts placement */ bool preview; }; #endif // CAMSCENE_H
hananiahhsu/OpenCAD
XUXUCAM/dxfSrc/dl_dxf.h
<gh_stars>10-100 /**************************************************************************** ** $Id: dl_dxf.h 8865 2008-02-04 18:54:02Z andrew $ ** ** Copyright (C) 2001-2003 RibbonSoft. All rights reserved. ** ** This file is part of the dxflib project. ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** ** Licensees holding valid dxflib Professional Edition licenses may use ** this file in accordance with the dxflib Commercial License ** Agreement provided with the Software. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.ribbonsoft.com for further details. ** ** Contact <EMAIL> if any conditions of this licensing are ** not clear to you. ** **********************************************************************/ #ifndef DL_DXF_H #define DL_DXF_H #include <stdio.h> #include <stdlib.h> #include <string.h> #ifndef __GCC2x__ #include <sstream> #endif #include "dl_attributes.h" #include "dl_codes.h" #include "dl_entities.h" #include "dl_writer_ascii.h" #ifdef _WIN32 #undef M_PI #define M_PI 3.14159265358979323846 #pragma warning(disable : 4800) #endif #ifndef M_PI #define M_PI 3.1415926535897932384626433832795 #endif class DL_CreationInterface; class DL_WriterA; #define DL_VERSION "2.2.0.0" #define DL_UNKNOWN 0 #define DL_LAYER 10 #define DL_BLOCK 11 #define DL_ENDBLK 12 #define DL_LINETYPE 13 #define DL_SETTING 50 #define DL_ENTITY_POINT 100 #define DL_ENTITY_LINE 101 #define DL_ENTITY_POLYLINE 102 #define DL_ENTITY_LWPOLYLINE 103 #define DL_ENTITY_VERTEX 104 #define DL_ENTITY_SPLINE 105 #define DL_ENTITY_KNOT 106 #define DL_ENTITY_CONTROLPOINT 107 #define DL_ENTITY_ARC 108 #define DL_ENTITY_CIRCLE 109 #define DL_ENTITY_ELLIPSE 110 #define DL_ENTITY_INSERT 111 #define DL_ENTITY_TEXT 112 #define DL_ENTITY_MTEXT 113 #define DL_ENTITY_DIMENSION 114 #define DL_ENTITY_LEADER 115 #define DL_ENTITY_HATCH 116 #define DL_ENTITY_ATTRIB 117 #define DL_ENTITY_IMAGE 118 #define DL_ENTITY_IMAGEDEF 119 #define DL_ENTITY_TRACE 120 #define DL_ENTITY_SOLID 121 #define DL_ENTITY_3DFACE 122 #define DL_ENTITY_SEQEND 123 /** * Reading and writing of DXF files. * * This class can read in a DXF file and calls methods from the * interface DL_EntityContainer to add the entities to the * contianer provided by the user of the library. * * It can also be used to write DXF files to a certain extent. * * When saving entities, special values for colors and linetypes * can be used: * * Special colors are 0 (=BYBLOCK) and 256 (=BYLAYER). * Special linetypes are "BYLAYER" and "BYBLOCK". * * @author <NAME> */ class DL_Dxf { public: DL_Dxf(); ~DL_Dxf(); bool in(const string& file, DL_CreationInterface* creationInterface); bool readDxfGroups(FILE* fp, DL_CreationInterface* creationInterface, int* errorCounter = NULL); static bool getChoppedLine(char* s, unsigned int size, FILE *stream); #ifndef __GCC2x__ bool readDxfGroups(std::stringstream &stream, DL_CreationInterface* creationInterface, int* errorCounter = NULL); bool in(std::stringstream &stream, DL_CreationInterface* creationInterface); static bool getChoppedLine(char *s, unsigned int size, std::stringstream &stream); #endif static bool stripWhiteSpace(char** s); bool processDXFGroup(DL_CreationInterface* creationInterface, int groupCode, const char* groupValue); void addSetting(DL_CreationInterface* creationInterface); void addLayer(DL_CreationInterface* creationInterface); void addBlock(DL_CreationInterface* creationInterface); void endBlock(DL_CreationInterface* creationInterface); void addPoint(DL_CreationInterface* creationInterface); void addLine(DL_CreationInterface* creationInterface); void addPolyline(DL_CreationInterface* creationInterface); void addVertex(DL_CreationInterface* creationInterface); void addSpline(DL_CreationInterface* creationInterface); //void addKnot(DL_CreationInterface* creationInterface); //void addControlPoint(DL_CreationInterface* creationInterface); void addArc(DL_CreationInterface* creationInterface); void addCircle(DL_CreationInterface* creationInterface); void addEllipse(DL_CreationInterface* creationInterface); void addInsert(DL_CreationInterface* creationInterface); void addTrace(DL_CreationInterface* creationInterface); void add3dFace(DL_CreationInterface* creationInterface); void addSolid(DL_CreationInterface* creationInterface); void addMText(DL_CreationInterface* creationInterface); bool handleMTextData(DL_CreationInterface* creationInterface); bool handleLWPolylineData(DL_CreationInterface* creationInterface); bool handleSplineData(DL_CreationInterface* creationInterface); bool handleLeaderData(DL_CreationInterface* creationInterface); bool handleHatchData(DL_CreationInterface* creationInterface); void addText(DL_CreationInterface* creationInterface); void addAttrib(DL_CreationInterface* creationInterface); DL_DimensionData getDimData(); void addDimLinear(DL_CreationInterface* creationInterface); void addDimAligned(DL_CreationInterface* creationInterface); void addDimRadial(DL_CreationInterface* creationInterface); void addDimDiametric(DL_CreationInterface* creationInterface); void addDimAngular(DL_CreationInterface* creationInterface); void addDimAngular3P(DL_CreationInterface* creationInterface); void addDimOrdinate(DL_CreationInterface* creationInterface); void addLeader(DL_CreationInterface* creationInterface); void addHatch(DL_CreationInterface* creationInterface); void addImage(DL_CreationInterface* creationInterface); void addImageDef(DL_CreationInterface* creationInterface); void addComment(DL_CreationInterface* creationInterface, const char* comment); void endEntity(DL_CreationInterface* creationInterface); void endSequence(DL_CreationInterface* creationInterface); int stringToInt(const char* s, bool* ok=NULL); DL_WriterA* out(const char* file, DL_Codes::version version=VER_2000); void writeHeader(DL_WriterA& dw); void writePoint(DL_WriterA& dw, const DL_PointData& data, const DL_Attributes& attrib); void writeLine(DL_WriterA& dw, const DL_LineData& data, const DL_Attributes& attrib); void writePolyline(DL_WriterA& dw, const DL_PolylineData& data, const DL_Attributes& attrib); void writeVertex(DL_WriterA& dw, const DL_VertexData& data); void writePolylineEnd(DL_WriterA& dw); void writeSpline(DL_WriterA& dw, const DL_SplineData& data, const DL_Attributes& attrib); void writeControlPoint(DL_WriterA& dw, const DL_ControlPointData& data); void writeKnot(DL_WriterA& dw, const DL_KnotData& data); void writeCircle(DL_WriterA& dw, const DL_CircleData& data, const DL_Attributes& attrib); void writeArc(DL_WriterA& dw, const DL_ArcData& data, const DL_Attributes& attrib); void writeEllipse(DL_WriterA& dw, const DL_EllipseData& data, const DL_Attributes& attrib); void writeSolid(DL_WriterA& dw, const DL_SolidData& data, const DL_Attributes& attrib); void write3dFace(DL_WriterA& dw, const DL_3dFaceData& data, const DL_Attributes& attrib); void writeInsert(DL_WriterA& dw, const DL_InsertData& data, const DL_Attributes& attrib); void writeMText(DL_WriterA& dw, const DL_MTextData& data, const DL_Attributes& attrib); void writeText(DL_WriterA& dw, const DL_TextData& data, const DL_Attributes& attrib); void writeDimAligned(DL_WriterA& dw, const DL_DimensionData& data, const DL_DimAlignedData& edata, const DL_Attributes& attrib); void writeDimLinear(DL_WriterA& dw, const DL_DimensionData& data, const DL_DimLinearData& edata, const DL_Attributes& attrib); void writeDimRadial(DL_WriterA& dw, const DL_DimensionData& data, const DL_DimRadialData& edata, const DL_Attributes& attrib); void writeDimDiametric(DL_WriterA& dw, const DL_DimensionData& data, const DL_DimDiametricData& edata, const DL_Attributes& attrib); void writeDimAngular(DL_WriterA& dw, const DL_DimensionData& data, const DL_DimAngularData& edata, const DL_Attributes& attrib); void writeDimAngular3P(DL_WriterA& dw, const DL_DimensionData& data, const DL_DimAngular3PData& edata, const DL_Attributes& attrib); void writeDimOrdinate(DL_WriterA& dw, const DL_DimensionData& data, const DL_DimOrdinateData& edata, const DL_Attributes& attrib); void writeLeader(DL_WriterA& dw, const DL_LeaderData& data, const DL_Attributes& attrib); void writeLeaderVertex(DL_WriterA& dw, const DL_LeaderVertexData& data); void writeHatch1(DL_WriterA& dw, const DL_HatchData& data, const DL_Attributes& attrib); void writeHatch2(DL_WriterA& dw, const DL_HatchData& data, const DL_Attributes& attrib); void writeHatchLoop1(DL_WriterA& dw, const DL_HatchLoopData& data); void writeHatchLoop2(DL_WriterA& dw, const DL_HatchLoopData& data); void writeHatchEdge(DL_WriterA& dw, const DL_HatchEdgeData& data); int writeImage(DL_WriterA& dw, const DL_ImageData& data, const DL_Attributes& attrib); void writeImageDef(DL_WriterA& dw, int handle, const DL_ImageData& data); void writeLayer(DL_WriterA& dw, const DL_LayerData& data, const DL_Attributes& attrib); void writeLineType(DL_WriterA& dw, const DL_LineTypeData& data); void writeAppid(DL_WriterA& dw, const string& name); void writeBlock(DL_WriterA& dw, const DL_BlockData& data); void writeEndBlock(DL_WriterA& dw, const string& name); void writeVPort(DL_WriterA& dw); void writeStyle(DL_WriterA& dw); void writeView(DL_WriterA& dw); void writeUcs(DL_WriterA& dw); void writeDimStyle(DL_WriterA& dw, double dimasz, double dimexe, double dimexo, double dimgap, double dimtxt); void writeBlockRecord(DL_WriterA& dw); void writeBlockRecord(DL_WriterA& dw, const string& name); void writeObjects(DL_WriterA& dw); void writeObjectsEnd(DL_WriterA& dw); void writeComment(DL_WriterA& dw, const string& comment); /** * Converts the given string into a double or returns the given * default valud (def) if value is NULL or empty. */ static double toReal(const char* value, double def=0.0) { if (value!=NULL && value[0] != '\0') { double ret; if (strchr(value, ',') != NULL) { char* tmp = new char[strlen(value)+1]; strcpy(tmp, value); DL_WriterA::strReplace(tmp, ',', '.'); ret = atof(tmp); delete[] tmp; } else { ret = atof(value); } return ret; } else { return def; } } /** * Converts the given string into an int or returns the given * default valud (def) if value is NULL or empty. */ static int toInt(const char* value, int def=0) { if (value!=NULL && value[0] != '\0') { return atoi(value); } else { return def; } } /** * Converts the given string into a string or returns the given * default valud (def) if value is NULL or empty. */ static const char* toString(const char* value, const char* def="") { if (value!=NULL && value[0] != '\0') { return value; } else { return def; } } static bool checkVariable(const char* var, DL_Codes::version version); DL_Codes::version getVersion() { return version; } int getLibVersion(const char* str); static void test(); private: DL_Codes::version version; unsigned long styleHandleStd; string polylineLayer; double* vertices; int maxVertices; int vertexIndex; double* knots; int maxKnots; int knotIndex; double* controlPoints; int maxControlPoints; int controlPointIndex; double* leaderVertices; int maxLeaderVertices; int leaderVertexIndex; // array of hatch loops DL_HatchLoopData* hatchLoops; int maxHatchLoops; int hatchLoopIndex; // array in format [loop#][edge#] DL_HatchEdgeData** hatchEdges; int* maxHatchEdges; int* hatchEdgeIndex; bool dropEdges; // Bulge for the next vertex. double bulge; // Only the useful part of the group code char groupCodeTmp[DL_DXF_MAXLINE+1]; // ...same as integer unsigned int groupCode; // Only the useful part of the group value char groupValue[DL_DXF_MAXLINE+1]; // Current entity type int currentEntity; // Value of the current setting char settingValue[DL_DXF_MAXLINE+1]; // Key of the current setting (e.g. "$ACADVER") char settingKey[DL_DXF_MAXLINE+1]; // Stores the group codes char values[DL_DXF_MAXGROUPCODE][DL_DXF_MAXLINE+1]; // First call of this method. We initialize all group values in // the first call. bool firstCall; // Attributes of the current entity (layer, color, width, line type) DL_Attributes attrib; // library version. hex: 0x20003001 = 2.0.3.1 int libVersion; }; #endif // EOF
hananiahhsu/OpenCAD
XUXUCAM/CamDxf/campart.h
<filename>XUXUCAM/CamDxf/campart.h #ifndef CAMPART_H #define CAMPART_H /* ************************************ *** @<NAME> *** @2017.05.10 *** @NanJing,China *** @<EMAIL> ************************************ */ #include "CamDxf/qpointfwithparent.h" #include "camleads.h" #include <QtGui> #include <QGraphicsItem> /** A part is a QGraphicsItem composed by a number of internal loops, its outline and the lead-in out points */ ///@todo show possible start poits (the user may want to change the lead point for route/space /// A QGraphicItem representing a loop (closed or not) class Loop : public QGraphicsItem{ /// @todo use qobject to allow passing parent and using Tr inside getLoopNumber manullay //Q_OBJECT public: Loop(QGraphicsItem * parent = 0); QRectF boundingRect() const { return qtRect; } QPainterPath shape() const { return loopShape; } ///curretn loop rect QRectF qtRect ; ///curretn loop shape QPainterPath loopShape; ///loop shape without any modif (text for now...) QPainterPath originalShape; QSettings settings; /// Pen for basic drawing QPen myPen; /// Pen for seledted loops drawing QPen selectedPen; /// Pen for seledted loops drawing QPen unSelectedPen; /// Pen for loops outline drawing QPen outlinePen; ///weither or not to display loop number @todo have to get it from settings bool showText; /** * set the current painting pen to selection */ //void setSelected(){myPen=selectedPen;} /// set the original loop path entity by entity void addPath(QPainterPath pathToAdd); ///add a text path to the originalShape path void addTextPath(QPainterPath pathToAdd); ///Loop number in the current part int loopNumber; ///Weither or not the loop is a circle bool isCircle; ///Used to mark the outline loop (in plasma mode) bool isOutline; ///Used to mark the closed loops (in plasma mode) bool isClosed; ///used to stat painting the path when appropriate bool ready; /// Lead-In position for this loop QPointFWithParent leadIn; /// Lead out position for this loop QPointFWithParent leadOut; /// the loop start point. If it's a closed one, then startPoint=endPoint QPointFWithParent startPoint; /// the loop start point. If it's a closed one, then startPoint=endPoint QPointFWithParent endPoint; /// @note Remove touchPoin and use eiher Start or endPoint instead for both g-code and Optimi QPointFWithParent touchPoint; void setIsClosed (bool stat) { isClosed =stat;} void setReady(bool b){ready=b;if (b) update();} /** * Set the loop start point * @param sP new loop start point */ void setStart(QPointFWithParent sP){startPoint=sP;} /** * Set the loop end point * @param sP new loop end point */ void setEnd(QPointFWithParent eP){endPoint=eP;} /** * Mark the loop as part's outline if s * @param s weither or not the loop is the outline */ void setIsOutline(bool s){ update(); isOutline=s; } /** * Set the loop order when cutting it * @param nbr the new loop number */ void setNumber(int nbr);//{loopNumber=nbr;} /** * Identify the loop as a circle * @param type */ void setTypeCircle(bool type){isCircle=type;} /** * Set the loop lead-in position * @param p lead-in coord */ void setLeadIn(QPointFWithParent p){leadIn=p;} /** * Set the loop lead-out position * @param p lead-out coord */ void setTouchPoint(QPointFWithParent p){touchPoint=p;} /// the set of Points making the loop QPFWPVector entities; /** * set the loop entities * @param ts point set */ void setEntities(QPFWPVector ts); /** * * @return the entities forming the loop */ QPFWPVector getEntities(){return entities;} QVariant itemChange(GraphicsItemChange change, const QVariant &value); void paint(QPainter *painter, const QStyleOptionGraphicsItem*, QWidget *); protected: virtual void mouseDoubleClickEvent ( QGraphicsSceneMouseEvent * event ); }; /// A part is a set of organised loops. class Part: public QGraphicsItem // Qobject is needed for sending signals to alert about errenous parts { // Q_OBJECT public: ///@todo: cleanup this constructor ///@todo use set/get in naming /// value used when moving the part by keyboar static double movePartVal; /** * set movePartVal to val * @param val distance the part will be translated with @see movePartVal */ static void setMovePartVal(double val); /** * Setup the part for G-code generation * @param shape The part shape * @param pointsList The points list * @param partPathsList The paths forming the part * @param circlePointsList The circles points list * @param circlesPathsList the circles path list */ Part(const QPainterPath shape,QPFWPVector pointsList,QPPVector partPathsList,QPFWPVector circlePointsList,QPPVector circlesPathsList); /// used to create a copy on the sheet metal of the current part Part(const Part &parentPart); virtual ~Part(); QRectF boundingRect() const { return qtRect; } /// @note : to implement collison detection and part selection Qt refers to Shape or as when drawing the part outline QPainterPath shape() const { return partOutShape; } /// define the part shape for geometry collision and painting QPainterPath partShape; /// used for selection along with partshape QRectF qtRect ; /// The painterPath refered to for selection QPainterPath partOutShape; ///declare as static in main app and use everywhere needed QSettings settings; // a croo pixmap that will allow easy item mouvement QGraphicsPixmapItem *selecPix; /// The angle at which we place a lead on a circle int leadAngle; /// the minimal distance at which we can put the leads double leadDist; /// used to approximate lead surface. double leadRadius; /// used to track erros like small radius that can't be cut with plasma /// @todo use error code to track them bool errorsFound; /// used to track erros like open loop "useful only in plasma mode" /// @todo use error code to track them bool openLoopError; ///@see COPY constuctor Part* copy(); ///If the part is for preview or to be inserted in sheetmetal bool preview; ///number of closedloops int nbrClosedPath; ///number of circles int nbrCircles; ///the outline position in partLoops list int outlinePos; /// toolpath lentgh double tpLength; // @note:As we are using pointers to loops any change in a previewed part will affect all the others. //This is a desirbvale behavior! /// The loops making the part QVector <Loop* > partLoops; /// The loops making the part after GA optimization QVector <Loop* > partLoopsOpt; ///A part is a combinaison of loops (themselves composed of a number of paths ) each path has a start / end point the points definig the part QPFWPVector ptsVector; ///the painterPath used to draw the part QPPVector pathsList; ///the circles points coordinates QPFWPVector cirPtsList; ///the painterPath used to draw part circles QPPVector cirPathsList; /// the part filename, used to track it when on the sheet metal QString partName; //@todo:Maybe to be removed /// the coord of the outline point QPointFWithParent outlinePoint; /// The path of the outline QPainterPath outLinePath; /// stiores the lead/in out points QPFWPVector gLeadPoints; /// stiores the loops for gcode generation QList<QPFWPVector> gLoops; /** * Start the part geometry parsing */ void start(); /** * Generate the part lead in/out */ void generateLeads(); /** * Search for the part outiline loop */ void findOutline(); /** * Search for circles in the file */ void filterCircles(); /** * Starts the process of closed loop search * @param ptsVector the points list to parse */ void generateLoops(QPFWPVector ptsVector); /** * removes a point from the list * @param pointsList The old points list * @param pointsListNew The new points list * @param pos the position to take from * @param oldPos */ void shrink(QPFWPVector &pointsList,QPFWPVector &pointsListNew,int &pos,int &oldPos); ///find a lonley point if any or repreted one /** * Find an open loop ( a point in one entity * @param pointsList the part points list * @return A lonley point posistion within pointsList */ int newPos(QPFWPVector &pointsList); /// we use the QGraphicsItem default implementation for those events void drawArc(QPointFWithParent point,QPainterPath &pathToModify); /** * Return a translated coordinate * @param oldPoint original coor * @param offset delta * @return the new translated posiiton */ QPointFWithParent translateEntity(QPointFWithParent oldPoint, QPointF offset); /** * starts the optimlization process by calling GA TSP */ void optimizeRoute(); /** * Move a part (translation) * @param dx Delta X * @param dy Delta Y */ void moveMeBy(qreal dx, qreal dy); /** * Set the part name to its filename * @param f part filename */ void setPartName(QString f){partName=f;} /** this matrix holds the transformations applied to the part, transformations can be one of the following: / translation , rotation ,shearing. wWe'll discard shearing and keep both translation and rotation / therefor x' = m11*x + m21*y + dx / y' = m22*y + m12*x + dy / where The dx and dy elements specify horizontal and vertical translation. / The m11 and m22 elements specify horizontal and vertical scaling. /And finally, the m21 and m12 elements specify horizontal and vertical shearing. */ QTransform transform; enum { Type = UserType + 1 }; int type() const { // Enable the use of qgraphicsitem_cast with this item. return Type; } //public slots: //void setMoveVal(int); //{qDebug()<<"test";movePartVal=val;} //signals: //void progressionStep(); //void descStep( QString desc); private: QBasicTimer timer; void paint(QPainter *painter, const QStyleOptionGraphicsItem*, QWidget *); protected: /// called by QGraphicsItem to notify custom items that some part of the item's state changes. QVariant itemChange(GraphicsItemChange change, const QVariant &value); void mousePressEvent(QGraphicsSceneMouseEvent *event); void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); void mouseMoveEvent(QGraphicsSceneMouseEvent *event); void hoverEnterEvent ( QGraphicsSceneHoverEvent * event ); void hoverLeaveEvent ( QGraphicsSceneHoverEvent * event ); void keyPressEvent ( QKeyEvent * keyEvent ); }; class LoopThread : public QThread { Q_OBJECT public: LoopThread(Part *piece); Part *currentPiece; //QList <QPFWPList> filterLoop; protected: void run(); }; #endif // PART_H
hananiahhsu/OpenCAD
XUXUCAM/cam_newprt.h
#ifndef CAM_NEWPRT_H #define CAM_NEWPRT_H /* ************************************ *** @<NAME> *** @2017.06.6 *** @NanJing,China *** @<EMAIL> *** HardWriting Ui ************************************ */ #include <QDialog> #include <QCloseEvent> #include <QPushButton> #include <QLineEdit> #include <QComboBox> #include <QLabel> #include <QGroupBox> #include <QRadioButton> #include <QPainter> #include <QCheckBox> #include <QDir> #include "FileIO/cam_fileio.h" #include "StringOperation/stringoperation.h" namespace Ui { class CAM_NewPrt; } class CAM_NewPrt : public QDialog { Q_OBJECT public: explicit CAM_NewPrt(QWidget *parent = 0); ~CAM_NewPrt(); private: Ui::CAM_NewPrt *ui; void Init(); void closeEvent(QCloseEvent *event); //bool event(QEvent *event); signals: void CAM_NewPrt_Destroy(); void CAM_NewPrt_Close_Signal(QString name_mat,QString thick_mat); void CAM_NewPrt_New_Signal(QString name_mat,QString len,QString width,QString mat,QString thick_mat,QString qty,QString no,bool is_rot); void CAM_AddPrt_Add_Signal(QString name_mat,QString thick_mat); private slots: void on_combo_mat_changed(); void on_combo_mat_thk_changed(); void on_newprt_new_clicked(); public: //File operations CAM_FileIO file_io; QList<QList<QString>> p_all_mat_list; public: //All widgets of this window QPushButton *new_prt_new_prt; QPushButton *new_prt_add_prt; QLabel *label_name; QLabel *label_length; QLabel *label_width; QLabel *label_mat; QLabel *label_thk; QLabel *label_quantity; QLabel *label_prt_no; QLabel *label_rot; QComboBox *combo_names; QComboBox *combo_material; QComboBox *combo_mat_thicks; QLineEdit *lineE_name; QLineEdit *lineE_len; QLineEdit *lineE_width; QLineEdit *lineE_Qty; QLineEdit *lineE_prt_no; QRadioButton *radio_rot; QCheckBox *chk_rot; QPainter *line_painter; public: void paintEvent(QPaintEvent* event); }; #endif // CAM_NEWPRT_H
hananiahhsu/OpenCAD
XUXUCAM/FileIO/cam_fileio.h
<reponame>hananiahhsu/OpenCAD #ifndef CAM_FILEIO_H #define CAM_FILEIO_H /* ************************************ *** @<NAME> *** @2017.05.10 *** @NanJing,China *** @<EMAIL> ************************************ */ #include <QFile> #include <QTextStream> #include <QMessageBox> class CAM_FileIO { public: CAM_FileIO(void); virtual ~CAM_FileIO(); public: //read text by line void CAM_ReadText(QFile& file,QList<QString>& str_list); //read text by QStreamText void CAM_ReadText_ByStream(QFile& file,QString& lines); //write text void CAM_WriteText(QFile& file,QString& strs); }; #endif // CAM_FILEIO_H
hananiahhsu/OpenCAD
XUXUCAM/CamCores/CamEng/cam_vector.h
<filename>XUXUCAM/CamCores/CamEng/cam_vector.h #ifndef CAM_VECTOR_H #define CAM_VECTOR_H /* ************************************ *** @<NAME> *** @2017.05.10 *** @NanJing,China *** @<EMAIL> ************************************ */ #include <math.h> #include <algorithm> class Cam_Vector { public: //default Cam_Vector() {} //with multi-params Cam_Vector(double v_x,double v_y,double v_z=0.0); //single param firbidden implicit calling explicit Cam_Vector(double angle); explicit Cam_Vector(bool valid); //de-construc(no-vir) ~Cam_Vector()=default; //Any primitive type to bool explicit operator bool()const; //coords of setting void CamSetUnitVector(double angle);//by dir void CamSet(double x,double y,double z=0.0); void CamSetPolar(double radius,double angle); Cam_Vector CamGetPolar(double radius,double angle); //operators of basic maths computation double CamTwoD3Dist(const Cam_Vector& v)const; double CamGetCorrectAngle();//atan2 double CamGetAngleToVector(const Cam_Vector& v)const; double CamGetAngleBetweenVectors(const Cam_Vector& u,const Cam_Vector& v)const; double CamGetVectorLength(const Cam_Vector& v); double CamGetMagnitudeSquared(); double CamGetMagnitudeSquaredToVector(const Cam_Vector& v); double CamLerp(const Cam_Vector& v,double t); //Position check bool CamIsInWindow(const Cam_Vector& l_pnt,const Cam_Vector& r_pnt); bool CamIsInWindowOrdered(const Cam_Vector& u_pnt,const Cam_Vector& d_pnt); //type trans Cam_Vector CamToInteger(); //basic operation public: double x=0.0; double y=0.0; double z=0.0; bool is_valid=false; }; #endif // CAM_VECTOR_H
hananiahhsu/OpenCAD
XUXUCAM/CamCores/CamSci/cam_sci.h
#ifndef CAM_SCI_H #define CAM_SCI_H /* ************************************ *** @<NAME> *** @2017.05.10 *** @NanJing,China *** @<EMAIL> ************************************ */ #endif // CAM_SCI_H
hananiahhsu/OpenCAD
XUXUCAM/CamDxf/camdxf.h
#ifndef CAMDXF_H #define CAMDXF_H /* ************************************ *** @<NAME> *** @2017.05.10 *** @NanJing,China *** @<EMAIL> ************************************ */ /* Number of decimal digits of precision in a double */ #include <float.h> #include "dl_dxf.h" #include "dl_creationadapter.h" #include <QtGui> #include "CamDxf/qpointfwithparent.h" #include <QPoint> #include <QGraphicsPathItem> class QPointFWithParent; class CamDxf : public DL_CreationAdapter { public: CamDxf(); virtual void addLayer(const DL_LayerData& data); virtual void addPoint(const DL_PointData& data); virtual void addLine(const DL_LineData& data); virtual void addArc(const DL_ArcData& data); virtual void addCircle(const DL_CircleData& data); virtual void addPolyline(const DL_PolylineData& data); virtual void addVertex(const DL_VertexData& data); virtual void add3dFace(const DL_3dFaceData& data); /** * Called for every block. Note: all entities added after this * command go into this block until endBlock() is called. */ virtual void addBlock(const DL_BlockData& data); /** Called to end the current block */ virtual void endBlock() ; virtual void addInsert(const DL_InsertData& data); virtual void addMText(const DL_MTextData& data); virtual void addText(const DL_TextData& data); ///------------------ QPainterPath drawLine( const QPointF & startPoint, const QPointF & endPoint); QPainterPath drawArc( const QPointFWithParent & startPoint, const QRectF & rectangle, qreal startAngle, qreal sweepAngle); QPainterPath drawCircle( const QPointFWithParent &centerPoint); ///------------------ /** Lines along with arcs and polylines have their end/start points stored within pointsPathList Circles are classified on their own in a Qlist of paths (definig their ceners, radis). Arcs are dealt with in another way as we need */ QPPVector partPathsList; QPPVector circlePathsList; QPFWPVector pointsCircleVector; QPFWPVector pointsPathVector; QList <QGraphicsPathItem *> polylinesList; QList <QPointF *> vertexesList; /// the resulting part path QPainterPath partPath; /// the digit to round to float values (to still be in the tolerance) int precision; void printAttributes(); bool polylineNew; bool inBlock; bool corrupted; /// indicates weither ot not it's the first encountred polyline bool polylineFirst; QPainterPath polylineCurrent; double getPoint(double pos,double teta1,double radius,bool cos); double roundMe(double val); }; #endif // CAMDXF_H
hananiahhsu/OpenCAD
XUXUCAM/CamCores/CamEng/cam_layer.h
<reponame>hananiahhsu/OpenCAD<gh_stars>10-100 #ifndef CAM_LAYER_H #define CAM_LAYER_H /* ************************************ *** @<NAME> *** @2017.05.10 *** @NanJing,China *** @<EMAIL> ************************************ */ class Cam_Layer { public: Cam_Layer() {} virtual~Cam_Layer(); public: }; #endif // CAM_LAYER_H
hananiahhsu/OpenCAD
XUXUCAM/dxfSrc/dl_exception.h
<reponame>hananiahhsu/OpenCAD /**************************************************************************** ** $Id: dl_exception.h 3591 2006-10-18 21:23:25Z andrew $ ** ** Copyright (C) 2001-2003 RibbonSoft. All rights reserved. ** Copyright (C) 2001 <NAME>. ** ** This file is part of the dxflib project. ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** ** Licensees holding valid dxflib Professional Edition licenses may use ** this file in accordance with the dxflib Commercial License ** Agreement provided with the Software. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.ribbonsoft.com for further details. ** ** Contact <EMAIL> if any conditions of this licensing are ** not clear to you. ** **********************************************************************/ #ifndef DL_EXCEPTION_H #define DL_EXCEPTION_H #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 /** * Used for exception handling. */ class DL_Exception {} ; /** * Used for exception handling. */ class DL_NullStrExc : public DL_Exception {} ; /** * Used for exception handling. */ class DL_GroupCodeExc : public DL_Exception { DL_GroupCodeExc(int gc=0) : groupCode(gc) {} int groupCode; }; #endif
hananiahhsu/OpenCAD
XUXUCAM/CamDxf/qpointfwithparent.h
<reponame>hananiahhsu/OpenCAD #ifndef QPOINTFWITHPARENT_H #define QPOINTFWITHPARENT_H /* ************************************ *** @<NAME> *** @2017.05.10 *** @NanJing,China *** @<EMAIL> ************************************ */ #include <QtGui> class QPointFWithParent; typedef QList <QPointFWithParent > QPFWPList; typedef QVector <QPointFWithParent > QPFWPVector; typedef QList <QPainterPath > QPPList; typedef QVector <QPainterPath > QPPVector; /// holds the point parent loop and its infos class QPointFWithParent : public QPointF { public: /// Refers to the entity's type the point is attached to enum type { Line = 0x0, Arc = 0x1, Circle = 0x2, Polyline = 0x3, LeadCertain=0x4, LeadUncertain=0x5 }; Q_DECLARE_FLAGS(Types, type) QPointFWithParent::Types parentType; /// the loop the point is linked to int parentLoop; /// the circle center X coord double centerX; ///the circle center Y coord double centerY; ///the circle center QPointF center; /// @todo remove leadTouch at it's now loop dependant QPointF leadTouch; ///the circle radius double parentRadius; ///the arc angle double angle1; /// the arc angle double angle2; /// The arc is clockwise bool cWise; /** * Set the lead-out point * @param myLeadTouch Lead-out coord */ void setLeadTouch(QPointF myLeadTouch){ leadTouch=myLeadTouch;} /// TODO: rename to setParentLoop for homongenity /** * Set the loop number on the toolpath * @param nbr loop number */ void setLoopNbr(int nbr){ parentLoop=nbr; } /** * Set the point parent type to type * @param type the point parent type */ void setParentType(QPointFWithParent::Types type ){ parentType=type; } /** * Set the point circle center coordinates * @param newCenter */ void setCenter(QPointF newCenter){ center=newCenter; centerX=newCenter.x();centerY=newCenter.y();} /// create by default a point stores its parents as a Line QPointFWithParent (double x=0, double y=0, double cx=0,double cy=0,double radius=0,QPointFWithParent::Types type=0x0,bool cw=true, double teta1=0, double teta2=0); virtual ~QPointFWithParent(); QPointFWithParent operator+= (QPointF point ); QPointFWithParent operator= (const QPointF point ); // create an overloaded ont to WithParent //QPointFWithParent operator+ (const QPointFWithParent &point1 ); }; Q_DECLARE_OPERATORS_FOR_FLAGS(QPointFWithParent::Types) #endif // QPOINTFWITHPARENT_H
hananiahhsu/OpenCAD
XUXUCAM/CamCores/CamEng/cam_block.h
<reponame>hananiahhsu/OpenCAD<gh_stars>10-100 #ifndef CAM_BLOCK_H #define CAM_BLOCK_H /* ************************************ *** @<NAME> *** @2017.05.10 *** @NanJing,China *** @<EMAIL> ************************************ */ class Cam_Block { public: Cam_Block() {} virtual~Cam_Block(); }; #endif // CAM_BLOCK_H
hananiahhsu/OpenCAD
XUXUCAM/cam_importmat.h
#ifndef CAM_IMPORTMAT_H #define CAM_IMPORTMAT_H /* ************************************ *** @<NAME> *** @2017.05.10 *** @LianYunGang,China *** @<EMAIL> ************************************ */ #include <QDialog> #include <QAbstractButton> #include <QFileDialog> namespace Ui { class CAM_ImportMat; } class CAM_ImportMat : public /*QDialog*/QFileDialog { Q_OBJECT public: explicit CAM_ImportMat(QWidget *parent = 0); ~CAM_ImportMat(); public: QString dxf_name; QStringList dxf_list; private: Ui::CAM_ImportMat *ui; private: void closeEvent(QCloseEvent *event); signals: void CAM_ImportMat_Close_Signal(QStringList dxf_list); private slots: void on_buttonBox_clicked(QAbstractButton *button); void on_destroyed(); void on_FilesSelected(); }; #endif // CAM_IMPORTMAT_H
hananiahhsu/OpenCAD
XUXUCAM/cam_importprt.h
<filename>XUXUCAM/cam_importprt.h #ifndef CAM_IMPORTPRT_H #define CAM_IMPORTPRT_H /* ************************************ *** @<NAME> *** @2017.06.06 *** @NanJing,China *** @<EMAIL> ************************************ */ #include <QDialog> #include <QAbstractButton> #include <QFileDialog> #include <QCloseEvent> //namespace Ui { //class CAM_ImportPrt; //} class CAM_ImportPrt : public /*QDialog*/QFileDialog { Q_OBJECT public: explicit CAM_ImportPrt(QWidget *parent = 0); ~CAM_ImportPrt(); public: QStringList prt_list; private: void closeEvent(QCloseEvent *event); signals: void CAM_ImportPrt_Destroyed(); void CAM_ImportPrt_Close_Signal(QStringList prt_list); private slots: void on_FilesSelected();//for prt selected }; #endif // CAM_IMPORTPRT_H
hananiahhsu/OpenCAD
XUXUCAM/dxfSrc/dl_entities.h
/**************************************************************************** ** $Id: dl_entities.h 7812 2008-01-04 16:56:09Z andrew $ ** ** Copyright (C) 2001-2003 RibbonSoft. All rights reserved. ** ** This file is part of the dxflib project. ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** ** Licensees holding valid dxflib Professional Edition licenses may use ** this file in accordance with the dxflib Commercial License ** Agreement provided with the Software. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.ribbonsoft.com for further details. ** ** Contact <EMAIL> if any conditions of this licensing are ** not clear to you. ** **********************************************************************/ #ifndef DL_ENTITIES_H #define DL_ENTITIES_H #include <string> using std::string; /** * Layer Data. * * @author <NAME> */ struct DL_LayerData { /** * Constructor. * Parameters: see member variables. */ DL_LayerData(const string& lName, int lFlags) { name = lName; flags = lFlags; } /** Layer name. */ string name; /** Layer flags. (1 = frozen, 2 = frozen by default, 4 = locked) */ int flags; }; /** * Block Data. * * @author <NAME> */ struct DL_BlockData { /** * Constructor. * Parameters: see member variables. */ DL_BlockData(const string& bName, int bFlags, double bbpx, double bbpy, double bbpz) { name = bName; flags = bFlags; bpx = bbpx; bpy = bbpy; bpz = bbpz; } /** Block name. */ string name; /** Block flags. (not used currently) */ int flags; /** X Coordinate of base point. */ double bpx; /** Y Coordinate of base point. */ double bpy; /** Z Coordinate of base point. */ double bpz; }; /** * Line Type Data. * * @author <NAME> */ struct DL_LineTypeData { /** * Constructor. * Parameters: see member variables. */ DL_LineTypeData(const string& lName, int lFlags) { name = lName; flags = lFlags; } /** Line type name. */ string name; /** Line type flags. */ int flags; }; /** * Point Data. * * @author <NAME> */ struct DL_PointData { /** * Constructor. * Parameters: see member variables. */ DL_PointData(double px=0.0, double py=0.0, double pz=0.0) { x = px; y = py; z = pz; } /*! X Coordinate of the point. */ double x; /*! Y Coordinate of the point. */ double y; /*! Z Coordinate of the point. */ double z; }; /** * Line Data. * * @author <NAME> */ struct DL_LineData { /** * Constructor. * Parameters: see member variables. */ DL_LineData(double lx1, double ly1, double lz1, double lx2, double ly2, double lz2) { x1 = lx1; y1 = ly1; z1 = lz1; x2 = lx2; y2 = ly2; z2 = lz2; } /*! X Start coordinate of the point. */ double x1; /*! Y Start coordinate of the point. */ double y1; /*! Z Start coordinate of the point. */ double z1; /*! X End coordinate of the point. */ double x2; /*! Y End coordinate of the point. */ double y2; /*! Z End coordinate of the point. */ double z2; }; /** * Arc Data. * * @author <NAME> */ struct DL_ArcData { /** * Constructor. * Parameters: see member variables. */ DL_ArcData(double acx, double acy, double acz, double aRadius, double aAngle1, double aAngle2) { cx = acx; cy = acy; cz = acz; radius = aRadius; angle1 = aAngle1; angle2 = aAngle2; } /*! X Coordinate of center point. */ double cx; /*! Y Coordinate of center point. */ double cy; /*! Z Coordinate of center point. */ double cz; /*! Radius of arc. */ double radius; /*! Startangle of arc in degrees. */ double angle1; /*! Endangle of arc in degrees. */ double angle2; }; /** * Circle Data. * * @author <NAME> */ struct DL_CircleData { /** * Constructor. * Parameters: see member variables. */ DL_CircleData(double acx, double acy, double acz, double aRadius) { cx = acx; cy = acy; cz = acz; radius = aRadius; } /*! X Coordinate of center point. */ double cx; /*! Y Coordinate of center point. */ double cy; /*! Z Coordinate of center point. */ double cz; /*! Radius of arc. */ double radius; }; /** * Polyline Data. * * @author <NAME> */ struct DL_PolylineData { /** * Constructor. * Parameters: see member variables. */ DL_PolylineData(int pNumber, int pMVerteces, int pNVerteces, int pFlags) { number = pNumber; m = pMVerteces; n = pNVerteces; flags = pFlags; } /*! Number of vertices in this polyline. */ unsigned int number; /*! Number of vertices in m direction if polyline is a polygon mesh. */ unsigned int m; /*! Number of vertices in n direction if polyline is a polygon mesh. */ unsigned int n; /*! Flags */ int flags; }; /** * Vertex Data. * * @author <NAME> */ struct DL_VertexData { /** * Constructor. * Parameters: see member variables. */ DL_VertexData(double px=0.0, double py=0.0, double pz=0.0, double pBulge=0.0) { x = px; y = py; z = pz; bulge = pBulge; } /*! X Coordinate of the vertex. */ double x; /*! Y Coordinate of the vertex. */ double y; /*! Z Coordinate of the vertex. */ double z; /*! Bulge of vertex. * (The tangent of 1/4 of the arc angle or 0 for lines) */ double bulge; }; /** * Trace Data / solid data / 3d face data. * * @author <NAME> */ struct DL_TraceData { DL_TraceData() { thickness = 0.0; for (int i=0; i<4; i++) { x[i] = 0.0; y[i] = 0.0; z[i] = 0.0; } } /** * Constructor. * Parameters: see member variables. */ DL_TraceData(double sx1, double sy1, double sz1, double sx2, double sy2, double sz2, double sx3, double sy3, double sz3, double sx4, double sy4, double sz4, double sthickness=0.0) { thickness = sthickness; x[0] = sx1; y[0] = sy1; z[0] = sz1; x[1] = sx2; y[1] = sy2; z[1] = sz2; x[2] = sx3; y[2] = sy3; z[2] = sz3; x[3] = sx4; y[3] = sy4; z[3] = sz4; } /*! Thickness */ double thickness; /*! Points */ double x[4]; double y[4]; double z[4]; }; /** * Solid Data. * * @author AHM */ typedef DL_TraceData DL_SolidData; /** * 3dface Data. */ typedef DL_TraceData DL_3dFaceData; /** * Spline Data. * * @author <NAME> */ struct DL_SplineData { /** * Constructor. * Parameters: see member variables. */ DL_SplineData(int pDegree, int pNKnots, int pNControl, int pFlags) { degree = pDegree; nKnots = pNKnots; nControl = pNControl; flags = pFlags; } /*! Degree of the spline curve. */ unsigned int degree; /*! Number of knots. */ unsigned int nKnots; /*! Number of control points. */ unsigned int nControl; /*! Flags */ int flags; }; /** * Spline knot data. * * @author <NAME> */ struct DL_KnotData { DL_KnotData() {} /** * Constructor. * Parameters: see member variables. */ DL_KnotData(double pk) { k = pk; } /*! Knot value. */ double k; }; /** * Spline control point data. * * @author <NAME> */ struct DL_ControlPointData { /** * Constructor. * Parameters: see member variables. */ DL_ControlPointData(double px, double py, double pz) { x = px; y = py; z = pz; } /*! X coordinate of the control point. */ double x; /*! Y coordinate of the control point. */ double y; /*! Z coordinate of the control point. */ double z; }; /** * Ellipse Data. * * @author <NAME> */ struct DL_EllipseData { /** * Constructor. * Parameters: see member variables. */ DL_EllipseData(double ecx, double ecy, double ecz, double emx, double emy, double emz, double eRatio, double eAngle1, double eAngle2) { cx = ecx; cy = ecy; cz = ecz; mx = emx; my = emy; mz = emz; ratio = eRatio; angle1 = eAngle1; angle2 = eAngle2; } /*! X Coordinate of center point. */ double cx; /*! Y Coordinate of center point. */ double cy; /*! Z Coordinate of center point. */ double cz; /*! X coordinate of the endpoint of the major axis. */ double mx; /*! Y coordinate of the endpoint of the major axis. */ double my; /*! Z coordinate of the endpoint of the major axis. */ double mz; /*! Ratio of minor axis to major axis.. */ double ratio; /*! Startangle of ellipse in rad. */ double angle1; /*! Endangle of ellipse in rad. */ double angle2; }; /** * Insert Data. * * @author <NAME> */ struct DL_InsertData { /** * Constructor. * Parameters: see member variables. */ DL_InsertData(const string& iName, double iipx, double iipy, double iipz, double isx, double isy, double isz, double iAngle, int iCols, int iRows, double iColSp, double iRowSp) { name = iName; ipx = iipx; ipy = iipy; ipz = iipz; sx = isx; sy = isy; sz = isz; angle = iAngle; cols = iCols; rows = iRows; colSp = iColSp; rowSp = iRowSp; } /*! Name of the referred block. */ string name; /*! X Coordinate of insertion point. */ double ipx; /*! Y Coordinate of insertion point. */ double ipy; /*! Z Coordinate of insertion point. */ double ipz; /*! X Scale factor. */ double sx; /*! Y Scale factor. */ double sy; /*! Z Scale factor. */ double sz; /*! Rotation angle in rad. */ double angle; /*! Number of colums if we insert an array of the block or 1. */ int cols; /*! Number of rows if we insert an array of the block or 1. */ int rows; /*! Values for the spacing between cols. */ double colSp; /*! Values for the spacing between rows. */ double rowSp; }; /** * MText Data. * * @author <NAME> */ struct DL_MTextData { /** * Constructor. * Parameters: see member variables. */ DL_MTextData(double tipx, double tipy, double tipz, double tHeight, double tWidth, int tAttachmentPoint, int tDrawingDirection, int tLineSpacingStyle, double tLineSpacingFactor, const string& tText, const string& tStyle, double tAngle) { ipx = tipx; ipy = tipy; ipz = tipz; height = tHeight; width = tWidth; attachmentPoint = tAttachmentPoint; drawingDirection = tDrawingDirection; lineSpacingStyle = tLineSpacingStyle; lineSpacingFactor = tLineSpacingFactor; text = tText; style = tStyle; angle = tAngle; } /*! X Coordinate of insertion point. */ double ipx; /*! Y Coordinate of insertion point. */ double ipy; /*! Z Coordinate of insertion point. */ double ipz; /*! Text height */ double height; /*! Width of the text box. */ double width; /** * Attachment point. * * 1 = Top left, 2 = Top center, 3 = Top right, * 4 = Middle left, 5 = Middle center, 6 = Middle right, * 7 = Bottom left, 8 = Bottom center, 9 = Bottom right */ int attachmentPoint; /** * Drawing direction. * * 1 = left to right, 3 = top to bottom, 5 = by style */ int drawingDirection; /** * Line spacing style. * * 1 = at least, 2 = exact */ int lineSpacingStyle; /** * Line spacing factor. 0.25 .. 4.0 */ double lineSpacingFactor; /*! Text string. */ string text; /*! Style string. */ string style; /*! Rotation angle. */ double angle; }; /** * Text Data. * * @author <NAME> */ struct DL_TextData { /** * Constructor. * Parameters: see member variables. */ DL_TextData(double tipx, double tipy, double tipz, double tapx, double tapy, double tapz, double tHeight, double tXScaleFactor, int tTextGenerationFlags, int tHJustification, int tVJustification, const string& tText, const string& tStyle, double tAngle) { ipx = tipx; ipy = tipy; ipz = tipz; apx = tapx; apy = tapy; apz = tapz; height = tHeight; xScaleFactor = tXScaleFactor; textGenerationFlags = tTextGenerationFlags; hJustification = tHJustification; vJustification = tVJustification; text = tText; style = tStyle; angle = tAngle; } /*! X Coordinate of insertion point. */ double ipx; /*! Y Coordinate of insertion point. */ double ipy; /*! Z Coordinate of insertion point. */ double ipz; /*! X Coordinate of alignment point. */ double apx; /*! Y Coordinate of alignment point. */ double apy; /*! Z Coordinate of alignment point. */ double apz; /*! Text height */ double height; /*! Relative X scale factor. */ double xScaleFactor; /*! 0 = default, 2 = Backwards, 4 = Upside down */ int textGenerationFlags; /** * Horizontal justification. * * 0 = Left (default), 1 = Center, 2 = Right, * 3 = Aligned, 4 = Middle, 5 = Fit * For 3, 4, 5 the vertical alignment has to be 0. */ int hJustification; /** * Vertical justification. * * 0 = Baseline (default), 1 = Bottom, 2 = Middle, 3= Top */ int vJustification; /*! Text string. */ string text; /*! Style (font). */ string style; /*! Rotation angle of dimension text away from default orientation. */ double angle; }; /** * Generic Dimension Data. * * @author <NAME> */ struct DL_DimensionData { /** * Constructor. * Parameters: see member variables. */ DL_DimensionData(double ddpx, double ddpy, double ddpz, double dmpx, double dmpy, double dmpz, int dType, int dAttachmentPoint, int dLineSpacingStyle, double dLineSpacingFactor, const string& dText, const string& dStyle, double dAngle) { dpx = ddpx; dpy = ddpy; dpz = ddpz; mpx = dmpx; mpy = dmpy; mpz = dmpz; type = dType; attachmentPoint = dAttachmentPoint; lineSpacingStyle = dLineSpacingStyle; lineSpacingFactor = dLineSpacingFactor; text = dText; style = dStyle; angle = dAngle; } /*! X Coordinate of definition point. */ double dpx; /*! Y Coordinate of definition point. */ double dpy; /*! Z Coordinate of definition point. */ double dpz; /*! X Coordinate of middle point of the text. */ double mpx; /*! Y Coordinate of middle point of the text. */ double mpy; /*! Z Coordinate of middle point of the text. */ double mpz; /** * Dimension type. * * 0 Rotated, horizontal, or vertical * 1 Aligned * 2 Angular * 3 Diametric * 4 Radius * 5 Angular 3-point * 6 Ordinate * 64 Ordinate type. This is a bit value (bit 7) * used only with integer value 6. If set, * ordinate is X-type; if not set, ordinate is * Y-type * 128 This is a bit value (bit 8) added to the * other group 70 values if the dimension text * has been positioned at a user-defined * location rather than at the default location */ int type; /** * Attachment point. * * 1 = Top left, 2 = Top center, 3 = Top right, * 4 = Middle left, 5 = Middle center, 6 = Middle right, * 7 = Bottom left, 8 = Bottom center, 9 = Bottom right, */ int attachmentPoint; /** * Line spacing style. * * 1 = at least, 2 = exact */ int lineSpacingStyle; /** * Line spacing factor. 0.25 .. 4.0 */ double lineSpacingFactor; /** * Text string. * * Text string entered explicitly by user or null * or "<>" for the actual measurement or " " (one blank space). * for supressing the text. */ string text; /*! Dimension style (font name). */ string style; /** * Rotation angle of dimension text away from * default orientation. */ double angle; }; /** * Aligned Dimension Data. * * @author <NAME> */ struct DL_DimAlignedData { /** * Constructor. * Parameters: see member variables. */ DL_DimAlignedData(double depx1, double depy1, double depz1, double depx2, double depy2, double depz2) { epx1 = depx1; epy1 = depy1; epz1 = depz1; epx2 = depx2; epy2 = depy2; epz2 = depz2; } /*! X Coordinate of Extension point 1. */ double epx1; /*! Y Coordinate of Extension point 1. */ double epy1; /*! Z Coordinate of Extension point 1. */ double epz1; /*! X Coordinate of Extension point 2. */ double epx2; /*! Y Coordinate of Extension point 2. */ double epy2; /*! Z Coordinate of Extension point 2. */ double epz2; }; /** * Linear Dimension Data. * * @author <NAME> */ struct DL_DimLinearData { /** * Constructor. * Parameters: see member variables. */ DL_DimLinearData(double ddpx1, double ddpy1, double ddpz1, double ddpx2, double ddpy2, double ddpz2, double dAngle, double dOblique) { dpx1 = ddpx1; dpy1 = ddpy1; dpz1 = ddpz1; dpx2 = ddpx2; dpy2 = ddpy2; dpz2 = ddpz2; angle = dAngle; oblique = dOblique; } /*! X Coordinate of Extension point 1. */ double dpx1; /*! Y Coordinate of Extension point 1. */ double dpy1; /*! Z Coordinate of Extension point 1. */ double dpz1; /*! X Coordinate of Extension point 2. */ double dpx2; /*! Y Coordinate of Extension point 2. */ double dpy2; /*! Z Coordinate of Extension point 2. */ double dpz2; /*! Rotation angle (angle of dimension line) in degrees. */ double angle; /*! Oblique angle in degrees. */ double oblique; }; /** * Radial Dimension Data. * * @author <NAME> */ struct DL_DimRadialData { /** * Constructor. * Parameters: see member variables. */ DL_DimRadialData(double ddpx, double ddpy, double ddpz, double dleader) { dpx = ddpx; dpy = ddpy; dpz = ddpz; leader = dleader; } /*! X Coordinate of definition point. */ double dpx; /*! Y Coordinate of definition point. */ double dpy; /*! Z Coordinate of definition point. */ double dpz; /*! Leader length */ double leader; }; /** * Diametric Dimension Data. * * @author <NAME> */ struct DL_DimDiametricData { /** * Constructor. * Parameters: see member variables. */ DL_DimDiametricData(double ddpx, double ddpy, double ddpz, double dleader) { dpx = ddpx; dpy = ddpy; dpz = ddpz; leader = dleader; } /*! X Coordinate of definition point. */ double dpx; /*! Y Coordinate of definition point. */ double dpy; /*! Z Coordinate of definition point. */ double dpz; /*! Leader length */ double leader; }; /** * Angular Dimension Data. * * @author <NAME> */ struct DL_DimAngularData { /** * Constructor. * Parameters: see member variables. */ DL_DimAngularData(double ddpx1, double ddpy1, double ddpz1, double ddpx2, double ddpy2, double ddpz2, double ddpx3, double ddpy3, double ddpz3, double ddpx4, double ddpy4, double ddpz4) { dpx1 = ddpx1; dpy1 = ddpy1; dpz1 = ddpz1; dpx2 = ddpx2; dpy2 = ddpy2; dpz2 = ddpz2; dpx3 = ddpx3; dpy3 = ddpy3; dpz3 = ddpz3; dpx4 = ddpx4; dpy4 = ddpy4; dpz4 = ddpz4; } /*! X Coordinate of definition point 1. */ double dpx1; /*! Y Coordinate of definition point 1. */ double dpy1; /*! Z Coordinate of definition point 1. */ double dpz1; /*! X Coordinate of definition point 2. */ double dpx2; /*! Y Coordinate of definition point 2. */ double dpy2; /*! Z Coordinate of definition point 2. */ double dpz2; /*! X Coordinate of definition point 3. */ double dpx3; /*! Y Coordinate of definition point 3. */ double dpy3; /*! Z Coordinate of definition point 3. */ double dpz3; /*! X Coordinate of definition point 4. */ double dpx4; /*! Y Coordinate of definition point 4. */ double dpy4; /*! Z Coordinate of definition point 4. */ double dpz4; }; /** * Angular Dimension Data (3 points version). * * @author <NAME> */ struct DL_DimAngular3PData { /** * Constructor. * Parameters: see member variables. */ DL_DimAngular3PData(double ddpx1, double ddpy1, double ddpz1, double ddpx2, double ddpy2, double ddpz2, double ddpx3, double ddpy3, double ddpz3) { dpx1 = ddpx1; dpy1 = ddpy1; dpz1 = ddpz1; dpx2 = ddpx2; dpy2 = ddpy2; dpz2 = ddpz2; dpx3 = ddpx3; dpy3 = ddpy3; dpz3 = ddpz3; } /*! X Coordinate of definition point 1. */ double dpx1; /*! Y Coordinate of definition point 1. */ double dpy1; /*! Z Coordinate of definition point 1. */ double dpz1; /*! X Coordinate of definition point 2. */ double dpx2; /*! Y Coordinate of definition point 2. */ double dpy2; /*! Z Coordinate of definition point 2. */ double dpz2; /*! X Coordinate of definition point 3. */ double dpx3; /*! Y Coordinate of definition point 3. */ double dpy3; /*! Z Coordinate of definition point 3. */ double dpz3; }; /** * Ordinate Dimension Data. * * @author <NAME> */ struct DL_DimOrdinateData { /** * Constructor. * Parameters: see member variables. */ DL_DimOrdinateData(double ddpx1, double ddpy1, double ddpz1, double ddpx2, double ddpy2, double ddpz2, bool dxtype) { dpx1 = ddpx1; dpy1 = ddpy1; dpz1 = ddpz1; dpx2 = ddpx2; dpy2 = ddpy2; dpz2 = ddpz2; xtype = dxtype; } /*! X Coordinate of definition point 1. */ double dpx1; /*! Y Coordinate of definition point 1. */ double dpy1; /*! Z Coordinate of definition point 1. */ double dpz1; /*! X Coordinate of definition point 2. */ double dpx2; /*! Y Coordinate of definition point 2. */ double dpy2; /*! Z Coordinate of definition point 2. */ double dpz2; /*! True if the dimension indicates the X-value, false for Y-value */ bool xtype; }; /** * Leader (arrow). * * @author <NAME> */ struct DL_LeaderData { /** * Constructor. * Parameters: see member variables. */ DL_LeaderData(int lArrowHeadFlag, int lLeaderPathType, int lLeaderCreationFlag, int lHooklineDirectionFlag, int lHooklineFlag, double lTextAnnotationHeight, double lTextAnnotationWidth, int lNumber) { arrowHeadFlag = lArrowHeadFlag; leaderPathType = lLeaderPathType; leaderCreationFlag = lLeaderCreationFlag; hooklineDirectionFlag = lHooklineDirectionFlag; hooklineFlag = lHooklineFlag; textAnnotationHeight = lTextAnnotationHeight; textAnnotationWidth = lTextAnnotationWidth; number = lNumber; } /*! Arrow head flag (71). */ int arrowHeadFlag; /*! Leader path type (72). */ int leaderPathType; /*! Leader creation flag (73). */ int leaderCreationFlag; /*! Hookline direction flag (74). */ int hooklineDirectionFlag; /*! Hookline flag (75) */ int hooklineFlag; /*! Text annotation height (40). */ double textAnnotationHeight; /*! Text annotation width (41) */ double textAnnotationWidth; /*! Number of vertices in leader (76). */ int number; }; /** * Leader Vertex Data. * * @author <NAME> */ struct DL_LeaderVertexData { /** * Constructor. * Parameters: see member variables. */ DL_LeaderVertexData(double px=0.0, double py=0.0, double pz=0.0) { x = px; y = py; z = pz; } /*! X Coordinate of the vertex. */ double x; /*! Y Coordinate of the vertex. */ double y; /*! Z Coordinate of the vertex. */ double z; }; /** * Hatch data. */ struct DL_HatchData { /** * Default constructor. */ DL_HatchData() {} /** * Constructor. * Parameters: see member variables. */ DL_HatchData(int hNumLoops, bool hSolid, double hScale, double hAngle, const string& hPattern) { numLoops = hNumLoops; solid = hSolid; scale = hScale; angle = hAngle; pattern = hPattern; } /*! Number of boundary paths (loops). */ int numLoops; /*! Solid fill flag (true=solid, false=pattern). */ bool solid; /*! Pattern scale or spacing */ double scale; /*! Pattern angle */ double angle; /*! Pattern name. */ string pattern; }; /** * Hatch boundary path (loop) data. */ struct DL_HatchLoopData { /** * Default constructor. */ DL_HatchLoopData() {} /** * Constructor. * Parameters: see member variables. */ DL_HatchLoopData(int hNumEdges) { numEdges = hNumEdges; } /*! Number of edges in this loop. */ int numEdges; }; /** * Hatch edge data. */ struct DL_HatchEdgeData { /** * Default constructor. */ DL_HatchEdgeData() { defined = false; } /** * Constructor for a line edge. * Parameters: see member variables. */ DL_HatchEdgeData(double lx1, double ly1, double lx2, double ly2) { x1 = lx1; y1 = ly1; x2 = lx2; y2 = ly2; type = 1; defined = true; } /** * Constructor for an arc edge. * Parameters: see member variables. */ DL_HatchEdgeData(double acx, double acy, double aRadius, double aAngle1, double aAngle2, bool aCcw) { cx = acx; cy = acy; radius = aRadius; angle1 = aAngle1; angle2 = aAngle2; ccw = aCcw; type = 2; defined = true; } /** * Edge type. 1=line, 2=arc. */ int type; /** * Set to true if this edge is fully defined. */ bool defined; /*! Start point (X). */ double x1; /*! Start point (Y). */ double y1; /*! End point (X). */ double x2; /*! End point (Y). */ double y2; /*! Center point of arc (X). */ double cx; /*! Center point of arc (Y). */ double cy; /*! Arc radius. */ double radius; /*! Start angle. */ double angle1; /*! End angle. */ double angle2; /*! Counterclockwise flag. */ bool ccw; }; /** * Image Data. * * @author <NAME> */ struct DL_ImageData { /** * Constructor. * Parameters: see member variables. */ DL_ImageData(const string& iref, double iipx, double iipy, double iipz, double iux, double iuy, double iuz, double ivx, double ivy, double ivz, int iwidth, int iheight, int ibrightness, int icontrast, int ifade) { ref = iref; ipx = iipx; ipy = iipy; ipz = iipz; ux = iux; uy = iuy; uz = iuz; vx = ivx; vy = ivy; vz = ivz; width = iwidth; height = iheight; brightness = ibrightness; contrast = icontrast; fade = ifade; } /*! Reference to the image file (unique, used to refer to the image def object). */ string ref; /*! X Coordinate of insertion point. */ double ipx; /*! Y Coordinate of insertion point. */ double ipy; /*! Z Coordinate of insertion point. */ double ipz; /*! X Coordinate of u vector along bottom of image. */ double ux; /*! Y Coordinate of u vector along bottom of image. */ double uy; /*! Z Coordinate of u vector along bottom of image. */ double uz; /*! X Coordinate of v vector along left side of image. */ double vx; /*! Y Coordinate of v vector along left side of image. */ double vy; /*! Z Coordinate of v vector along left side of image. */ double vz; /*! Width of image in pixel. */ int width; /*! Height of image in pixel. */ int height; /*! Brightness (0..100, default = 50). */ int brightness; /*! Contrast (0..100, default = 50). */ int contrast; /*! Fade (0..100, default = 0). */ int fade; }; /** * Image Definition Data. * * @author <NAME> */ struct DL_ImageDefData { /** * Constructor. * Parameters: see member variables. */ DL_ImageDefData(const string& iref, const string& ifile) { ref = iref; file = ifile; } /*! Reference to the image file (unique, used to refer to the image def object). */ string ref; /*! Image file */ string file; }; #endif // EOF
hananiahhsu/OpenCAD
XUXUCAM/StringOperation/stringoperation.h
#ifndef STRINGOPERATION_H #define STRINGOPERATION_H /* ************************************ *** @<NAME> *** @2017.05.10 *** @NanJing,China *** @<EMAIL> ************************************ */ #include<QString> #include<QList> class StringOperations { public: StringOperations(void); virtual ~StringOperations(); public: //Divide a long str by comma void DivideStrIntoList(QString in_str,QString div_str,QList<QString>& str_list); //Int to char* QString IntToQstring(int in_i); //Int to QByteArray QByteArray IntToQByteArray(int in_i); }; #endif // STRINGOPERATION_H