repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
dolovnyak/ray-marching-render
libui/src/ui_jtoc/ui_jtoc_utils.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ui_jtoc_utils.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: edraugr- <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/06/19 20:05:37 by sbednar #+# #+# */ /* Updated: 2019/07/24 19:40:51 by sbecker ### ########.fr */ /* */ /* ************************************************************************** */ #include "libui.h" int ui_jtoc_sdl_log_error(const char *p, const int id) { SDL_Log("%s ----> ERROR <---- %s", KRED, KNRM); SDL_Log("INCORRECT: %s%s%s%s%s", p, id < 0 ? "" : " IN ID = ", KGRN, id < 0 ? "" : ft_itoa(id), KNRM); return (FUNCTION_FAILURE); } int ui_jtoc_isnum(enum e_type type) { return (type == fractional || type == integer); }
dolovnyak/ray-marching-render
libui/src/ui_el/ui_el_set_new_pos.c
<reponame>dolovnyak/ray-marching-render /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ui_el_set_new_pos.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: edraugr- <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/06/03 21:13:32 by sbecker #+# #+# */ /* Updated: 2019/07/15 04:06:13 by edraugr- ### ########.fr */ /* */ /* ************************************************************************** */ #include "libui.h" static void set_rect(t_ui_el *el, int x, int y) { el->rect.x = x; el->rect.y = y; } void ui_el_set_new_pos_for_children(void *a1, void *a2) { t_ui_el *el; el = (t_ui_el *)a1; (void)a2; el->rect.x = (int)roundf((float)el->parent->rect.x + (float)el->parent->rect.w * el->rrect.x); el->rect.y = (int)roundf((float)el->parent->rect.y + (float)el->parent->rect.h * el->rrect.y); el->crect.x = el->rect.x; el->crect.y = el->rect.y; } void ui_el_set_new_pos(t_ui_el *el, t_ui_el *canvas, int type, t_fvec2 v) { if ((type & ABS) && (type & PIXEL)) set_rect(el, (int)roundf(v.x), (int)roundf(v.y)); else if ((type & ABS)) set_rect(el, (int)roundf((float)canvas->rect.w * v.x), (int)roundf((float)canvas->rect.h * v.y)); else if ((type & PIXEL)) set_rect(el, (int)roundf((float)el->parent->rect.x + v.x), (int)roundf((float)el->parent->rect.y + v.y)); else set_rect(el, (int)roundf((float)el->parent->rect.x + (float)el->parent->rect.w * v.x), (int)roundf((float)el->parent->rect.y + (float)el->parent->rect.h * v.y)); el->rrect.x = (float)(el->rect.x - el->parent->rect.x) / (float)el->parent->rect.w; el->rrect.y = (float)(el->rect.y - el->parent->rect.y) / (float)el->parent->rect.h; el->crect.x = el->rect.x; el->crect.y = el->rect.y; bfs_iter(el->children, ui_el_set_new_pos_for_children, 0); }
dolovnyak/ray-marching-render
libui/src/ui_jtoc/ui_jtoc_el_pref_text.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ui_jtoc_el_pref_text.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: edraugr- <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/07/12 06:55:50 by sbecker #+# #+# */ /* Updated: 2019/07/15 08:23:38 by edraugr- ### ########.fr */ /* */ /* ************************************************************************** */ #include "libui.h" static int get_font_color(t_ui_main *m, t_ui_el *e, t_jnode *n) { t_jnode *t; int c; if (!((t = jtoc_node_get_by_path(n, "text_area.font")) && t->type == string)) ui_sdl_deinit(228); if (!(e->text_area->font = ui_main_get_font_by_id(m, jtoc_get_string(t)))) ui_sdl_deinit(228); if ((t = jtoc_node_get_by_path(n, "text_area.color")) && t->type == string) { c = ft_atoi_base(jtoc_get_string(t), 16); e->text_area->text_color = (SDL_Color){(Uint8)((c & 0xFF0000) >> 16), (Uint8)((c & 0x00FF00) >> 8), (Uint8)(c & 0x0000FF), 255}; } else ui_sdl_deinit(228); if (!((t = jtoc_node_get_by_path(n, "text_area.bg_color")) && t->type == string)) return (FUNCTION_SUCCESS); c = ft_atoi_base(jtoc_get_string(t), 16); e->text_area->bg_color = (SDL_Color){(Uint8)((c & 0xFF0000) >> 16), (Uint8)((c & 0x00FF00) >> 8), (Uint8)(c & 0x0000FF), 255}; return (FUNCTION_SUCCESS); } static int norm_kostil(t_ui_el *e, t_jnode *t, int h) { t = t->down; while (t) { if (t->type != string) return (FUNCTION_FAILURE); h = ft_strhash(jtoc_get_string(t)); e->text_area->params |= (h == ft_strhash("TEXT_IS_CENTERED") ? TEXT_IS_CENTERED : 0); e->text_area->params |= (h == ft_strhash("TEXT_IS_INPUTTING") ? TEXT_IS_INPUTTING : 0); e->text_area->params |= (h == ft_strhash("TEXT_IS_REGULAR") ? TEXT_IS_REGULAR : 0); t = t->right; } return (FUNCTION_SUCCESS); } static int get_text_params(t_ui_el *e, t_jnode *n) { int h; t_jnode *t; if ((t = jtoc_node_get_by_path(n, "text_area.string_len")) && ui_jtoc_isnum(t->type)) e->text_area->string_len = jtoc_get_int(t); if ((t = jtoc_node_get_by_path(n, "text_area.render_param")) && t->type == string) { h = ft_strhash(jtoc_get_string(t)); e->text_area->render_param |= (h == ft_strhash("TEXT_IS_SOLID") ? TEXT_IS_SOLID : 0); e->text_area->render_param |= (h == ft_strhash("TEXT_IS_SHADED") ? TEXT_IS_SHADED : 0); e->text_area->render_param |= (h == ft_strhash("TEXT_IS_BLENDED") ? TEXT_IS_BLENDED : 0); } else e->text_area->render_param |= TEXT_IS_BLENDED; if ((t = jtoc_node_get_by_path(n, "text_area.params"))) if (norm_kostil(e, t, h) == FUNCTION_FAILURE) return (FUNCTION_FAILURE); return (FUNCTION_SUCCESS); } int ui_jtoc_el_pref_text(t_ui_main *m, t_ui_el *e, t_jnode *n) { char *tmp_text; t_jnode *tmp; tmp_text = NULL; if ((jtoc_node_get_by_path(n, "text_area"))) { e->text_area = (t_ui_text *)ft_memalloc(sizeof(t_ui_text)); if (get_font_color(m, e, n)) ui_sdl_deinit(228); if (get_text_params(e, n)) ui_sdl_deinit(228); if ((tmp = jtoc_node_get_by_path(n, "text_area.text")) && tmp->type == string) tmp_text = ft_strdup(jtoc_get_string(tmp)); else ui_sdl_deinit(228); e->params |= EL_IS_TEXT; ui_el_update_text(e, tmp_text); free(tmp_text); } return (FUNCTION_SUCCESS); }
dolovnyak/ray-marching-render
include/rt_rotations.h
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* rt_rotations.h :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: sbecker <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/04/10 05:13:21 by sbecker #+# #+# */ /* Updated: 2019/07/03 20:16:18 by sbecker ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef RT_ROTATIONS_H # define RT_ROTATIONS_H # ifndef OPENCL___ # ifdef APPLE___ # include <OpenCL/opencl.h> # else # include <opencl.h> # endif # include "math.h" # endif void fill_rotation_matrix(float *m, cl_float3 v, float a); void mult(float *m, cl_float3 *v); #endif
dolovnyak/ray-marching-render
src/cl/pp/pp_blur_x.c
#include "rt_cl.h" __kernel void pp_blur_x( const __global int *input_data, __global int *output_data, int2 screen) { int tx = get_global_id(0); int ty = get_global_id(1); int index = ty * screen.x + tx; float3 color; int a = 3 * 2; float sum = 0; int coef; color = (float3) 0; for (int i = -a; i <= a; i++) { if (tx + i >= 0 && tx + i < screen.x) { coef = gauss_coeff_x(i, 2); color += int_color(input_data[screen.x * ty + (tx + i)]) * coef; sum += coef; } } output_data[index] = get_color(color / sum); }
dolovnyak/ray-marching-render
libui/src/ui_jtoc/ui_jtoc_efj_helper3.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ui_jtoc_efj_helper3.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: edraugr- <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/07/15 07:28:15 by edraugr- #+# #+# */ /* Updated: 2019/07/15 08:07:30 by edraugr- ### ########.fr */ /* */ /* ************************************************************************** */ #include "libui.h" int ui_el_from_json_textures(t_ui_main *m, t_ui_el *e, t_jnode *n) { t_jnode *t; if ((t = jtoc_node_get_by_path(n, "textures"))) { t = t->down; while (t) { if (t->type != object || ui_el_from_json_texture(m, e, t)) ui_sdl_deinit(228); t = t->right; } } if ((t = jtoc_node_get_by_path(n, "current_texture"))) { if (t->type != string) return (ui_jtoc_sdl_log_error("NODE EL (CURRENT TEXTURE)", e->id)); ui_el_set_current_texture_by_id(e, jtoc_get_string(t)); } return (ui_el_from_json_events(m, e, n)); } int ui_parse_canvas(t_ui_main *m, t_ui_el *e, t_jnode *n) { if (ui_el_from_json_textures(m, e, n)) ui_sdl_deinit(228); return (FUNCTION_SUCCESS); } int ui_el_from_json_size(t_ui_main *m, t_ui_el *e, t_jnode *n) { float x; float y; int p; t_jnode *t; if (!(t = jtoc_node_get_by_path(n, "size.x")) || !ui_jtoc_isnum(t->type)) return (ui_jtoc_sdl_log_error("NODE EL (SIZE.X)", e->id)); x = jtoc_get_float(t); if (!(t = jtoc_node_get_by_path(n, "size.y")) || !ui_jtoc_isnum(t->type)) return (ui_jtoc_sdl_log_error("NODE EL (SIZE.Y)", e->id)); y = jtoc_get_float(t); p = 0; if ((t = jtoc_node_get_by_path(n, "size.params"))) { t = t->down; while (t) { if (t->type != string) return (ui_jtoc_sdl_log_error("NODE EL (SIZE.PARAMS)", e->id)); p |= ui_jtoc_get_pos_size(jtoc_get_string(t)); t = t->right; } } ui_el_set_size(e, p, (t_fvec2){x, y}); return (ui_el_from_json_textures(m, e, n)); }
dolovnyak/ray-marching-render
libui/src/ui_cursor/ui_cursor_from_el_data.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ui_cursor_from_el_data.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: sbednar <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/06/22 19:49:00 by sbednar #+# #+# */ /* Updated: 2019/07/13 09:37:15 by sbecker ### ########.fr */ /* */ /* ************************************************************************** */ #include "libui.h" int ui_cursor_from_el_data(t_ui_main *m, void *a) { SDL_Cursor *current_cursor; SDL_Cursor *new_cursor; t_cursor *rc; t_ui_el *el; (void)m; el = (t_ui_el *)a; if ((current_cursor = SDL_GetCursor())) SDL_FreeCursor(current_cursor); if (!(rc = (t_cursor *)el->data) || !(new_cursor = SDL_CreateColorCursor(rc->s, rc->hot_x, rc->hot_y))) return (1); SDL_SetCursor(new_cursor); return (1); }
dolovnyak/ray-marching-render
libui/src/ui_event/ui_event_add_listener.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ui_event_add_listener.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: edraugr- <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/27 17:16:15 by sbednar #+# #+# */ /* Updated: 2019/07/13 05:47:23 by sbecker ### ########.fr */ /* */ /* ************************************************************************** */ #include "libui.h" int ui_event_add_listener(t_ui_event *e, t_pred_ptr_event f) { t_list *node; long ptr; ptr = (long)f; if ((node = ft_lstnew((void *)&ptr, sizeof(ptr))) == NULL) ui_sdl_deinit(228); if (e->events == NULL) e->events = node; else ft_lstadd_back(&(e->events), node); return (FUNCTION_SUCCESS); }
dolovnyak/ray-marching-render
libui/src/ui_el/ui_el_create_texture.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ui_el_create_texture.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: sbednar <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/05/17 15:54:15 by sbednar #+# #+# */ /* Updated: 2019/07/10 02:34:52 by sbecker ### ########.fr */ /* */ /* ************************************************************************** */ #include "libui.h" SDL_Texture *ui_el_create_empty_texture(t_ui_el *el) { SDL_Texture *tmp; if (!(tmp = SDL_CreateTexture(el->sdl_renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, el->rect.w, el->rect.h))) return (NULL); SDL_SetRenderTarget(el->sdl_renderer, tmp); SDL_SetRenderDrawBlendMode(el->sdl_renderer, SDL_BLENDMODE_NONE); SDL_SetRenderDrawColor(el->sdl_renderer, 255, 255, 255, 0); SDL_SetTextureBlendMode(tmp, SDL_BLENDMODE_BLEND); SDL_RenderFillRect(el->sdl_renderer, NULL); SDL_SetRenderDrawBlendMode(el->sdl_renderer, SDL_BLENDMODE_BLEND); SDL_SetRenderTarget(el->sdl_renderer, NULL); SDL_SetRenderDrawColor(el->sdl_renderer, 0, 0, 0, 255); return (tmp); } SDL_Texture *ui_el_create_texture(t_ui_el *el) { SDL_Texture *tmp; SDL_Rect rect; if (!el->sdl_surface || !el->sdl_renderer) ui_sdl_deinit(EXIT_FAILURE); SDL_GetClipRect(el->sdl_surface, &rect); if (rect.w > 16384 || rect.h > 4000) return (ui_el_create_empty_texture(el)); if (!(tmp = SDL_CreateTextureFromSurface(el->sdl_renderer, el->sdl_surface))) ui_sdl_deinit(EXIT_FAILURE); return (tmp); }
dolovnyak/ray-marching-render
libui/src/ui_el/ui_el_event_change_text.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ui_el_event_change_text.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: sbednar <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/07/24 22:47:00 by sbednar #+# #+# */ /* Updated: 2019/07/24 22:47:00 by sbednar ### ########.fr */ /* */ /* ************************************************************************** */ #include "libui.h" static void circumcision(t_ui_el *el) { char *str; if (el->text_area->text == NULL || *el->text_area->text == '\0') str = ft_strnew(1); else str = ft_strsub(el->text_area->text, 0, ft_strlen(el->text_area->text) - 1); ui_el_update_text(el, str); if (str != NULL) free(str); } static void join_with_letter(t_ui_el *el, unsigned int keycode, Uint8 is_upper) { char *str; char *str_letter; str_letter = ft_strnew(1); str_letter[0] = (char)(keycode + 93); if (is_upper) str_letter[0] = ft_toupper(str_letter[0]); if (el->text_area->text == NULL) str = ft_strdup(str_letter); else str = ft_strjoin(el->text_area->text, str_letter); ui_el_update_text(el, str); if (str != NULL) free(str); free(str_letter); } static void join_with_number(t_ui_el *el, unsigned int keycode) { char *str_letter; char *str; str_letter = ft_strnew(1); str_letter[0] = (char)(keycode + 19); if (el->text_area->text == NULL) str = ft_strdup(str_letter); else str = ft_strjoin(el->text_area->text, str_letter); ui_el_update_text(el, str); if (str != NULL) free(str); free(str_letter); } static void join_with_other(t_ui_el *el, unsigned int keycode) { char *str_letter; char *str; str_letter = ft_strnew(1); if (keycode == 56) str_letter[0] = '/'; else if (keycode == 55) str_letter[0] = '.'; else if (keycode == SDL_SCANCODE_SPACE) str_letter[0] = ' '; else if (keycode == 45) str_letter[0] = '-'; else if (keycode == SDL_SCANCODE_0) str_letter[0] = '0'; if (el->text_area->text == NULL) str = ft_strdup(str_letter); else str = ft_strjoin(el->text_area->text, str_letter); ui_el_update_text(el, str); if (str != NULL) free(str); free(str_letter); } int ui_el_event_change_text(t_ui_main *m, void *a) { t_ui_el *el; el = (t_ui_el *)a; if (!el || !(el->params & EL_IS_TEXT) || !(el->text_area->params & TEXT_IS_INPUTTING)) return (1); if (m->cur_keycode >= SDL_SCANCODE_A && m->cur_keycode <= SDL_SCANCODE_Z) join_with_letter(el, m->cur_keycode, m->is_upper); else if (m->cur_keycode >= SDL_SCANCODE_1 && m->cur_keycode <= SDL_SCANCODE_9) join_with_number(el, m->cur_keycode); else if (m->cur_keycode == SDL_SCANCODE_BACKSPACE) circumcision(el); else if (m->cur_keycode == 55 || m->cur_keycode == 56 || m->cur_keycode == SDL_SCANCODE_0 || m->cur_keycode == SDL_SCANCODE_SPACE || m->cur_keycode == 45) join_with_other(el, m->cur_keycode); return (1); }
dolovnyak/ray-marching-render
src/rt_post_processing.c
#include "rt.h" static void pp_process(t_rt_main *rt, int i) { cl_kernel *k; k = (cl_kernel *)vec_at(rt->pp, i); size_t arr[2] = {rt->screen_size.x, rt->screen_size.y}; clSetKernelArg(*k, 0, sizeof(cl_mem), i % 2 ? &rt->gpu_mem->cl_aux : &rt->gpu_mem->cl_image); clSetKernelArg(*k, 1, sizeof(cl_mem), i % 2 ? &rt->gpu_mem->cl_image : &rt->gpu_mem->cl_aux); clSetKernelArg(*k, 2, sizeof(cl_int2), &rt->screen_size); clEnqueueNDRangeKernel(*rt->cl->queue, *k, 2, NULL, arr, NULL, 0, NULL, NULL); } void post_processing(t_rt_main *rt) { size_t i; size_t cur; if (!rt->pp) return; i = -1; cur = 0; while (++i < rt->pp->size) { pp_process(rt, i); } }
dolovnyak/ray-marching-render
libui/src/ui_el/ui_el_setup_default.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ui_el_setup_default.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: sbecker <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/04/15 05:50:32 by sbednar #+# #+# */ /* Updated: 2019/07/15 15:25:14 by sbecker ### ########.fr */ /* */ /* ************************************************************************** */ #include "libui.h" static void ui_el_setup_change_text(t_ui_el *el) { int i; i = -1; while (++i < KEYS_COUNT) ui_event_add_listener(el->events->on_key_down[i], ui_el_event_change_text); } static void ui_el_setup_default_logs(t_ui_el *el) { ui_event_add_listener(el->events->on_pointer_enter, ui_log_el_pointer_enter); ui_event_add_listener(el->events->on_pointer_exit, ui_log_el_pointer_exit); ui_event_add_listener(el->events->on_pointer_stay, ui_log_el_pointer_stay); ui_event_add_listener(el->events->on_pointer_left_button_hold, ui_log_el_left_button_hold); ui_event_add_listener(el->events->on_pointer_left_button_pressed, ui_log_el_left_button_pressed); ui_event_add_listener(el->events->on_pointer_left_button_released, ui_log_el_left_button_released); ui_event_add_listener(el->events->on_pointer_right_button_hold, ui_log_el_right_button_hold); ui_event_add_listener(el->events->on_pointer_right_button_pressed, ui_log_el_right_button_pressed); ui_event_add_listener(el->events->on_pointer_right_button_released, ui_log_el_right_button_released); } void ui_el_setup_default(t_ui_el *el) { el->current_texture = ft_strhash("default"); ui_event_add_listener(el->events->on_render, ui_el_event_default_draw); ui_event_add_listener(el->events->on_pointer_enter, ui_el_event_default_pointer_enter); ui_event_add_listener(el->events->on_pointer_exit, ui_el_event_default_pointer_exit); ui_el_setup_change_text(el); if (DEBUG_STATUS == 1) ui_el_setup_default_logs(el); }
dolovnyak/ray-marching-render
libft/src/vec_resize.c
<reponame>dolovnyak/ray-marching-render<filename>libft/src/vec_resize.c<gh_stars>1-10 /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* vec_resize.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: sbecker <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/07/24 21:47:16 by sbecker #+# #+# */ /* Updated: 2019/07/24 21:47:17 by sbecker ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" int vec_resize(t_vec *v, size_t c) { int *new_storage; size_t s; size_t b; s = c * v->cell_size * sizeof(int); if (!(new_storage = malloc(s))) return (-1); v->capacity = c; b = v->capacity * v->cell_size * sizeof(int); ft_memcpy(new_storage, v->storage, b); ft_bzero(new_storage + b, s - b); free(v->storage); v->storage = new_storage; return (0); }
dolovnyak/ray-marching-render
include/rt_jtoc.h
#ifndef RT_JTOC_H # define RT_JTOC_H #include "rt.h" int rt_jtoc_textures_setup(t_rt_main *rt, const char *json); int rt_jtoc_scene_setup(t_rt_main *rt, const char *json); int rt_jtoc_ps_setup(t_scene *scene, t_physics_system *ps, const char *path); int rt_jtoc_get_float2(cl_float2 *vec, t_jnode *n); int rt_jtoc_get_float3(cl_float3 *vec, t_jnode *n); int rt_jtoc_get_float4(cl_float4 *vec, t_jnode *n); int rt_jtoc_ispos_float2(cl_float2 *vec); int rt_jtoc_ispos_float3(cl_float3 *vec); int rt_jtoc_ispos_float4(cl_float4 *vec); int rt_jtoc_sdl_log_error(const char *p, const int id); int rt_jtoc_get_camera(t_camera *camera, t_jnode *n); int rt_jtoc_get_transform(t_transform *transform, t_jnode *n); int rt_jtoc_get_objects_num_in_arr(unsigned int *objects_num, t_jnode *n); int rt_jtoc_get_lights(t_scene *scene, t_jnode *n); int rt_jtoc_get_objects(t_scene *scene, t_jnode *n, t_obj_texture *texture); int rt_jtoc_get_sphere(t_object *obj, t_jnode *n); int rt_jtoc_get_box(t_object *obj, t_jnode *n); int rt_jtoc_get_round_box(t_object *obj, t_jnode *n); int rt_jtoc_get_torus(t_object *obj, t_jnode *n); int rt_jtoc_get_plane(t_object *obj, t_jnode *n); int rt_jtoc_get_cone(t_object *obj, t_jnode *n); int rt_jtoc_get_cylinder(t_object *obj, t_jnode *n); int rt_jtoc_get_link(t_object *obj, t_jnode *n); int rt_jtoc_get_octahedron(t_object *obj, t_jnode *n); int rt_jtoc_get_mandelbulb(t_object *obj, t_jnode *n); int rt_jtoc_get_mandelbox(t_object *obj, t_jnode *n); int rt_jtoc_get_menger_sponge(t_object *obj, t_jnode *n); int rt_jtoc_is01_float3(cl_float3 *vec); # endif
dolovnyak/ray-marching-render
include/rt_physics_system.h
<filename>include/rt_physics_system.h<gh_stars>1-10 /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* rt_physics.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: sbecker <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/04/10 05:13:21 by sbecker #+# #+# */ /* Updated: 2019/07/03 20:16:18 by sbecker ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef RT_PHYSICS_H # define RT_PHYSICS_H # define CL_SILENCE_DEPRECATION # ifndef OPENCL___ # ifdef APPLE___ # include <OpenCL/opencl.h> # else # include <opencl.h> # endif # include <SDL.h> # include "libft.h" # include "transform.h" # include "rt_rotations.h" # include "rt_numerics.h" # include "rt_utilities.h" # endif typedef struct s_move_params { cl_float3 vel; cl_float3 raw_vel; cl_float acc; cl_float speed; cl_float speed_mult; } t_move_params; typedef struct s_rb { t_move_params move; t_move_params rot; t_transform *transform; } t_rb; # include "rt_system.h" typedef struct s_physics_system { t_system system; t_vec rbs; int change_indicator; } t_physics_system; int ps_func(void *psv); #endif
dolovnyak/ray-marching-render
libui/src/ui_main/ui_main_try_invoke_modal_windows.c
<reponame>dolovnyak/ray-marching-render /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ui_main_try_invoke_modal_windows.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: sbecker <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/07/14 15:11:08 by sbecker #+# #+# */ /* Updated: 2019/07/15 11:34:20 by sbecker ### ########.fr */ /* */ /* ************************************************************************** */ #include "libui.h" static void show_window(t_ui_main *m, t_ui_win *w) { SDL_LockMutex(m->mutex); SDL_ShowWindow(w->sdl_window); SDL_RaiseWindow(w->sdl_window); w->params &= ~WIN_IS_SHOWN; SDL_UnlockMutex(m->mutex); } void ui_main_try_invoke_modal_windows(t_ui_main *m) { t_list *node; t_ui_win *w; node = m->windows; while (node) { w = (t_ui_win *)node->content; if (w->params & WIN_IS_SHOWN) { show_window(m, w); return ; } if (w->params & WIN_IS_HIDDEN) { SDL_LockMutex(m->mutex); SDL_HideWindow(w->sdl_window); SDL_UnlockMutex(m->mutex); w->params &= ~WIN_IS_HIDDEN; return ; } node = node->next; } }
dolovnyak/ray-marching-render
libui/src/ui_el/ui_el_change_size.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ui_el_change_size.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: edraugr- <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/06/03 22:01:02 by sbecker #+# #+# */ /* Updated: 2019/06/05 16:42:03 by edraugr- ### ########.fr */ /* */ /* ************************************************************************** */ #include "libui.h" static void ui_el_change_size_in_tree(void *a1, void *a2) { t_ui_el *el; t_vec2 *dist; el = (t_ui_el *)a1; dist = (t_vec2 *)a2; el->rect.w += dist->x; el->rect.h += dist->y; el->rrect.w = (float)el->rect.w / (float)el->parent->rect.w; el->rrect.h = (float)el->rect.h / (float)el->parent->rect.h; el->crect.w = el->rect.w; el->crect.h = el->rect.h; } void ui_el_change_size(t_ui_el *el, t_ui_el *canvas, int type, t_fvec2 v) { t_vec2 dist; if (type & PIXEL) { dist.x = roundf(v.x); dist.y = roundf(v.y); } else if ((type & ABS)) { dist.x = roundf((float)canvas->rect.w * v.x); dist.y = roundf((float)canvas->rect.h * v.y); } else { dist.x = roundf((float)el->parent->rect.w * v.x); dist.y = roundf((float)el->parent->rect.h * v.y); } bfs_iter_root(el, ui_el_change_size_in_tree, &dist); }
dolovnyak/ray-marching-render
libui/src/ui_el/ui_el_set_text.c
<reponame>dolovnyak/ray-marching-render /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ui_el_set_text.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: sbecker <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/06/11 01:55:53 by sbecker #+# #+# */ /* Updated: 2019/07/14 09:31:18 by sbecker ### ########.fr */ /* */ /* ************************************************************************** */ #include "libui.h" static void add_change_text_events(t_ui_el *el) { int i; i = -1; while (++i < KEYS_COUNT) ui_event_add_listener(el->events->on_key_down[i], ui_el_event_change_text); } int ui_el_set_text(t_ui_el *el, TTF_Font *font, t_text_params text_params) { el->text_area = (t_ui_text *)ft_memalloc(sizeof(t_ui_text)); el->text_area->font = font; el->text_area->string_len = text_params.string_len; el->text_area->text_color = text_params.text_color; el->text_area->render_param = text_params.render_param; el->text_area->params = text_params.params; el->text_area->bg_color = text_params.bg_color; el->params |= EL_IS_TEXT; add_change_text_events(el); ui_el_update_text(el, ""); return (FUNCTION_SUCCESS); }
dolovnyak/ray-marching-render
libui/src/ui_el/ui_el_add_texture_from_file.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ui_el_add_texture_from_file.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: sbecker <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/07/15 07:05:59 by sbecker #+# #+# */ /* Updated: 2019/07/15 07:13:24 by sbecker ### ########.fr */ /* */ /* ************************************************************************** */ #include "libui.h" int ui_el_add_texture_from_file(t_ui_el *el, const char *path, const char *tid) { t_list_texture *tmp_lst; SDL_Texture *tmp; int hash; hash = ft_strhash(tid); tmp_lst = NULL; tmp = NULL; if (ctid(el->sdl_textures, hash) || !(tmp_lst = ft_lstnew(NULL, 0))) ui_sdl_deinit(228); if (ui_el_load_surface_from(el, path) == FUNCTION_FAILURE || (tmp = ui_el_create_texture(el)) == NULL) ui_sdl_deinit(228); tmp_lst->content_size = hash; tmp_lst->content = (void *)tmp; ft_lstadd(&(el->sdl_textures), tmp_lst); return (FUNCTION_SUCCESS); }
dolovnyak/ray-marching-render
libui/src/ui_prefab/ui_prefab_get_pixel_size.c
<gh_stars>1-10 /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ui_prefab_get_pixel_size.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: sbecker <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/06/06 00:00:42 by sbecker #+# #+# */ /* Updated: 2019/06/06 01:25:30 by sbecker ### ########.fr */ /* */ /* ************************************************************************** */ #include "libui.h" void ui_prefab_get_pixel_size(t_ui_el *p, t_ui_el *canvas, int type, t_fvec2 *v) { if ((type & PIXEL)) { v->x = roundf(v->x); v->y = roundf(v->y); } else if ((type & ABS)) { v->x = roundf((float)canvas->rect.w * v->x); v->y = roundf((float)canvas->rect.h * v->y); } else { v->x = roundf((float)p->rect.w * v->x); v->y = roundf((float)p->rect.h * v->y); } }
dolovnyak/ray-marching-render
libui/src/ui_sdl/ui_sdl_win_position.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ui_sdl_win_position.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: sbecker <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/07/15 12:23:53 by sbecker #+# #+# */ /* Updated: 2019/07/15 12:23:55 by sbecker ### ########.fr */ /* */ /* ************************************************************************** */ #include "libui.h" void ui_sdl_set_window_position(SDL_Window *w, int x, int y) { SDL_SetWindowPosition(w, x, y); } void ui_sdl_get_window_position(SDL_Window *w, int *x, int *y) { SDL_GetWindowPosition(w, x, y); } void ui_sdl_raise_window(SDL_Window *w) { SDL_RaiseWindow(w); }
dolovnyak/ray-marching-render
libjtoc/src/jtoc_validate_value.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* jtoc_validate_value.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: sbednar <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/06/02 20:30:23 by sbednar #+# #+# */ /* Updated: 2019/06/02 20:31:49 by sbednar ### ########.fr */ /* */ /* ************************************************************************** */ #include "libjtoc.h" int jtoc_validate_number(const char *str, int b, int e) { if (str[b] == '-') ++b; while (b <= e && str[b] >= '0' && str[b] <= '9') ++b; if ((b < e && str[b] != '.') || (b == e && str[b] == '.')) return (FUNCTION_FAILURE); if (str[b] == '.') ++b; while (b <= e && str[b] >= '0' && str[b] <= '9') ++b; return (b < e ? FUNCTION_FAILURE : FUNCTION_SUCCESS); } int jtoc_validate_string(const char *str, int b, int e) { if (e - b == 3 && !ft_strncmp(str + b, "null", 4)) return (FUNCTION_SUCCESS); return (str[b] == '"' && str[e] == '"' ? FUNCTION_SUCCESS : FUNCTION_FAILURE); } int jtoc_validate_object(const char *str, int b, int e) { int c; if (str[e] == '\n') --e; if (e - b == 3 && !ft_strncmp(str + b, "null", 4)) return (FUNCTION_SUCCESS); if (str[b++] != '{' || str[e--] != '}') return (FUNCTION_FAILURE); while (b < e) { if ((c = jtoc_find_comma(str, b) - 1) < 0 || c > e) c = e; if (jtoc_validate_field(str, b, c) < 0) return (FUNCTION_FAILURE); b = c + (c == e ? 0 : 2); } return (b > e ? FUNCTION_FAILURE : FUNCTION_SUCCESS); } int jtoc_validate_array(const char *str, int b, int e) { int c; if (e - b == 3 && !ft_strncmp(str + b, "null", 4)) return (FUNCTION_SUCCESS); if (str[b++] != '[' || str[e--] != ']') return (FUNCTION_FAILURE); while (b < e) { if ((c = jtoc_find_comma(str, b) - 1) < 0 || c > e) c = e; if (jtoc_validate_value(str, b, c)) return (FUNCTION_FAILURE); b = c + (c == e ? 0 : 2); } return (b > e ? FUNCTION_FAILURE : FUNCTION_SUCCESS); }
dolovnyak/ray-marching-render
libui/src/ui_jtoc/ui_jtoc_main_from_json.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ui_jtoc_main_from_json.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: sbecker <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/07/12 06:52:57 by sbecker #+# #+# */ /* Updated: 2019/07/12 07:04:43 by sbecker ### ########.fr */ /* */ /* ************************************************************************** */ #include "libui.h" int ui_jtoc_main_from_json(t_ui_main *m, const char *p) { t_jnode *root; t_jnode *win; ui_main_fill_default_functions(m); if (!(root = jtoc_read(p))) return (ui_jtoc_sdl_log_error("JSON", -1)); if (!(win = jtoc_node_get_by_path(root, "windows")) || win->type != array) return (ui_jtoc_sdl_log_error("NODE WINDOWS", -1)); win = win->down; while (win) { if (win->type != object) return (ui_jtoc_sdl_log_error("NODE WINDOW (TYPE)", -1)); if (ui_jtoc_win_from_json(m, win)) ui_sdl_deinit(228); win = win->right; } jtoc_node_clear(root); return (FUNCTION_SUCCESS); }
dolovnyak/ray-marching-render
include/rt_light.h
<reponame>dolovnyak/ray-marching-render /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* rt_light.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: sbecker <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/04/10 05:13:21 by sbecker #+# #+# */ /* Updated: 2019/07/03 20:16:18 by sbecker ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef RT_LIGHT_H # define RT_LIGHT_H # ifndef OPENCL___ # ifdef APPLE___ # include <OpenCL/opencl.h> # else # include <opencl.h> # endif # endif # include "transform.h" typedef struct s_directional { # ifndef OPENCL___ cl_float3 color; # else float3 color; # endif } t_directional; typedef struct s_point { # ifndef OPENCL___ cl_float3 color; cl_float distance; # else float3 color; float distance; # endif } t_point; union u_lparams { t_directional directional; t_point point; }; enum e_light_type { directional, point }; typedef struct s_light { t_transform transform; union u_lparams params; enum e_light_type type; } t_light; #endif
dolovnyak/ray-marching-render
libui/src/ui_win/ui_win_setup_default.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ui_win_setup_default.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: sbecker <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/04/15 05:38:36 by sbednar #+# #+# */ /* Updated: 2019/07/15 15:23:17 by sbecker ### ########.fr */ /* */ /* ************************************************************************** */ #include "libui.h" static int ui_win_invoke_key_down_on_focused_el(t_ui_main *m, void *a) { t_ui_el *el; (void)a; el = m->focused_el; if (!el) return (1); if (m->cur_keycode == SDL_SCANCODE_ESCAPE) m->focused_el = NULL; else ui_event_invoke(el->events->on_key_down[m->cur_keycode], m, el); return (1); } static void ui_win_setup_default_logs(t_ui_win *w) { ui_event_add_listener(w->events->on_focus_lost, ui_log_window_focus_lost); ui_event_add_listener(w->events->on_focus_gained, ui_log_window_focus_gained); ui_event_add_listener(w->events->on_resize, ui_log_window_resized); ui_event_add_listener(w->events->on_close, ui_log_window_closed); ui_event_add_listener(w->events->on_moved, ui_log_window_moved); } static void ui_win_setup_default_keyboard_events(t_ui_win *w) { int i; i = -1; while (++i < KEYS_COUNT) ui_event_add_listener(w->events->on_key_down[i], ui_win_invoke_key_down_on_focused_el); } void ui_win_setup_default(t_ui_win *w) { ui_win_setup_default_keyboard_events(w); ui_event_add_listener(w->events->on_pointer_moved, ui_main_event_pointer_moved); ui_event_add_listener(w->events->on_pointer_left_button_pressed, ui_main_event_lmb_pressed); ui_event_add_listener(w->events->on_pointer_left_button_released, ui_main_event_lmb_released); ui_event_add_listener(w->events->on_pointer_right_button_pressed, ui_main_event_rmb_pressed); ui_event_add_listener(w->events->on_pointer_right_button_released, ui_main_event_rmb_released); ui_event_add_listener(w->events->on_scroll_up, ui_main_event_scroll_up); ui_event_add_listener(w->events->on_scroll_down, ui_main_event_scroll_down); ui_event_add_listener(w->events->on_focus_gained, ui_win_event_focus_gained); ui_event_add_listener(w->events->on_focus_lost, ui_win_event_focus_lost); ui_event_add_listener(w->events->on_focus_lost, ui_main_event_lmb_released); ui_event_add_listener(w->events->on_focus_lost, ui_main_event_rmb_released); if (DEBUG_STATUS == 1) ui_win_setup_default_logs(w); }
dolovnyak/ray-marching-render
src/interface/uix_render_mode_choose.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* uix_render_mode_choose.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: edraugr- <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/09/26 15:59:02 by edraugr- #+# #+# */ /* Updated: 2019/09/26 15:59:05 by edraugr- ### ########.fr */ /* */ /* ************************************************************************** */ #include "interface.h" int rt_uix_choose_path_trace(t_ui_main *main, void *el_v) { (void)el_v; ((t_rt_main *)main->data)->scene->params = RT_PATH_TRACE; rt_render_update(main, ui_win_find_el_by_id(ui_main_find_window_by_id(main, 0), 1)); return (1); } int rt_uix_choose_none(t_ui_main *main, void *el_v) { (void)el_v; ((t_rt_main *)main->data)->scene->params = 0; rt_render_update(main, ui_win_find_el_by_id(ui_main_find_window_by_id(main, 0), 1)); return (1); } int rt_uix_choose_pong(t_ui_main *main, void *el_v) { (void)el_v; ((t_rt_main *)main->data)->scene->params = RT_PHONG; rt_render_update(main, ui_win_find_el_by_id(ui_main_find_window_by_id(main, 0), 1)); return (1); }
dolovnyak/ray-marching-render
libui/src/ui_el/ui_el_set_pos.c
<reponame>dolovnyak/ray-marching-render<filename>libui/src/ui_el/ui_el_set_pos.c<gh_stars>1-10 /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ui_el_set_pos.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: edraugr- <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/05/24 15:45:47 by sbecker #+# #+# */ /* Updated: 2019/07/15 04:02:37 by edraugr- ### ########.fr */ /* */ /* ************************************************************************** */ #include "libui.h" static void set_rect(t_ui_el *el, int x, int y) { el->rect.x = x; el->rect.y = y; } void ui_el_set_pos(t_ui_el *el, int type, t_fvec2 v) { t_ui_el *p; p = el; while (p->parent) p = p->parent; if ((type & ABS) && (type & PIXEL)) set_rect(el, (int)roundf(v.x), (int)roundf(v.y)); else if ((type & ABS)) set_rect(el, (int)roundf((float)p->rect.w * v.x), (int)roundf((float)p->rect.h * v.y)); else if ((type & PIXEL)) set_rect(el, (int)roundf((float)el->parent->rect.x + v.x), (int)roundf((float)el->parent->rect.y + v.y)); else set_rect(el, (int)roundf((float)el->parent->rect.x + (float)el->parent->rect.w * v.x), (int)roundf((float)el->parent->rect.y + (float)el->parent->rect.h * v.y)); el->rrect.x = (float)(el->rect.x - el->parent->rect.x) / (float)el->parent->rect.w; el->rrect.y = (float)(el->rect.y - el->parent->rect.y) / (float)el->parent->rect.h; el->crect.x = el->rect.x; el->crect.y = el->rect.y; }
dolovnyak/ray-marching-render
src/cl/pp/pp_monochrome.c
<gh_stars>1-10 #include "rt_cl.h" __kernel void pp_monochrome( const __global int *input_data, __global int *output_data, int2 screen) { int tx = get_global_id(0); int ty = get_global_id(1); int index = ty * screen.x + tx; int red = (input_data[index] >> 16) & 0xFF; int green = (input_data[index] >> 8) & 0xFF; int blue = input_data[index] & 0xFF; float3 v = (float3)(red, green, blue) / 255.0f; float3 c_linear; float y_linear; c_linear.x = v.x > 0.04045f ? pow((v.x + 0.055f) / 1.055f, 2.4f) : v.x / 12.92f; c_linear.y = v.y > 0.04045f ? pow((v.y + 0.055f) / 1.055f, 2.4f) : v.y / 12.92f; c_linear.z = v.z > 0.04045f ? pow((v.z + 0.055f) / 1.055f, 2.4f) : v.z / 12.92f; y_linear = 0.2126f * c_linear.x + 0.7152f * c_linear.y + 0.0722f * c_linear.z; v.x = y_linear > 0.0031308f ? 1.055f * pow(y_linear, 1.f / 2.4f) - 0.055f : 12.92f * y_linear; v.y = v.x; v.z = v.x; output_data[index] = get_color(v); }
dolovnyak/ray-marching-render
src/interface/uix_choose_obj_from_scene.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* uix_choose_obj_from_scene.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: edraugr- <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/10/05 15:19:23 by edraugr- #+# #+# */ /* Updated: 2019/10/05 15:19:27 by edraugr- ### ########.fr */ /* */ /* ************************************************************************** */ #include "interface.h" int rt_uix_choose_obj_from_scene(t_ui_main *main, void *el_v) { t_ui_el *inspector; inspector = ui_win_find_el_by_id( ui_main_find_window_by_id(main, 1), INSPECTOR_EL_ID); inspector->data = ((t_ui_el *)el_v)->data; rt_uix_update_inspector_values(main); return 1; }
dolovnyak/ray-marching-render
src/rt_jtoc/rt_jtoc_get_objects.c
#include "rt.h" #include "rt_jtoc.h" #include "rt_raycast.h" int rt_jtoc_compare_str_with_texture_name(t_obj_texture *texture, char *str) { int i; int cache_counter; i = -1; cache_counter = texture->textures_count; while (++i < cache_counter) if ((ft_strstr(texture->textures_path[i], str))) return (i); return (-2); } int rt_jtoc_get_object_texture(t_object *obj, t_obj_texture *texture, t_jnode *n) { t_jnode *tmp; int id; char *str; if (!(tmp = jtoc_node_get_by_path(n, "texture")) || tmp->type != string) return (rt_jtoc_sdl_log_error("TEXTURE ERROR OR TEXTURE IS MISSING", -1)); str = jtoc_get_string(tmp); if (!(ft_strcmp(str, "none"))) id = -1; else id = rt_jtoc_compare_str_with_texture_name(texture, str); if (id == -2) return (rt_jtoc_sdl_log_error("TEXTURE NAME ERROR OR TEXTURE NAME IS MISSING", -1)); obj->material.texture_id = id; return (FUNCTION_SUCCESS); } int rt_jtoc_get_object_type(t_object *obj, t_jnode *n) { char *str; t_jnode *tmp; if (!(tmp = jtoc_node_get_by_path(n, "type")) || tmp->type != string) return (rt_jtoc_sdl_log_error("TYPE ERROR OR TYPE IS MISSING", -1)); str = jtoc_get_string(tmp); obj->type = 0; obj->type = ft_strcmp(str, "sphere") ? obj->type : o_sphere; obj->type = ft_strcmp(str, "box") ? obj->type : o_box; obj->type = ft_strcmp(str, "round_box") ? obj->type : o_round_box; obj->type = ft_strcmp(str, "torus") ? obj->type : o_torus; obj->type = ft_strcmp(str, "capped_torus") ? obj->type : o_capped_torus; obj->type = ft_strcmp(str, "link") ? obj->type : o_link; obj->type = ft_strcmp(str, "cylinder") ? obj->type : o_cylinder; obj->type = ft_strcmp(str, "cone") ? obj->type : o_cone; obj->type = ft_strcmp(str, "plane") ? obj->type : o_plane; obj->type = ft_strcmp(str, "octahedron") ? obj->type : o_octahedron; obj->type = ft_strcmp(str, "mandelbulb") ? obj->type : o_mandelbulb; obj->type = ft_strcmp(str, "mandelbox") ? obj->type : o_mandelbox; obj->type = ft_strcmp(str, "menger_sponge") ? obj->type : o_menger_sponge; if (obj->type == 0) return (FUNCTION_FAILURE); return (FUNCTION_SUCCESS); } int rt_jtoc_get_object_layer(t_object *obj, t_jnode *n) { t_jnode *tmp; char *str; if (!(tmp = jtoc_node_get_by_path(n, "layer")) || tmp->type != string) return (rt_jtoc_sdl_log_error("LAYER ERROR OR LAYER IS MISSING", -1)); str = jtoc_get_string(tmp); obj->layer = 0; obj->layer |= ft_strcmp(str, "default_layer") ? DEFAULT_LAYER : obj->layer; obj->layer |= ft_strcmp(str, "ignore_raycast_layer") ? IGNORE_RAYCAST_LAYER : obj->layer; if (obj->layer == 0) obj->layer = DEFAULT_LAYER; return (FUNCTION_SUCCESS); } int rt_jtoc_check_and_get_id_for_object(t_scene *scene, t_jnode *n, t_object *object) { t_jnode *tmp; cl_uint id; if (!(tmp = jtoc_node_get_by_path(n, "id")) || tmp->type != integer) return (rt_jtoc_sdl_log_error("ID ERROR", -1)); id = jtoc_get_int(tmp); if (id <= 0) return (FUNCTION_FAILURE); if (scene->camera.transform.id == (cl_uint)id) return (rt_jtoc_sdl_log_error("THAT ID ALREADY EXISTS IN CAMERA", id)); if (rt_find_light_by_id(scene->lights, id)) return (rt_jtoc_sdl_log_error("THAT ID ALREADY EXISTS IN LIGHTS", id)); if (rt_find_object_by_id(scene->objects, id)) return (rt_jtoc_sdl_log_error("THAT ID ALREADY EXISTS IN OBJECTS", id)); object->transform.id = id; return (FUNCTION_SUCCESS); } int rt_jtoc_get_type_name(int type, int id, char *str) { char *tmp_id; char tmp_str[15]; ft_bzero(tmp_str, 15); tmp_id = ft_itoa(id); if (type == o_sphere) ft_strcat(ft_strcat(str,"Sphere"), tmp_id); else if (type == o_box) ft_strcat(ft_strcat(str,"Box"), tmp_id); else if (type == o_round_box) ft_strcat(ft_strcat(str,"Round Box"), tmp_id); else if (type == o_torus) ft_strcat(ft_strcat(str,"Torus"), tmp_id); else if (type == o_capped_torus) ft_strcat(ft_strcat(str,"Capped Torus"), tmp_id); else if (type == o_link) ft_strcat(ft_strcat(str,"Link"), tmp_id); else if (type == o_cylinder) ft_strcat(ft_strcat(str,"Cylinder"), tmp_id); else if (type == o_cone) ft_strcat(ft_strcat(str,"Cone"), tmp_id); else if (type == o_plane) ft_strcat(ft_strcat(str,"Plane"), tmp_id); else if (type == o_octahedron) ft_strcat(ft_strcat(str, "Octahedron"), tmp_id); else if (type == o_mandelbulb) ft_strcat(ft_strcat(str,"Mandelbulb"), tmp_id); else if (type == o_mandelbox) ft_strcat(ft_strcat(str,"Mandelbox"), tmp_id); else if (type == o_menger_sponge) ft_strcat(ft_strcat(str,"Menger Sponge"), tmp_id); free(tmp_id); return (FUNCTION_SUCCESS); } //int rt_jtoc_get_type_name(int type, int id, char *str) юзать если объявлять str на стеке //{ // char *tmp_id; // char tmp_str[30]; // // ft_bzero(tmp_str, 30); // tmp_id = ft_itoa(id); // if (type == o_sphere) // ft_strcat(str, ft_strcat(ft_strcat(tmp_str,"Sphere"), tmp_id)); // else if (type == o_box) // ft_strcat(str, ft_strcat(ft_strcat(tmp_str,"Box"), tmp_id)); // else if (type == o_round_box) // ft_strcat(str, ft_strcat(ft_strcat(tmp_str,"Round Box"), tmp_id)); // else if (type == o_torus) // ft_strcat(str, ft_strcat(ft_strcat(tmp_str,"Torus"), tmp_id)); // else if (type == o_capped_torus) // ft_strcat(str, ft_strcat(ft_strcat(tmp_str,"Capped Torus"), tmp_id)); // else if (type == o_link) // ft_strcat(str, ft_strcat(ft_strcat(tmp_str,"Link"), tmp_id)); // else if (type == o_cylinder) // ft_strcat(str, ft_strcat(ft_strcat(tmp_str,"Cylinder"), tmp_id)); // else if (type == o_cone) // ft_strcat(str, ft_strcat(ft_strcat(tmp_str,"Cone"), tmp_id)); // else if (type == o_plane) // ft_strcat(str, ft_strcat(ft_strcat(tmp_str,"Plane"), tmp_id)); // else if (type == o_mandelbulb) // ft_strcat(str, ft_strcat(ft_strcat(tmp_str,"Mandelbulb"), tmp_id)); // else if (type == o_mandelbox) // ft_strcat(str, ft_strcat(ft_strcat(tmp_str,"Mandelbox"), tmp_id)); // free(tmp_id); // return (FUNCTION_SUCCESS); //} int rt_jtoc_compare_name(t_object *obj, int i, char str[1000][15], int name) { int tmp; tmp = i; while (tmp > 0) { if (ft_strcmp(obj->local_name, str[tmp - 1]) == 0) break; else tmp--; } if (tmp == 0) return (FUNCTION_SUCCESS); else { ft_bzero(str[i], 15); rt_jtoc_get_type_name(obj->type, name, str[i]); obj->local_name = str[i]; name++; rt_jtoc_compare_name(obj, i, str, name); } return (FUNCTION_SUCCESS); } int rt_jtoc_get_object_name(t_object *obj, t_jnode *n) { t_jnode *tmp; char *str; int name; static int i = 0; static char tmp_str[1000][15]; if (!(str = (char *)ft_x_memalloc(sizeof(char) * 16))) return (FUNCTION_FAILURE); name = 0; if ((tmp = jtoc_node_get_by_path(n, "name")) && tmp->type == string) { ft_strncpy(str, jtoc_get_string(tmp), 15); obj->local_name = str; } else { rt_jtoc_get_type_name(obj->type, name, str); obj->local_name = str; } ft_strcpy(tmp_str[i], str); rt_jtoc_compare_name(obj, i, tmp_str, name); obj->local_name = tmp_str[i]; i++; free(str); return (FUNCTION_SUCCESS); } int rt_jtoc_get_object(t_object *obj, t_jnode *n, t_scene *scene, t_obj_texture *texture) { t_jnode *tmp; int err; ft_bzero(obj, sizeof(t_object)); if (rt_jtoc_get_object_type(obj, n)) return (rt_jtoc_sdl_log_error("NOT VALID TYPE", -1)); if (rt_jtoc_get_object_layer(obj, n)) return (rt_jtoc_sdl_log_error("NOT VALID LAYER", -1)); if (rt_jtoc_get_object_texture(obj, texture , n)) return(rt_jtoc_sdl_log_error("NOT VALID TEXTURE", -1)); if (rt_jtoc_get_transform(&obj->transform, n)) return (rt_jtoc_sdl_log_error("TRANSFORM ERROR", -1)); if (!(tmp = jtoc_node_get_by_path(n, "color")) || tmp->type != object) return (rt_jtoc_sdl_log_error("COLOR TYPE ERROR OR COLOR IS MISSING", -1)); if (rt_jtoc_get_float4(&obj->material.color, tmp)) return (rt_jtoc_sdl_log_error("COLOR ERROR", -1)); if (rt_jtoc_check_and_get_id_for_object(scene, n, obj)) return (rt_jtoc_sdl_log_error("ID ERROR", -1)); rt_jtoc_get_object_name(obj, n); obj->sub_mult_flag = 0; obj->obj_with_oper_id = 0; err = 0; err = obj->type == o_sphere ? rt_jtoc_get_sphere(obj, n) : err; err = obj->type == o_box ? rt_jtoc_get_box(obj, n) : err; err = obj->type == o_round_box ? rt_jtoc_get_round_box(obj, n) : err; err = obj->type == o_torus ? rt_jtoc_get_torus(obj, n) : err; err = obj->type == o_plane ? rt_jtoc_get_plane(obj, n) : err; err = obj->type == o_cone ? rt_jtoc_get_cone(obj, n) : err; err = obj->type == o_cylinder ? rt_jtoc_get_cylinder(obj, n) : err; err = obj->type == o_link ? rt_jtoc_get_link(obj, n) : err; err = obj->type == o_octahedron ? rt_jtoc_get_octahedron(obj, n) : err; err = obj->type == o_mandelbulb ? rt_jtoc_get_mandelbulb(obj, n) : err; err = obj->type == o_mandelbox ? rt_jtoc_get_mandelbox(obj, n) : err; err = obj->type == o_menger_sponge ? rt_jtoc_get_menger_sponge(obj, n) : err; if (err != 0) return (FUNCTION_FAILURE); return (FUNCTION_SUCCESS); } int rt_jtoc_get_objects(t_scene *scene, t_jnode *n, t_obj_texture *texture) { t_jnode *tmp; t_object obj; uint c; int i; c = 0; if (rt_jtoc_get_objects_num_in_arr(&c, n) || !(scene->objects = vec_init(c, sizeof(t_object)))) return (FUNCTION_FAILURE); if (c >= 100) return (rt_jtoc_sdl_log_error("OBJECT OVER 100", -1)); tmp = n->down; i = 0; while (tmp) { if (tmp->type != object) return (rt_jtoc_sdl_log_error("OBJECT TYPE ERROR", i)); if (rt_jtoc_get_object(&obj, tmp, scene, texture)) return (rt_jtoc_sdl_log_error("OBJECT DATA ERROR", i)); vec_push_back(scene->objects, &obj); i++; tmp = tmp->right; } return (FUNCTION_SUCCESS); }
dolovnyak/ray-marching-render
libui/src/ui_main/ui_main_event_pointer_moved.c
<reponame>dolovnyak/ray-marching-render<filename>libui/src/ui_main/ui_main_event_pointer_moved.c<gh_stars>1-10 /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ui_main_event_pointer_moved.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: sbecker <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/07/12 05:03:30 by sbecker #+# #+# */ /* Updated: 2019/07/15 11:55:46 by sbecker ### ########.fr */ /* */ /* ************************************************************************** */ #include "libui.h" int ui_main_event_pointer_moved(t_ui_main *m, void *a) { (void)a; m->raycaster->focused_win = ui_main_find_window_by_sdl_id(m, m->sdl_event->motion.windowID); m->ptr_pos.x = m->sdl_event->motion.x; m->ptr_pos.y = m->sdl_event->motion.y; return (1); }
dolovnyak/ray-marching-render
src/rt_jtoc/rt_jtoc_utilits.c
<gh_stars>1-10 #include "rt.h" int rt_jtoc_sdl_log_error(const char *p, const int id) { SDL_Log("%s ----> ERROR <---- %s", KRED, KNRM); SDL_Log("INCORRECT: %s%s%s%s%s", p, id < 0 ? "" : " IN ID = ", KGRN, id < 0 ? "" : ft_itoa(id), KNRM); return (FUNCTION_FAILURE); } int rt_jtoc_get_objects_num_in_arr(unsigned int *objects_num, t_jnode *n) { t_jnode *tmp; if (n == NULL) return (FUNCTION_SUCCESS); if (n->type != array) return (rt_jtoc_sdl_log_error("TYPE IS NOT ARRAY", -1)); tmp = n->down; while (tmp) { if (tmp->type != object) return (rt_jtoc_sdl_log_error("TYPE IS NOT OBJECT", -1)); (*objects_num)++; tmp = tmp->right; } return (FUNCTION_SUCCESS); } int rt_jtoc_get_float2(cl_float2 *vec, t_jnode *n) { t_jnode *tmp; if (!(tmp = jtoc_node_get_by_path(n, "x")) || tmp->type != fractional) return (rt_jtoc_sdl_log_error("X ERROR", -1)); vec->x = jtoc_get_float(tmp); if (!(tmp = jtoc_node_get_by_path(n, "y")) || tmp->type != fractional) return (rt_jtoc_sdl_log_error("Y ERROR", -1)); vec->y = jtoc_get_float(tmp); return (FUNCTION_SUCCESS); } int rt_jtoc_get_float3(cl_float3 *vec, t_jnode *n) { t_jnode *tmp; if (!(tmp = jtoc_node_get_by_path(n, "x")) || tmp->type != fractional) return (rt_jtoc_sdl_log_error("X ERROR", -1)); vec->x = jtoc_get_float(tmp); if (!(tmp = jtoc_node_get_by_path(n, "y")) || tmp->type != fractional) return (rt_jtoc_sdl_log_error("Y ERROR", -1)); vec->y = jtoc_get_float(tmp); if (!(tmp = jtoc_node_get_by_path(n, "z")) || tmp->type != fractional) return (rt_jtoc_sdl_log_error("Z ERROR", -1)); vec->z = jtoc_get_float(tmp); return (FUNCTION_SUCCESS); } int rt_jtoc_get_float4(cl_float4 *vec, t_jnode *n) { t_jnode *tmp; if (!(tmp = jtoc_node_get_by_path(n, "x")) || tmp->type != fractional) return (rt_jtoc_sdl_log_error("X ERROR", -1)); vec->x = jtoc_get_float(tmp); if (!(tmp = jtoc_node_get_by_path(n, "y")) || tmp->type != fractional) return (rt_jtoc_sdl_log_error("Y ERROR", -1)); vec->y = jtoc_get_float(tmp); if (!(tmp = jtoc_node_get_by_path(n, "z")) || tmp->type != fractional) return (rt_jtoc_sdl_log_error("Z ERROR", -1)); vec->z = jtoc_get_float(tmp); if (!(tmp = jtoc_node_get_by_path(n, "w")) || tmp->type != fractional) return (rt_jtoc_sdl_log_error("W ERROR", -1)); vec->w = jtoc_get_float(tmp); return (FUNCTION_SUCCESS); } int rt_jtoc_ispos_float2(cl_float2 *vec) { return (vec->x >= 0 && vec->y >= 0 ? FUNCTION_SUCCESS : FUNCTION_FAILURE); } int rt_jtoc_ispos_float3(cl_float3 *vec) { return (vec->x >= 0 && vec->y >= 0 && vec->z >= 0 ? FUNCTION_SUCCESS : FUNCTION_FAILURE); } int rt_jtoc_is01_float3(cl_float3 *vec) { return (vec->x >= 0 && vec->x <= 1 && vec->y >= 0 && vec->y <= 1 && vec->z >= 0 && vec->z <= 1 ? FUNCTION_SUCCESS : FUNCTION_FAILURE); } int rt_jtoc_ispos_float4(cl_float4 *vec) { return (vec->x >= 0 && vec->y >= 0 && vec->z >= 0 && vec->w >= 0 ? FUNCTION_SUCCESS : FUNCTION_FAILURE); }
dolovnyak/ray-marching-render
src/rt_render_processing.c
#include "rt.h" #include "time.h" static void create_buffers_for_render(t_rt_main *rt, cl_mem *cl_scene, cl_mem *cl_objects, cl_mem *cl_lights) { *cl_scene = clCreateBuffer(*rt->cl->context, CL_MEM_READ_ONLY, sizeof(t_scene), NULL, NULL); *cl_objects = clCreateBuffer(*rt->cl->context, CL_MEM_READ_ONLY, sizeof(t_object) * rt->scene[0].objects->size, NULL, NULL); *cl_lights = clCreateBuffer(*rt->cl->context, CL_MEM_READ_ONLY, sizeof(t_light) * rt->scene[0].lights->size, NULL, NULL); clEnqueueWriteBuffer(*rt->cl->queue, *cl_scene, CL_TRUE, 0, sizeof(t_scene), &rt->scene[0], 0, NULL, NULL); clEnqueueWriteBuffer(*rt->cl->queue, *cl_objects, CL_TRUE, 0, sizeof(t_object) * rt->scene[0].objects->size, rt->scene[0].objects->storage, 0, NULL, NULL); clEnqueueWriteBuffer(*rt->cl->queue, *cl_lights, CL_TRUE, 0, sizeof(t_light) * rt->scene[0].lights->size, rt->scene[0].lights->storage, 0, NULL, NULL); } int time1; int time2; void render_processing(t_rt_main *rt, size_t global_size[2], cl_int path_trace_count) { cl_kernel *kernel; cl_mem cl_scene; cl_mem cl_objects; cl_mem cl_lights; time2 = SDL_GetTicks(); SDL_Log("TICK: %d", time2 - time1); time1 = time2; create_buffers_for_render(rt, &cl_scene, &cl_objects, &cl_lights); // rt->scenes[0].objects[0].params.mandelbulb.power = 10 + 10 * (sin(clock() / (CLOCKS_PER_SEC * 10.0f)) + 1); //для изменения фрактала со временем // rt->scene[0].objects[0].params.mandelbox.scale = -3.73 + 1.3 * (sin(clock() / (CLOCKS_PER_SEC * 3.0f)) + 1); //для изменения фрактала со временем kernel = cl_get_kernel_by_name(rt->cl, "ray_march_render"); cl_int2 rands; srand(time1); rands.x = rand(); rands.y = rand(); clSetKernelArg(*kernel, 0, sizeof(cl_mem), &rt->gpu_mem->cl_image); clSetKernelArg(*kernel, 1, sizeof(cl_mem), &cl_scene); clSetKernelArg(*kernel, 2, sizeof(cl_mem), &cl_objects); clSetKernelArg(*kernel, 3, sizeof(cl_int), &rt->scene->objects->size); clSetKernelArg(*kernel, 4, sizeof(cl_mem), &cl_lights); clSetKernelArg(*kernel, 5, sizeof(cl_mem), &rt->scene->lights->size); clSetKernelArg(*kernel, 6, sizeof(cl_int2), &rt->screen_size); clSetKernelArg(*kernel, 7, sizeof(cl_mem), &rt->gpu_mem->cl_texture); clSetKernelArg(*kernel, 8, sizeof(cl_mem), &rt->gpu_mem->cl_texture_w); clSetKernelArg(*kernel, 9, sizeof(cl_mem), &rt->gpu_mem->cl_texture_h); clSetKernelArg(*kernel, 10, sizeof(cl_mem), &rt->gpu_mem->cl_prev_texture_size); clSetKernelArg(*kernel, 11, sizeof(cl_int), &path_trace_count); clSetKernelArg(*kernel, 12, sizeof(cl_mem), &rt->gpu_mem->cl_pt_color_buf); clSetKernelArg(*kernel, 13, sizeof(cl_int2), &rands); clEnqueueNDRangeKernel(*rt->cl->queue, *kernel, 2, NULL, global_size, NULL, 0, NULL, NULL); clReleaseMemObject(cl_objects); clReleaseMemObject(cl_lights); clReleaseMemObject(cl_scene); }
dolovnyak/ray-marching-render
src/rt_jtoc/rt_jtoc_get_camera.c
<filename>src/rt_jtoc/rt_jtoc_get_camera.c<gh_stars>1-10 // // Created by <NAME> on 2019-09-13. // #include "rt.h" #include "rt_jtoc.h" static int rt_jtoc_get_clipping_planes(t_clipping *clipping_planes, t_jnode *n) { t_jnode *tmp; if (!(n = jtoc_node_get_by_path(n, "clipping_planes")) || n->type != object) return (rt_jtoc_sdl_log_error("CLIPPING_PLANES TYPE ERROR OR CLIPPING_PLANES MISSING", -1)); if (!(tmp = jtoc_node_get_by_path(n, "near")) || tmp->type != fractional) return (rt_jtoc_sdl_log_error("NEAR ERROR", -1)); clipping_planes->near = jtoc_get_float(tmp); if (clipping_planes->near < 0) return (rt_jtoc_sdl_log_error("NEAR ERROR", -1)); if (!(tmp = jtoc_node_get_by_path(n, "far")) || tmp->type != fractional) return (rt_jtoc_sdl_log_error("FAR ERROR", -1)); clipping_planes->far = jtoc_get_float(tmp); if (clipping_planes->far < 0 || clipping_planes->far <= clipping_planes->near) return (rt_jtoc_sdl_log_error("FAR ERROR", -1)); return (FUNCTION_SUCCESS); } int rt_jtoc_get_camera(t_camera *camera, t_jnode *n) { t_jnode *tmp; int i; ft_bzero(camera, sizeof(t_camera)); if (!(tmp = jtoc_node_get_by_path(n, "fov")) || tmp->type != fractional) return (rt_jtoc_sdl_log_error("FOV ERROR", -1)); camera->fov = jtoc_get_float(tmp); if (camera->fov < 30 || camera->fov > 180) return (rt_jtoc_sdl_log_error("FOV ERROR", -1)); if (rt_jtoc_get_clipping_planes(&(camera->clipping_planes), n)) return (rt_jtoc_sdl_log_error("CLIPPING_PLANES ERROR", -1)); if (rt_jtoc_get_transform(&(camera->transform), n)) return (rt_jtoc_sdl_log_error("TRANSFORM ERROR", -1)); if (!(tmp = jtoc_node_get_by_path(n, "id")) || tmp->type != integer) return (rt_jtoc_sdl_log_error("CAMERA ID ERROR", -1)); i = jtoc_get_int(tmp); if (i <= 0) return (rt_jtoc_sdl_log_error("CAMERA ID ERROR", -1)); camera->transform.id = i; return (FUNCTION_SUCCESS); }
dolovnyak/ray-marching-render
src/cl/pp/pp_utilities.c
<filename>src/cl/pp/pp_utilities.c #include "rt_cl.h" float gauss_coeff_x(int x, float sigma) { return(1000.f / (sqrt(2 * M_PI_F) * sigma) * exp(-(float)(x * x) / (2 * sigma * sigma))); } float3 int_color(int col) { float3 v; v.x = (float)((col >> 16) & 0xFF) / 255; v.y = (float)((col >> 8) & 0xFF) / 255; v.z = (float)((col) & 0xFF) / 255; return (v); } int get_light(int start, int end, float percentage) { return ((int)((1 - percentage) * start + percentage * end)); } int get_color(float3 v) { int red; int green; int blue; int start; int end; start = 0; end = 0xFFFFFF; red = get_light((start >> 16) & 0xFF, (end >> 16) & 0xFF, v.x); green = get_light((start >> 8) & 0xFF, (end >> 8) & 0xFF, v.y); blue = get_light(start & 0xFF, end & 0xFF, v.z); return ((red << 16) | (green << 8) | blue); }
dolovnyak/ray-marching-render
src/main.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: sbecker <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/07/24 22:28:53 by sbecker #+# #+# */ /* Updated: 2019/07/24 22:28:56 by sbecker ### ########.fr */ /* */ /* ************************************************************************** */ #include <stdlib.h> #include <rt_jtoc.h> #include "rt.h" #include "rt_raycast.h" #include "rt_input_system.h" #include "interface.h" int rt_free_gpu_mem(t_ui_main *m, void *a1) { t_rt_main *rt; (void)a1; rt = (t_rt_main *)m->data; clReleaseMemObject(rt->gpu_mem->cl_aux); clReleaseMemObject(rt->gpu_mem->cl_image); clReleaseMemObject(rt->gpu_mem->cl_prev_texture_size); clReleaseMemObject(rt->gpu_mem->cl_texture); clReleaseMemObject(rt->gpu_mem->cl_texture_h); clReleaseMemObject(rt->gpu_mem->cl_texture_w); return (1); } cl_int2 modification_rt_elem_and_get_screen_size(t_ui_main *ui) { t_ui_win *w; t_ui_el *el; SDL_Texture *t; t_list *lst; cl_int2 rt_screen_size; w = ui_main_find_window_by_id(ui, 0); el = ui_win_find_el_by_id(w, 1); t = SDL_CreateTexture(el->sdl_renderer, SDL_PIXELFORMAT_RGB888, SDL_TEXTUREACCESS_STREAMING, el->rect.w, el->rect.h); lst = ft_lstnew(NULL, 0); lst->content = t; lst->content_size = ft_strhash("default"); ft_lstadd(&el->sdl_textures, lst); rt_screen_size.x = el->rect.w; rt_screen_size.y = el->rect.h; return (rt_screen_size); } int main() { t_rt_main *rt; t_ui_main *ui; cl_int2 rt_screen_size; ui = ui_main_init(); ui_sdl_init(); ui_main_add_function_by_id(ui, rt_render, "rt_render"); ui_main_add_function_by_id(ui, rt_free_gpu_mem, "rt_free_gpu_mem"); rt_uix_interface_setup(ui, "json/interface/main.json"); rt_screen_size = modification_rt_elem_and_get_screen_size(ui); // rt = rt_setup(rt_screen_size, "json/textures.json", "json/scenes/test1_scene/test1.json"); // rt = rt_setup(rt_screen_size, "json/textures.json", "json/scenes/mandelbulb_scene/mandelbulb.json"); // rt = rt_setup(rt_screen_size, "json/textures.json", "json/scenes/scene_nice/test2.json"); rt = rt_setup(rt_screen_size, "json/textures.json", "json/scenes/menger_sponge_scene/menger_sponge.json"); // rt = rt_setup(rt_screen_size, "json/textures.json", "json/scenes/mandelbox_scene/mandelbox.json"); // rt = rt_setup(rt_screen_size, "json/textures.json", "json/scenes/1_scene/scene_1.json"); // rt = rt_setup(rt_screen_size, "json/textures.json", "json/scenes/test_scene/test_scene.json"); ui->data = (void *)rt; rt_uix_scene_setup(ui); //TODO NEEDED FOR PLANE (NOW PLANE IN JSON DOESN'T WORK CORRECTLY) (MAKSON WHAT IT TAKOE WOBSHE?) // t_transform *temp = &rt->scene[0].objects[4].transform; // float d = -(temp->up.x * temp->pos.x + temp->up.y * temp->pos.y + temp->up.z * temp->pos.z); // rt->scene[0].objects[4].params.plane.distance = fabs(d) / sqrt(temp->up.x * temp->up.x + temp->up.y * temp->up.y + temp->up.z * temp->up.z); //TODO CONE IS STRANGE //TODO CYLINDER PARAMS X AND Y ARE USELESS (IT'S Z AND X OFFSET, BUT WE HAVE TRANSFORM) //TODO capped torus doesn't work correctly // rt->scene[0].objects[4].type = o_capped_torus; // rt->scene[0].objects[4].layer = DEFAULT_LAYER; // rt->scene[0].objects[4].params.capped_torus.sc = (cl_float2){{0.4f, 0.5f}}; // rt->scene[0].objects[4].params.capped_torus.ra = 1; // rt->scene[0].objects[4].params.capped_torus.rb = 2; // rt->scene[0].objects[4].transform.pos = (cl_float3){{0, 10, 40}}; // rt->scene[0].objects[4].transform.id = 6; // rt->scene[0].objects[4].material.color = (cl_float4){{0, 1, 1, 1}}; /// PHYSICS SYSTEM START !!!!!!!!!!!!!!!!!!!!!!!!! // rt->scenes[0].objects[0].params.mandelbumb.power = 2; t_physics_system *ps = ft_memalloc(sizeof(t_physics_system)); if (rt_jtoc_ps_setup(rt->scene, ps, "json/scenes/mandelbox_scene/ps.json")) { rt_jtoc_sdl_log_error("PATH PS ERROR OR NOT FOUND", -1); exit (0); } // ps->rbs_count = 1; // ps->rbs = (t_rb *)malloc(sizeof(t_rb) * ps->rbs_count); // ps->rbs[0].move.speed = 10000; // ps->rbs[0].move.speed_mult = 4; // ps->rbs[0].move.braking_coef = 0.025f; // ps->rbs[0].move.vel = (cl_float3){{0, 0, 0}}; // ps->rbs[0].move.raw_vel = (cl_float3){{0, 0, 0}}; // // ps->rbs[0].rot.speed = 100000; // ps->rbs[0].rot.braking_coef = .04f; // ps->rbs[0].rot.vel = (cl_float3){{0, 0, 0}}; // ps->rbs[0].rot.raw_vel = (cl_float3){{0, 0, 0}}; // ps->rbs[0].transform = rt_find_transform_by_id(rt->scene, 1); /* t_object *objs = rt->scene->objects; objs[0].material.luminosity = (cl_float3){{.0f, .0f, 0.f}}; objs[1].material.luminosity = (cl_float3){{.0f, .0f, 0.f}}; objs[2].material.luminosity = (cl_float3){{.0f, .0f, 0.f}}; objs[3].material.luminosity = (cl_float3){{.0f, .0f, 0.f}}; objs[4].material.luminosity = (cl_float3){{1.f, 1.f, 1.f}};*/ // // mandelbumb // ps->rbs[1].move.speed = 10000; // ps->rbs[1].move.speed_mult = 4; // ps->rbs[1].move.acc = 0.025f; // ps->rbs[1].move.vel = (cl_float3){{0, 0, 0}}; // ps->rbs[1].move.raw_vel = (cl_float3){{0, 0, 0}}; // // ps->rbs[1].rot.speed = 100000; // ps->rbs[1].rot.acc = .04f; // ps->rbs[1].rot.vel = (cl_float3){{0, 0, 1}}; // ps->rbs[1].rot.raw_vel = (cl_float3){{0, 0, 1}}; // // ps->rbs[1].transform = &rt->scenes[0].objects[0].transform; // /* ps->rbs[1].move.speed = 10000; ps->rbs[1].move.speed_mult = 4; ps->rbs[1].move.braking_coef = 0.025f; ps->rbs[1].move.vel = (cl_float3){{0, 0, 0}}; ps->rbs[1].move.raw_vel = (cl_float3){{0, 0, 0}}; ps->rbs[1].rot.speed = 100000; ps->rbs[1].rot.braking_coef = .04f; ps->rbs[1].rot.vel = (cl_float3){{1, 0, 1}}; ps->rbs[1].rot.raw_vel = (cl_float3){{1, 0, 1}}; ps->rbs[1].transform = rt_find_transform_by_id(rt->scene, 2); ps->rbs[2].move.speed = 10000; ps->rbs[2].move.speed_mult = 4; ps->rbs[2].move.braking_coef = 0.025f; ps->rbs[2].move.vel = (cl_float3){{0, 0, 0}}; ps->rbs[2].move.raw_vel = (cl_float3){{0, 0, 0}}; ps->rbs[2].rot.speed = 150000; ps->rbs[2].rot.braking_coef = .04f; ps->rbs[2].rot.vel = (cl_float3){{1, 0, 1}}; ps->rbs[2].rot.raw_vel = (cl_float3){{0, 1, 1}}; ps->rbs[2].transform = rt_find_transform_by_id(rt->scene, 3); ps->rbs[3].move.speed = 10000; ps->rbs[3].move.speed_mult = 4; ps->rbs[3].move.braking_coef = 0.025f; ps->rbs[3].move.vel = (cl_float3){{0, 0, 0}}; ps->rbs[3].move.raw_vel = (cl_float3){{0, 0, 0}}; ps->rbs[3].rot.speed = 200000; ps->rbs[3].rot.braking_coef = .04f; ps->rbs[3].rot.vel = (cl_float3){{1, 0, 1}}; ps->rbs[3].rot.raw_vel = (cl_float3){{1, 1, 1}}; ps->rbs[3].transform = rt_find_transform_by_id(rt->scene, 4); ps->rbs[4].move.speed = 100000; ps->rbs[4].move.speed_mult = 4; ps->rbs[4].move.braking_coef = 0.025f; ps->rbs[4].move.vel = (cl_float3){{0, 0, 0}}; ps->rbs[4].move.raw_vel = (cl_float3){{0, 0, 0}}; ps->rbs[4].rot.speed = 200000; ps->rbs[4].rot.braking_coef = .04f; ps->rbs[4].rot.vel = (cl_float3){{1, 1, 1}}; ps->rbs[4].rot.raw_vel = (cl_float3){{1, 1, 1}}; ps->rbs[4].transform = rt_find_transform_by_id(rt->scene, 5);*/ system_setup(&ps->system, "physics", &ps_func, 5); ps->change_indicator = 1; system_start(&ps->system); /// INPUT SYSTEM START !!!!!!!!!!!!!!!!!!!!!!!!! t_input_system *is = ft_memalloc(sizeof(t_input_system)); is->system.parent = is; is->state = ui->state; is->active = vec_at(&ps->rbs, 0); system_setup(&is->system, "input", is_func, 3); system_start(&is->system); rt->systems_count = 2; rt->systems = ft_memalloc(sizeof(t_system *) * rt->systems_count); rt->systems[0] = &(is->system); rt->systems[1] = &(ps->system); ((t_object *)rt->scene->objects->storage)->material.luminosity.x = 0.0f; ((t_object *)rt->scene->objects->storage)->material.luminosity.y = 0.0f; ((t_object *)rt->scene->objects->storage)->material.luminosity.z = 0.0f; ui_main_run_program(ui); return 0; }
dolovnyak/ray-marching-render
libui/src/ui_el/ui_el_event_drag.c
<filename>libui/src/ui_el/ui_el_event_drag.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ui_el_drag.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: edraugr- <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/04/25 20:15:41 by sbednar #+# #+# */ /* Updated: 2019/07/13 09:30:24 by sbecker ### ########.fr */ /* */ /* ************************************************************************** */ #include "libui.h" int ui_el_event_drag(t_ui_main *m, void *a) { t_ui_el *el; int x; int y; el = (t_ui_el *)a; x = m->ptr_pos.x - el->ptr_rel_pos.x; y = m->ptr_pos.y - el->ptr_rel_pos.y; if (x < el->parent->rect.x || y < el->parent->rect.y || x + el->rect.w > el->parent->rect.x + el->parent->rect.w || y + el->rect.h > el->parent->rect.y + el->parent->rect.h) return (1); ui_el_set_new_pos(el, 0, PIXEL, (t_fvec2){x, y}); return (1); } int ui_el_event_hor_slider_drag(t_ui_main *m, void *a) { t_ui_el *el; int x; int y; el = (t_ui_el *)a; x = m->ptr_pos.x - el->ptr_rel_pos.x; y = el->rect.y; if (x < el->parent->rect.x || x + el->rect.w > el->parent->rect.x + el->parent->rect.w) return (1); ui_el_set_new_pos(el, 0, ABS | PIXEL, (t_fvec2){x, y}); return (1); }
dolovnyak/ray-marching-render
libui/src/ui_jtoc/ui_jtoc_el_get_and_setup_json.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ui_jtoc_el_get_and_setup_json.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: sbecker <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/07/12 06:44:19 by sbecker #+# #+# */ /* Updated: 2019/07/15 15:24:36 by sbecker ### ########.fr */ /* */ /* ************************************************************************** */ #include "libui.h" t_ui_event *ui_jtoc_win_from_json_get_event_by_name(t_ui_win *w, const char *n) { int hash; t_ui_event *res; hash = ft_strhash(n); res = NULL; res = (hash == ft_strhash("onPointerMoved") ? w->events->on_pointer_moved : res); res = (hash == ft_strhash("onPointerLeftButtonPressed") ? w->events->on_pointer_left_button_pressed : res); res = (hash == ft_strhash("onPointerLeftButtonReleased") ? w->events->on_pointer_left_button_released : res); res = (hash == ft_strhash("onPointerRightButtonPressed") ? w->events->on_pointer_right_button_pressed : res); res = (hash == ft_strhash("onPointerRightButtonReleased") ? w->events->on_pointer_right_button_released : res); res = (hash == ft_strhash("onScrollUp") ? w->events->on_scroll_up : res); res = (hash == ft_strhash("onScrollDown") ? w->events->on_scroll_down : res); res = (hash == ft_strhash("onFocusGained") ? w->events->on_focus_gained : res); res = (hash == ft_strhash("onFocusLost") ? w->events->on_focus_lost : res); res = (hash == ft_strhash("onResize") ? w->events->on_resize : res); res = (hash == ft_strhash("onClose") ? w->events->on_close : res); res = (hash == ft_strhash("onMoved") ? w->events->on_moved : res); return (res); } int ui_jtoc_get_el_param_from_string(const char *str) { int hash; int i; hash = ft_strhash(str); i = 0; i |= (hash == ft_strhash("EL_IGNOR_RAYCAST") ? EL_IGNOR_RAYCAST : 0); i |= (hash == ft_strhash("EL_IS_HIDDEN") ? EL_IS_HIDDEN : 0); i |= (hash == ft_strhash("EL_IS_SCROLLABLE") ? EL_IS_SCROLLABLE : 0); i |= (hash == ft_strhash("EL_IS_DEPENDENT") ? EL_IS_DEPENDENT : 0); i |= (hash == ft_strhash("EL_IS_ICON") ? EL_IS_ICON : 0); return (i); } int ui_jtoc_get_pos_size(const char *str) { int hash; int i; hash = ft_strhash(str); i = 0; i |= (hash == ft_strhash("ABS") ? ABS : 0); i |= (hash == ft_strhash("PIXEL") ? PIXEL : 0); return (i); } int ui_jtoc_el_setup_by_type(t_ui_el *e, t_jnode *n) { int h; t_jnode *tmp; ui_el_setup_default(e); if (!(tmp = jtoc_node_get_by_path(n, "type"))) return (FUNCTION_SUCCESS); tmp = tmp->down; while (tmp) { if (tmp->type != string) ui_sdl_deinit(228); h = ft_strhash(jtoc_get_string(tmp)); (h == ft_strhash("DRAGGABLE") ? ui_el_setup_default_draggable(e) : 0); (h == ft_strhash("RESIZABLE") ? ui_el_setup_default_resizable(e) : 0); (h == ft_strhash("SCROLL_MENU_ELEM") ? ui_el_setup_default_scroll_menu_elem(e) : 0); (h == ft_strhash("SCROLL_MENU") ? ui_el_setup_default_scroll_menu(e) : 0); (h == ft_strhash("HORIZONTAL_DRAGGABLE") ? ui_el_setup_horizontal_draggable(e) : 0); (h == ft_strhash("MENU_RESIZABLE") ? ui_el_setup_menu_resizable(e) : 0); (h == ft_strhash("RADIO") ? ui_el_setup_radio(e) : 0); tmp = tmp->right; } return (FUNCTION_SUCCESS); } int ui_jtoc_get_win_param_from_string(const char *str) { int i; i = 0; i |= ((ft_strcmp(str, "WIN_RESIZABLE") == 0) ? WIN_RESIZABLE : 0); return (i); }
dolovnyak/ray-marching-render
src/rt_find_by_id.c
<filename>src/rt_find_by_id.c<gh_stars>1-10 #include "rt.h" t_transform *rt_find_transform_by_id(t_scene *scene, cl_uint id) { t_transform *res; cl_uint i; if (scene->camera.transform.id == id) return (&scene->camera.transform); i = -1; while (++i < scene->objects->size) { res = &((t_object *)vec_at(scene->objects, i))->transform; if (res->id == id) return (res); } i = -1; while (++i < scene->lights->size) { res = &((t_light *)vec_at(scene->lights, i))->transform; if (res->id == id) return (res); } return (NULL); } int rt_find_object_by_id_in_array(t_vec *objects, cl_uint id) { t_object *res; cl_uint i; i = -1; while (++i < objects->size) { res = (t_object *)vec_at(objects, i); if (res->transform.id == id) return (i); } return (FUNCTION_FAILURE); } t_object *rt_find_object_by_id(t_vec *objects, cl_uint id) { t_object *res; cl_uint i; i = -1; while (++i < objects->size) { res = (t_object *)vec_at(objects, i); if (res->transform.id == id) return (res); } return (NULL); } t_light *rt_find_light_by_id(t_vec *lights, cl_uint id) { t_light *res; cl_uint i; i = -1; while (++i < lights->size) { res = (t_light *)vec_at(lights, i); if (res->transform.id == id) return (res); } return (NULL); }
dolovnyak/ray-marching-render
src/interface/uix_init.c
<filename>src/interface/uix_init.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* uix_init.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: edraugr- <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/09/28 17:58:14 by edraugr- #+# #+# */ /* Updated: 2019/09/28 17:58:19 by edraugr- ### ########.fr */ /* */ /* ************************************************************************** */ #include "interface.h" static void setup_el_data(t_ui_main *ui) { t_ui_win *uix_w; uix_w = ui_main_find_window_by_id(ui, 1); ui_win_find_el_by_id(uix_w, 20)->data = (void *)ACTIVE_MENU; } void rt_uix_interface_setup(t_ui_main *ui, const char *json_path) { ui_main_fill_default_functions(ui); rt_uix_fill_default_images(ui); rt_uix_add_functions(ui); ui_main_fill_default_fonts(ui); ui_jtoc_main_from_json(ui, json_path); setup_el_data(ui); } void rt_uix_scene_setup(t_ui_main *ui) { t_ui_el *obj_menu; obj_menu = ui_win_find_el_by_id(ui_main_find_window_by_id(ui, 1), 52); fill_scene(ui, obj_menu); }
dolovnyak/ray-marching-render
libui/src/ui_main/ui_main_handle_keyboard_event.c
<filename>libui/src/ui_main/ui_main_handle_keyboard_event.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ui_main_handle_keyboard_event.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: sbecker <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/04/04 07:49:09 by sbednar #+# #+# */ /* Updated: 2019/07/15 15:05:05 by sbecker ### ########.fr */ /* */ /* ************************************************************************** */ #include "libui.h" void ui_main_handle_keyboard_event(t_ui_main *m) { t_ui_win *win; t_ui_event *event; if ((win = ui_main_find_window_by_sdl_id(m, m->sdl_event->window.windowID)) == NULL) return ; event = NULL; if (m->sdl_event->window.type == SDL_KEYDOWN) { if (win->events->on_key_down[0]) ui_event_invoke(win->events->on_key_down[0], m, win); m->cur_keycode = m->sdl_event->key.keysym.scancode; if (m->cur_keycode == 225) m->is_upper = 1; event = win->events->on_key_down[m->sdl_event->key.keysym.scancode]; } else if (m->sdl_event->window.type == SDL_KEYUP) { if (win->events->on_key_up[0]) ui_event_invoke(win->events->on_key_up[0], m, win); if (m->sdl_event->key.keysym.scancode == 225) m->is_upper = 0; } if (event != NULL) { SDL_LockMutex(m->mutex); ui_event_invoke(event, m, win); SDL_UnlockMutex(m->mutex); } }
dolovnyak/ray-marching-render
libui/src/ui_event/ui_event_destroy.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ui_event_destroy.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: sbecker <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/07/09 21:27:39 by sbednar #+# #+# */ /* Updated: 2019/07/15 15:02:19 by sbecker ### ########.fr */ /* */ /* ************************************************************************** */ #include "libui.h" void ui_event_destroy(t_ui_event *e) { t_list *p; t_list *l; l = e->events; p = l; while (l) { free(l->content); l = l->next; p->next = NULL; free(p); p = l; } free(e); } void ui_event_win_events_destroy(t_ui_win_events *we) { int i; ui_event_destroy(we->on_pointer_moved); ui_event_destroy(we->on_pointer_enter); ui_event_destroy(we->on_pointer_exit); ui_event_destroy(we->on_pointer_left_button_pressed); ui_event_destroy(we->on_pointer_left_button_released); ui_event_destroy(we->on_pointer_right_button_pressed); ui_event_destroy(we->on_pointer_right_button_released); ui_event_destroy(we->on_scroll_up); ui_event_destroy(we->on_scroll_down); ui_event_destroy(we->on_focus_gained); ui_event_destroy(we->on_focus_lost); ui_event_destroy(we->on_resize); ui_event_destroy(we->on_close); ui_event_destroy(we->on_moved); i = KEYS_COUNT; while (--i >= 0) { ui_event_destroy(we->on_key_down[i]); ui_event_destroy(we->on_key_up[i]); } free(we->on_key_down); free(we->on_key_up); free(we); } void ui_event_el_events_destroy(t_ui_el_events *ee) { ui_event_destroy(ee->on_pointer_enter); ui_event_destroy(ee->on_pointer_stay); ui_event_destroy(ee->on_pointer_exit); ui_event_destroy(ee->on_pointer_left_button_pressed); ui_event_destroy(ee->on_pointer_left_button_hold); ui_event_destroy(ee->on_pointer_left_button_released); ui_event_destroy(ee->on_pointer_right_button_pressed); ui_event_destroy(ee->on_pointer_right_button_hold); ui_event_destroy(ee->on_pointer_right_button_released); ui_event_destroy(ee->on_scroll_up); ui_event_destroy(ee->on_scroll_down); ui_event_destroy(ee->on_render); ui_event_destroy(ee->on_resize); free(ee); }
dolovnyak/ray-marching-render
libui/src/ui_el/ui_el_remove_texture_by_id.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ui_el_remove_texture_by_id.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: edraugr- <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/05/23 05:38:20 by sbednar #+# #+# */ /* Updated: 2019/07/15 01:17:03 by edraugr- ### ########.fr */ /* */ /* ************************************************************************** */ #include "libui.h" void ui_el_remove_texture_by_id(t_ui_el *el, const char *id) { t_list *p; t_list *l; t_list *t; l = el->sdl_textures; p = NULL; while (l) { if ((int)l->content_size == ft_strhash(id)) { t = l; if (p) p->next = l->next; else el->sdl_textures = l->next; SDL_DestroyTexture((SDL_Texture *)t->content); free(t); return ; } p = l; l = l->next; } }
dolovnyak/ray-marching-render
src/rt_jtoc/rt_jtoc_get_transform.c
<reponame>dolovnyak/ray-marching-render #include "rt.h" #include "rt_jtoc.h" static void rt_jtoc_setup_transform_default(t_transform *t) { t->right = (cl_float3){{1, 0, 0}}; t->up = (cl_float3){{0, 1, 0}}; t->forward = (cl_float3){{0, 0, 1}}; } static void rt_jtoc_rotate_transform(t_transform *t, float x, float y, float z) { if (fabs(x) >= 0.001f) rotate_transform_around_axis(t, (cl_float3){{1, 0, 0}}, x); if (fabs(y) >= 0.001f) rotate_transform_around_axis(t, (cl_float3){{0, 1, 0}}, y); if (fabs(z) >= 0.001f) rotate_transform_around_axis(t, (cl_float3){{0, 0, 1}}, z); } static int rt_jtoc_get_eulers(t_transform *t, t_jnode *n) { t_jnode *tmp; float x; float y; float z; if (!(tmp = jtoc_node_get_by_path(n, "x")) || tmp->type != fractional) return (rt_jtoc_sdl_log_error("EULERS.X TYPE ERROR OR MISSING", -1)); x = jtoc_get_float(tmp); if (!(tmp = jtoc_node_get_by_path(n, "y")) || tmp->type != fractional) return (rt_jtoc_sdl_log_error("EULERS.Y TYPE ERROR OR MISSING", -1)); y = jtoc_get_float(tmp); if (!(tmp = jtoc_node_get_by_path(n, "z")) || tmp->type != fractional) return (rt_jtoc_sdl_log_error("EULERS.Z TYPE ERROR OR MISSING", -1)); z = jtoc_get_float(tmp); rt_jtoc_rotate_transform(t, x, y, z); return (FUNCTION_SUCCESS); } int rt_jtoc_get_transform(t_transform *transform, t_jnode *n) { t_jnode *tmp; ft_bzero(transform, sizeof(t_transform)); if (!(n = jtoc_node_get_by_path(n, "transform")) || n->type != object) return (rt_jtoc_sdl_log_error("TRANSFORM TYPE ERROR OR TRANSFORM MISSING", -1)); if (!(tmp = jtoc_node_get_by_path(n, "pos")) || tmp->type != object) return (rt_jtoc_sdl_log_error("POS TYPE ERROR OR MISSING", -1)); if (rt_jtoc_get_float3(&(transform->pos), tmp)) return (rt_jtoc_sdl_log_error("POS ERROR", -1)); rt_jtoc_setup_transform_default(transform); if (!(tmp = jtoc_node_get_by_path(n, "eulers")) || tmp->type != object) return (rt_jtoc_sdl_log_error("EULERS TYPE ERROR OR MISSING", -1)); if (rt_jtoc_get_eulers(transform, tmp)) return (rt_jtoc_sdl_log_error("EULERS ERROR", -1)); return (FUNCTION_SUCCESS); }
LeandreBl/threadpool
src/reserve.c
<gh_stars>1-10 #include "lthread_pool.h" int lthread_pool_reserve(lthread_pool_t *handle, size_t count) { for (size_t size = clist_size(handle->threads); size < count; ++size) { clist_emplace_back(handle->threads, lthread_destroy, lthread_create, NULL, NULL); if (size + 1 != clist_size(handle->threads)) return -1; } return 0; }
LeandreBl/threadpool
include/lthread.h
#ifndef _LTHREAD_H_ #define _LTHREAD_H_ #define _GNU_SOURCE #include <pthread.h> #include <unistd.h> #include <stdbool.h> #include <semaphore.h> #include <stdio.h> struct lthread_s; typedef void (*lthread_function_t)(const struct lthread_s *thread); typedef struct lthread_s { pthread_t thread; sem_t sem_sync; sem_t sem_wait; lthread_function_t call; void *userdata; bool is_running : 1; bool is_canceled : 1; } lthread_t; int lthread_create(lthread_t *thread, lthread_function_t function, void *userdata); void lthread_set_function(lthread_t *thread, lthread_function_t function, void *userdata); int lthread_launch(lthread_t *thread, useconds_t delay); int lthread_wait(lthread_t *thread, long timeout); void lthread_destroy(lthread_t *thread); #endif /* !_LTHREAD_H_ */
LeandreBl/threadpool
src/launch.c
<reponame>LeandreBl/threadpool #include <unistd.h> #include "lthread.h" int lthread_launch(lthread_t *thread, useconds_t delay) { if (thread->is_running == true) return (-1); if (delay) usleep(delay); if (sem_post(&thread->sem_sync) == -1) return (-1); thread->is_running = true; return (0); }
LeandreBl/threadpool
src/wait_all.c
<gh_stars>1-10 #include "lthread_pool.h" static size_t count_running(const lthread_pool_t *pool) { size_t count = 0; clist_foreach(thread, pool->threads) { if (thread->is_running == true) ++count; } return count; } int lthread_pool_wait_all(lthread_pool_t *handle, lthread_pool_callback_t callback, void *userdata, long timeout) { size_t count = count_running(handle); long t = (timeout < 0) ? timeout : (timeout / (ssize_t)count); clist_foreach(thread, handle->threads) { if (thread->is_running) { if (lthread_wait(thread, t) == -1) return -1; if (callback != NULL) callback(handle, thread, userdata); } } return 0; }
LeandreBl/threadpool
src/set_function.c
<reponame>LeandreBl/threadpool<filename>src/set_function.c #include "lthread.h" void lthread_set_function(lthread_t *thread, lthread_function_t function, void *userdata) { thread->call = function; thread->userdata = userdata; }
LeandreBl/threadpool
src/pool.c
<gh_stars>1-10 #include <string.h> #include "lthread_pool.h" int lthread_pool_create(lthread_pool_t *handle, size_t count) { memset(handle, 0, sizeof(*handle)); if (lthread_pool_reserve(handle, count) == -1) goto error; return 0; error: lthread_pool_destroy(handle); return -1; } void lthread_pool_destroy(lthread_pool_t *handle) { clist_destroy(handle->threads); }
LeandreBl/threadpool
src/thread.c
<reponame>LeandreBl/threadpool #include <errno.h> #include <string.h> #include "lthread.h" static int wake_waiters(lthread_t *thread) { int sval; if (sem_getvalue(&thread->sem_wait, &sval) == -1 || (sval == 0 && sem_post(&thread->sem_wait) == -1)) return (-1); return (0); } static void *caller_wrapper(lthread_t *thread) { thread->is_canceled = false; while (thread->is_canceled == false) { if (sem_wait(&thread->sem_sync) != 0) { fprintf(stderr, "Error: lthread: semaphore: %s\n", strerror(errno)); break; } if (thread->is_canceled == true) break; thread->call(thread); if (wake_waiters(thread) == -1) break; thread->is_running = false; } return NULL; } int lthread_create(lthread_t *thread, lthread_function_t function, void *userdata) { thread->call = function; thread->userdata = userdata; thread->is_running = false; if (sem_init(&thread->sem_sync, 0, 0) == -1 || sem_init(&thread->sem_wait, 0, 0) == -1) return (-1); if (pthread_create(&thread->thread, NULL, (void *(*)(void *)) & caller_wrapper, thread) == -1) return (-1); return (0); } void lthread_destroy(lthread_t *thread) { int ret; thread->is_canceled = true; sem_post(&thread->sem_sync); ret = pthread_join(thread->thread, NULL); if (ret < 0) fprintf(stderr, "Error: lthread: pthread_join: %s\n", strerror(-ret)); sem_destroy(&thread->sem_sync); sem_destroy(&thread->sem_wait); }
LeandreBl/threadpool
include/lthread_pool.h
#ifndef _LTHREAD_POOL_H_ #define _LTHREAD_POOL_H_ #include <lthread.h> #include <clist.h> typedef struct lblthread_pool_s { clist(lthread_t) * threads; } lthread_pool_t; typedef void (*lthread_pool_callback_t)(const lthread_pool_t *handle, const lthread_t *thread, void *userdata); int lthread_pool_create(lthread_pool_t *handle, size_t count); int lthread_pool_reserve(lthread_pool_t *handle, size_t count); int lthread_pool_run(lthread_pool_t *handle, lthread_function_t function, void *userdata); int lthread_pool_wait_all(lthread_pool_t *handle, lthread_pool_callback_t callback, void *userdata, long timeout); void lthread_pool_destroy(lthread_pool_t *handle); #endif /* !_LTHREAD_POOL_H_ */
LeandreBl/threadpool
src/run.c
#include <stdlib.h> #include "lthread_pool.h" static int set_and_start(lthread_t *thread, lthread_function_t function, void *data) { lthread_set_function(thread, function, data); if (lthread_launch(thread, 0) == -1) return -1; return 0; } int lthread_pool_run(lthread_pool_t *handle, lthread_function_t function, void *data) { size_t size = clist_size(handle->threads); clist_foreach(thread, handle->threads) { if (thread->is_running == false) { if (set_and_start(thread, function, data) == -1) return -1; return 0; } } if (lthread_pool_reserve(handle, (size == 0) ? 1 : size * 2) == -1) return -1; return lthread_pool_run(handle, function, data); }
LeandreBl/threadpool
src/wait.c
#include "lthread.h" int lthread_wait(lthread_t *thread, long ms_timeout) { struct timespec ts = { ms_timeout / 1000, (ms_timeout - ms_timeout / 1000) * 1000000, }; if (thread->is_running == false) return (-1); if ((ms_timeout < 0 && sem_wait(&thread->sem_wait) == -1) || (ms_timeout > 0 && sem_timedwait(&thread->sem_wait, &ts) == -1)) return (-1); return (0); }
LeandreBl/threadpool
tests/thread_tests.c
<reponame>LeandreBl/threadpool<gh_stars>1-10 #include <criterion/criterion.h> #include "lthread.h" void func(const lthread_t *thread) { int *i = thread->userdata; *i = 1; } void funcf(const lthread_t *thread) { int *i = thread->userdata; *i = 2; } Test(create, lthread) { lthread_t thread; int val = 0; cr_assert(lthread_create(&thread, &func, &val) == 0); lthread_launch(&thread, 0); lthread_wait(&thread, -1); cr_assert(val == 1); lthread_destroy(&thread); } Test(set_function, lthread) { lthread_t thread; int val = 0; cr_assert(lthread_create(&thread, &func, &val) == 0); cr_assert(lthread_launch(&thread, 0) == 0); lthread_wait(&thread, -1); cr_assert(val == 1); lthread_set_function(&thread, &funcf, &val); cr_assert(lthread_launch(&thread, 0) == 0); lthread_wait(&thread, -1); cr_assert(val == 2); lthread_destroy(&thread); }
aaaaaaudrey/sys-clk
src/clock_table.h
<gh_stars>0 /* * -------------------------------------------------------------------------- * "THE BEER-WARE LICENSE" (Revision 42): * <<EMAIL>>, <<EMAIL>>, <<EMAIL>> * wrote this file. As long as you retain this notice you can do whatever you * want with this stuff. If you meet any of us some day, and you think this * stuff is worth it, you can buy us a beer in return. - The sys-clk authors * -------------------------------------------------------------------------- */ static std::uint32_t g_mem_clocks[] = { 1600000000, 1331200000, 1065600000, 800000000, 665600000, }; static size_t g_mem_clock_count = sizeof(g_mem_clocks) / sizeof(g_mem_clocks[0]); static std::uint32_t g_cpu_clocks[] = { 1785000000, 1683000000, 1581000000, 1428000000, 1326000000, 1224000000, 1122000000, 1020000000, 918000000, 816000000, 714000000, 612000000, }; static size_t g_cpu_clock_count = sizeof(g_cpu_clocks) / sizeof(g_cpu_clocks[0]); static std::uint32_t g_gpu_clocks[] = { 921600000, 844800000, 768000000, 691200000, 614400000, 537600000, 460800000, 384000000, 307200000, 230400000, 153600000, 76800000, }; static std::uint32_t g_gpu_handheld_max = 460800000; static std::uint32_t g_gpu_unofficial_charger_max = 768000000; static size_t g_gpu_clock_count = sizeof(g_gpu_clocks) / sizeof(g_gpu_clocks[0]);
aaaaaaudrey/sys-clk
src/clock_manager.h
<filename>src/clock_manager.h /* * -------------------------------------------------------------------------- * "THE BEER-WARE LICENSE" (Revision 42): * <<EMAIL>>, <<EMAIL>>, <<EMAIL>> * wrote this file. As long as you retain this notice you can do whatever you * want with this stuff. If you meet any of us some day, and you think this * stuff is worth it, you can buy us a beer in return. - The sys-clk authors * -------------------------------------------------------------------------- */ #pragma once #include "config.h" #include "clocks.h" class ClockManager { public: ClockManager(); virtual ~ClockManager(); void Tick(); protected: bool RefreshContext(); Config *config; ClockProfile profile; std::uint64_t applicationTid; std::uint32_t *freqs; ChargerType chargerType; };
aaaaaaudrey/sys-clk
src/clocks.h
/* * -------------------------------------------------------------------------- * "THE BEER-WARE LICENSE" (Revision 42): * <<EMAIL>>, <<EMAIL>>, <<EMAIL>> * wrote this file. As long as you retain this notice you can do whatever you * want with this stuff. If you meet any of us some day, and you think this * stuff is worth it, you can buy us a beer in return. - The sys-clk authors * -------------------------------------------------------------------------- */ #pragma once #include <string> #include <switch.h> typedef enum { ClockProfile_Handheld = 0, ClockProfile_HandheldCharging, ClockProfile_HandheldChargingUSB, ClockProfile_HandheldChargingOfficial, ClockProfile_Docked, ClockProfile_EnumMax } ClockProfile; typedef enum { ClockModule_CPU = 0, ClockModule_GPU, ClockModule_MEM, ClockModule_EnumMax } ClockModule; class Clocks { public: static void Exit(); static void Initialize(); static std::uint32_t ResetToStock(); static ClockProfile GetCurrentProfile(); static std::uint32_t GetCurrentHz(ClockModule module); static void SetHz(ClockModule module, std::uint32_t hz); static const char* GetProfileName(ClockProfile profile, bool pretty); static const char* GetModuleName(ClockModule module, bool pretty); static std::uint32_t GetNearestHz(ClockModule module, ClockProfile profile, std::uint32_t inHz); protected: static PcvModule GetPcvModule(ClockModule clockmodule); static PcvModuleId GetPcvModuleId(ClockModule clockmodule); static std::uint32_t GetNearestHz(ClockModule module, std::uint32_t inHz); static void GetList(ClockModule module, std::uint32_t **outClocks, size_t *outClockCount); static std::uint32_t GetMaxAllowedHz(ClockModule module, ClockProfile profile); };
aaaaaaudrey/sys-clk
src/config.h
<gh_stars>0 /* * -------------------------------------------------------------------------- * "THE BEER-WARE LICENSE" (Revision 42): * <<EMAIL>>, <<EMAIL>>, <<EMAIL>> * wrote this file. As long as you retain this notice you can do whatever you * want with this stuff. If you meet any of us some day, and you think this * stuff is worth it, you can buy us a beer in return. - The sys-clk authors * -------------------------------------------------------------------------- */ #pragma once #include <ctime> #include <map> #include <initializer_list> #include <switch.h> #include <minIni.h> #include "clocks.h" class Config { public: Config(std::string path); virtual ~Config(); static Config *CreateDefault(); void Load(); void Close(); bool Refresh(); bool HasLoaded(); std::string LastError(); std::uint32_t GetClockHz(std::uint64_t tid, ClockModule module, ClockProfile profile); protected: time_t CheckModificationTime(); std::uint32_t FindClockHzFromProfiles(std::uint64_t tid, ClockModule module, std::initializer_list<ClockProfile> profiles); static int BrowseIniFunc(const char* section, const char* key, const char* value, void *userdata); std::map<std::tuple<std::uint64_t, ClockProfile, ClockModule>, std::uint32_t> profileMhzMap; minIni *ini; std::string path; time_t mtime; };
aaaaaaudrey/sys-clk
src/ipc/apm_ext.c
/* * -------------------------------------------------------------------------- * "THE BEER-WARE LICENSE" (Revision 42): * <<EMAIL>>, <<EMAIL>>, <<EMAIL>> * wrote this file. As long as you retain this notice you can do whatever you * want with this stuff. If you meet any of us some day, and you think this * stuff is worth it, you can buy us a beer in return. - The sys-clk authors * -------------------------------------------------------------------------- */ #include "apm_ext.h" static Service g_apmSrv; static Service g_apmSysSrv; static u64 g_refCnt; Result apmExtInitialize(void) { atomicIncrement64(&g_refCnt); if (serviceIsActive(&g_apmSrv)) { return 0; } Result rc = 0; rc = smGetService(&g_apmSrv, "apm"); if(R_SUCCEEDED(rc)) { rc = smGetService(&g_apmSysSrv, "apm:sys"); } if (R_FAILED(rc)) { apmExtExit(); } return rc; } void apmExtExit(void) { if (atomicDecrement64(&g_refCnt) == 0) { serviceClose(&g_apmSrv); serviceClose(&g_apmSysSrv); } } Result apmExtGetPerformanceMode(u32 *out_mode) { IpcCommand c; ipcInitialize(&c); struct { u64 magic; u64 cmd_id; } *raw; raw = ipcPrepareHeader(&c, sizeof(*raw)); raw->magic = SFCI_MAGIC; raw->cmd_id = 1; Result rc = serviceIpcDispatch(&g_apmSrv); if (R_SUCCEEDED(rc)) { IpcParsedCommand r; ipcParse(&r); struct { u64 magic; u64 result; u32 mode; } *resp = r.Raw; rc = resp->result; if (R_SUCCEEDED(rc)) { *out_mode = resp->mode; } } return rc; } Result apmExtSysRequestPerformanceMode(u32 mode) { IpcCommand c; ipcInitialize(&c); struct { u64 magic; u64 cmd_id; u32 mode; } *raw; raw = ipcPrepareHeader(&c, sizeof(*raw)); raw->magic = SFCI_MAGIC; raw->cmd_id = 0; raw->mode = mode; Result rc = serviceIpcDispatch(&g_apmSysSrv); if (R_SUCCEEDED(rc)) { IpcParsedCommand r; ipcParse(&r); struct { u64 magic; u64 result; } *resp = r.Raw; rc = resp->result; } return rc; }
Alley815/PowerToys
src/modules/powerrename/lib/Helpers.h
#pragma once #include <common.h> #include <lib/PowerRenameInterfaces.h> HRESULT GetTrimmedFileName(_Out_ PWSTR result, UINT cchMax, _In_ PCWSTR source); HRESULT GetTransformedFileName(_Out_ PWSTR result, UINT cchMax, _In_ PCWSTR source, DWORD flags); HRESULT GetDatedFileName(_Out_ PWSTR result, UINT cchMax, _In_ PCWSTR source, SYSTEMTIME fileTime); bool isFileTimeUsed(_In_ PCWSTR source); bool DataObjectContainsRenamableItem(_In_ IUnknown* dataSource); HRESULT EnumerateDataObject(_In_ IUnknown* pdo, _In_ IPowerRenameManager* psrm); BOOL GetEnumeratedFileName( __out_ecount(cchMax) PWSTR pszUniqueName, UINT cchMax, __in PCWSTR pszTemplate, __in_opt PCWSTR pszDir, unsigned long ulMinLong, __inout unsigned long* pulNumUsed);
cms-codes/procfs-System-Monitor
include/processor.h
#ifndef PROCESSOR_H #define PROCESSOR_H #include <ctime> #include <vector> /********* Processor class ******* * Abstracts the system CPUs, collecting and calculating processor usage. */ struct CpuNData { int idle; int active; }; class Processor { public: std::vector<float> Utilization(); void UpdateData(); void UpdateResult(); int NumCpus(); private: // Each vector represents CPU n, with a nested vector of CPU samples. std::vector<std::vector<CpuNData>> cpu_data_; // Each float represents the percentage of active time for CPU n. std::vector<float> cpu_result_; void AddCpuSample(int cpu_id, int idle, int active); }; #endif
cms-codes/procfs-System-Monitor
include/system.h
<filename>include/system.h #ifndef SYSTEM_H #define SYSTEM_H #include <string> #include <vector> #include "process.h" #include "processor.h" /********* System class ******* * Unifier that provides interfacing to the system monitor modules. */ class System { public: Processor& Cpu(); std::vector<Process>& Processes(); float MemoryUtilization(); long UpTime(); int TotalProcesses(); int RunningProcesses(); std::string Kernel(); std::string OperatingSystem(); private: Processor cpu_ = {}; std::vector<Process> processes_ = {}; std::vector<int> DumpPids(); std::vector<int> NoPartner(const std::vector<int> partner_a, const std::vector<int> partner_b); void AddProcs(const std::vector<int> pid_list); void PruneProcs(const std::vector<int> dead_pids); void SortProcsByCpu(); }; #endif
cms-codes/procfs-System-Monitor
include/process.h
#ifndef PROCESS_H #define PROCESS_H #include <ctime> #include <string> #include <vector> /********* Process class ******* * Initializes a queue structure, preparing it for usage. */ class Process { public: Process(int pid); int Pid(); std::string User(); std::string Command(); float CpuUtilization() const; std::string CpuPretty(int precision) const; std::string Ram(); long UpTime(); bool operator<(Process const &that) const; bool operator>(Process const &that) const; void UpdateCpuData(); private: int pid_{0}; std::string user_ = ""; std::string command_ = ""; long start_time_{0}; void AddValue(int jiffy_type, long value); std::vector<std::vector<long>> cpu_data_ = {}; float cpu_util_{0}; }; enum JiffyData { kJiffiesSys_ = 0, kJiffiesProc_ }; #endif
krdarrah/trigBoardV8_BaseFirmware
includes.h
#ifndef INCLUDES_H #define INCLUDES_H /* * Versions: * Arduino IDE v1.8.15 * ESP32 v1.06 * PubSubClient Library v2.8.0 * Arduino Json Library v6.18.0 * UniversalTelegramBot v1.3.0 */ //libraries used #include "FS.h"// for SPIFFS #include "SPIFFS.h" #include "time.h" #include <WiFi.h> #include <Wire.h>//for I2C RTC #include <WiFiClientSecure.h> //*** THESE ARE THE ONLY LIBRARIES YOU NEED TO INSTALL *** #include <PubSubClient.h>//for mqtt #include <ArduinoJson.h> #include <UniversalTelegramBot.h> //******************************************************** #include <BLEDevice.h> #include <BLEServer.h> #include <BLEUtils.h> #include <BLE2902.h> #include <ESPmDNS.h> #include <ArduinoOTA.h> //trigBoard PINS const int BatteryPin = 36;//analog Input const int LEDpin = 0;//output const int ESPlatchPin = 16;//output const int killPowerPin = 17;//output const int contactOpenedPin = 18;//input const int contactClosedPin = 19;//input const int contactStatusPin = 23;//input const int wakeButtonPin = 27;//input const int SDApin = 21;//rtc I2C const int SCLpin = 22;//rtc I2C //globals struct Config {//full configuration file char ssid[50]; char pw[50]; int wifiTimeout; char trigName[50]; char trigSelect[10]; char triggerOpensMessage[50]; char triggerClosesMessage[50]; char buttonMessage[50]; int timerCountDown; char timerSelect[10]; char StillOpenMessage[50]; char StillClosedMessage[50]; double batteryThreshold; double batteryOffset; char pushOverEnable[3]; char pushUserKey[50]; char pushAPIKey[50]; char pushSaferEnable[3]; char pushSaferKey[50]; char iftttEnable[3]; char iftttMakerKey[50]; char udpEnable[3]; char tcpEnable[3]; char udpTargetIP[20]; char udpStaticIP[20]; char udpGatewayAddress[20]; char udpSubnetAddress[20]; char udpPrimaryDNSAddress[20]; char udpSecondaryDNSAddress[20]; char udpSSID[50]; char udpPW[50]; int udpPort; char rtcCountdownMinute[3]; char mqttEnable[3]; int mqttPort; char mqttServer[50]; char mqttTopic[50]; char mqttSecureEnable[3]; char mqttUser[50]; char mqttPW[50]; char staticIPenable[3]; char staticIP[20]; char staticGatewayAddress[20]; char staticSubnetAddress[20]; char staticPrimaryDNSAddress[20]; char staticSecondaryDNSAddress[20]; int udpBlastCount; int udptimeBetweenBlasts; char highSpeed[3]; char clkEnable[3]; int clkTimeZone; char clkAppendEnable[3]; char clkAlarmEnable[3]; int clkAlarmHour; int clkAlarmMinute; char clkUpdateNPTenable[3]; char clkAlarmMessage[50]; char clkAppendAlmEnable[3]; char telegramEnable[3]; char telegramBOT[50]; char telegramCHAT[50]; }; //bluetooth BLEServer *pServer = NULL; BLECharacteristic * pTxCharacteristic; bool deviceConnected = false; bool oldDeviceConnected = false; unsigned long bluetoothFlasherTime; uint8_t txValue = 0; #define SERVICE_UUID "a5f125c0-7cec-4334-9214-58cffb8706c0" // UART service UUID #define CHARACTERISTIC_UUID_RX "a5f125c1-7cec-4334-9214-58cffb8706c0" #define CHARACTERISTIC_UUID_TX "a5f125c2-7cec-4334-9214-58cffb8706c0" unsigned long bluetoothStatusStartTime; unsigned long bluetoothParamStartTime; bool sendParam = false; bool testPushover = false; char batCharString[5]; char pushMessage[100]; bool OTAsetup = false; const char *filename = "/config.txt"; //logic bool timerWake; bool clockWake; bool updateRTC; bool updateRTCtime; bool contactLatchClosed; bool contactLatchOpen; bool lowBattery; bool contactStatusClosed; bool buttonWasPressed; bool contactChanged = false; bool wiFiNeeded = false; Config config; //rtc char rtcTimeStamp[20]; //function prototypes // wakeup tab void checkWakeupPins(); void killPower(); void waitForButton(); void checkIfContactChanged(); // rtc tab bool rtcInit(byte timeValue, bool setNewTime); void rtcGetTime(); bool getNTPtime(); void nptUpdateTime(); void timestampAppend(); // pushover tab boolean pushOver(); // WiFi tab bool connectWiFi(); // battery tab float getBattery(); // congiguration tab void loadConfiguration(const char *filename, Config &config); void saveConfiguration(const char *filename, const Config &config); // bluetooth tab void initBluetooth(); void serviceBluetooth(); // logic tab bool pushLogic(); // udp tab void udp(); int oneIP = 0, twoIP = 0, threeIP = 0, fourIP = 0; void getFourNumbersForIP(const char *ipChar);//used also in WiFi & tcp tab //tcp tab // ifttt tab void ifttt(); //pushSafer tab struct PushSaferInput { String message; String title; String sound; String vibration; String icon; String iconcolor; String device; String url; String urlTitle; String time2live; String priority; String retry; String expire; String answer; String picture; String picture2; String picture3; }; void pushSafer(); String Pushsafer_buildString(String boundary, String name, String value); String Pushsafer_sendEvent(PushSaferInput input); // mqtt tab void mqtt(); // OTA tab void setupOTA(); void checkOTA(); #endif
wonderffee/DFDynamicProperty
DFDynamicProperty/DFDynamicProperty.h
<filename>DFDynamicProperty/DFDynamicProperty.h // // DFDynamicProperty.h // app // // Created by Pheylix on 16/4/3. // Copyright © 2016年 Hanhuo. All rights reserved. // #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> #import <objc/runtime.h> @interface DFDynamicProperty : NSObject //add NSString property + (BOOL)addStringProperty:(NSString *)propertyName ForClass:(NSString*)className; //add Object property + (BOOL)addObjectProperty:(NSString *)propertyName ForClass:(NSString*)className withPropertyClass:(NSString*)propertyClassName; + (BOOL)addCommonProperty:(NSString *)propertyName ForClass:(NSString*)className withAttri:(NSString*)strAttrParams withPropertyClass:(Class)valueClass withCustomEncodeType:(NSString*)strEncodeType; @end
wonderffee/DFDynamicProperty
Demo/DFDynamicPropertyDemo/ViewController.h
// // ViewController.h // DFDynamicPropertyDemo // // Created by Pheylix on 16/5/27. // Copyright © 2016年 wonderffee. All rights reserved. // #import <UIKit/UIKit.h> @interface ViewController : UIViewController @end
wonderffee/DFDynamicProperty
DFDynamicProperty/LcCategoryProperty/NSObject+LcInvokeAllMethod.h
<gh_stars>10-100 // // NSObject+LcInvokeAllMethod.h // LcCategoryPropertySample // // Created by jiangliancheng on 15/11/22. // Copyright © 2015年 jiangliancheng. All rights reserved. // #import <Foundation/Foundation.h> @interface NSObject (LcInvokeAllMethod) /** * 通过selector调用所有实例的方法,包括被category覆盖的方法 * @param selector 要调用方法的selector */ - (void)invokeAllInstanceMethodWithSelector:(SEL)selector; /** * 通过selector调用所有类的方法,包括被category覆盖的方法 * @param selector 方法的selector */ + (void)invokeAllClassMethodWithSelector:(SEL)selector; @end
wonderffee/DFDynamicProperty
DFDynamicProperty/LcCategoryProperty/NSObject+LcProperty.h
// // NSObject+LcProperty.h // LcCategoryPropertySample // // Created by jiangliancheng on 15/11/21. // Copyright © 2015年 jiangliancheng. All rights reserved. // #import <Foundation/Foundation.h> #import <objc/runtime.h> extern NSString *LcAddPropertyException; @interface NSObject (LcProperty) /** * 为类添加id类型的属性,objc_AssociationPolicy类型为OBJC_ASSOCIATION_RETAIN_NONATOMIC * @param name 属性的name */ + (void)addObjectProperty:(NSString *)name; /** * 为类添加id类型的属性 * @param name 属性的name * @param policy 属性的policy */ + (void)addObjectProperty:(NSString *)name associationPolicy:(objc_AssociationPolicy)policy; /** * 为类添加基础类型的属性,如:int,float,CGPoint,CGRect等 * @param name 属性的name * @param type 属性的encodingType,如int类型的属性,type为@encode(int) */ + (void)addBasicProperty:(NSString *)name encodingType:(char *)type; @end
wonderffee/DFDynamicProperty
Demo/DFDynamicPropertyDemo/Model/SampleModel.h
// // SampleModel.h // DFDynamicPropertyDemo // // Created by Pheylix on 16/5/27. // Copyright © 2016年 wonderffee. All rights reserved. // #import <Foundation/Foundation.h> @interface SampleModel : NSObject //@property (nonatomic, copy) NSString *homeTeam; //@property (nonatomic, copy) NSString *markerImage; //@property (nonatomic, copy) NSString *information; @property (nonatomic, copy) NSString *capacity; @property (nonatomic, copy) NSString *fixture; @property (nonatomic, copy) NSString *previousScore; @property (nonatomic, copy) NSString *awayTeam; @end
brianush1/origin
Origin/walker.h
#pragma once #include "ast.h" namespace origin { template<class T> class walker { public: T walk_expr(expr* expr) { if (auto error_expr = dynamic_cast<origin::error_expr*>(expr)) { return walk(error_expr); } else if (auto lambda_expr = dynamic_cast<lambda*>(expr)) { return walk(lambda_expr); } else if (auto parenthetical_expr = dynamic_cast<parenthetical*>(expr)) { return walk(parenthetical_expr); } else if (auto int_literal_expr = dynamic_cast<int_literal*>(expr)) { return walk(int_literal_expr); } else if (auto variable_expr = dynamic_cast<variable*>(expr)) { return walk(variable_expr); } else if (auto member_expr = dynamic_cast<member*>(expr)) { return walk(member_expr); } else if (auto subscript_expr = dynamic_cast<subscript*>(expr)) { return walk(subscript_expr); } else if (auto call_expr = dynamic_cast<origin::call_expr*>(expr)) { return walk(call_expr); } else if (auto bin_expr = dynamic_cast<origin::bin_expr*>(expr)) { return walk(bin_expr); } else if (auto un_expr = dynamic_cast<origin::un_expr*>(expr)) { return walk(un_expr); } else { throw std::exception(); } } T walk_stat(stat* stat) { if (auto vardecl_stat = dynamic_cast<vardecl*>(stat)) { return walk(vardecl_stat); } else if (auto expr_stat = dynamic_cast<origin::expr_stat*>(stat)) { return walk(expr_stat); } else if (auto if_stat = dynamic_cast<origin::if_stat*>(stat)) { return walk(if_stat); } else if (auto block_stat = dynamic_cast<block*>(stat)) { return walk(block_stat); } else if (auto return_stat = dynamic_cast<origin::return_stat*>(stat)) { return walk(return_stat); } else { throw std::exception(); } }; virtual T walk(vardecl* stat) = 0; virtual T walk(expr_stat* stat) = 0; virtual T walk(if_stat* stat) = 0; virtual T walk(block* stat) = 0; virtual T walk(return_stat* stat) = 0; virtual T walk(error_expr* expr) = 0; virtual T walk(lambda* expr) = 0; virtual T walk(parenthetical* expr) = 0; virtual T walk(int_literal* expr) = 0; virtual T walk(variable* expr) = 0; virtual T walk(member* expr) = 0; virtual T walk(subscript* expr) = 0; virtual T walk(call_expr* expr) = 0; virtual T walk(bin_expr* expr) = 0; virtual T walk(un_expr* expr) = 0; virtual T walk(compilation_unit* unit) = 0; }; }
brianush1/origin
Origin/type_analysis.h
#pragma once #include <unordered_map> #include "ast.h" #include "walker.h" #include "allocator.h" #include "diagnostics.h" #include "lexer.h" namespace origin { class scope { public: scope* parent; std::unordered_map<std::string, typing*> variables; scope(); scope(scope* parent); bool has(const std::string& name); typing* get(const std::string& name); void declare(const std::string& name, typing* typing); }; class type_assigner : public walker<void> { private: allocator memory; compilation_unit* unit; scope* current_scope; std::vector<diagnostic>& diagnostics; program* current_program; std::unordered_map<std::string, classdef*> classes; std::unordered_map<typing*, classdef*> generic_classes; std::unordered_map<std::string, typing*> typedefs; std::vector<typing*> current_template; public: type_assigner(std::vector<diagnostic>& diagnostics); ~type_assigner(); void downscope(); void upscope(); classdef* find_class(typing* typing); typing* patch(typing*); virtual void walk(vardecl* stat); virtual void walk(expr_stat* stat); virtual void walk(if_stat* stat); virtual void walk(block* stat); virtual void walk(return_stat* stat); virtual void walk(error_expr* expr); virtual void walk(lambda* expr); virtual void walk(parenthetical* expr); virtual void walk(int_literal* expr); virtual void walk(variable* expr); virtual void walk(member* expr); vardecl* find_overload(const std::string& name, typing* typing, const std::vector<origin::typing*>& expected_params); virtual void walk(subscript* expr); virtual void walk(call_expr* expr); virtual void walk(bin_expr* expr); virtual void walk(un_expr* expr); virtual void walk(compilation_unit* unit); }; /*class type_checker : public walker<void> { private: allocator memory; compilation_unit* unit; scope* current_scope; std::vector<diagnostic>& diagnostics; public: type_checker(std::vector<diagnostic>& diagnostics); ~type_checker(); void downscope(); void upscope(); virtual void walk(vardecl* stat); virtual void walk(expr_stat* stat); virtual void walk(block* stat); virtual void walk(return_stat* stat); virtual void walk(error_expr* expr); virtual void walk(lambda* expr); virtual void walk(parenthetical* expr); virtual void walk(int_literal* expr); virtual void walk(variable* expr); virtual void walk(member* expr); virtual void walk(subscript* expr); virtual void walk(call_expr* expr); virtual void walk(bin_expr* expr); virtual void walk(un_expr* expr); virtual void walk(classdef* classdef); virtual void walk(program* program); virtual void walk(compilation_unit* unit); };*/ }
brianush1/origin
Origin/lexer.h
<gh_stars>1-10 #pragma once #include <stddef.h> #include <istream> #include <string> #include <vector> namespace origin { enum class token_type { invalid_token, eof, identifier, keyword, string, number, symbol, }; struct token { token_type type = token_type::invalid_token; std::istream* stream; std::string value; size_t start; size_t end; }; struct diagnostic { std::string message; std::istream* stream; size_t start; size_t end; std::string template_str; bool warning = false; }; class lexer { private: struct lexer_state { size_t diagnostics; std::streampos input; bool has_peeked; token peeked; }; std::vector<lexer_state> state; std::istream& input; std::vector<diagnostic>& diagnostics; bool has_peeked = false; token peeked; token last_token; token ln_token; bool has_ln; token next_internal(); token next_internal(bool, token); public: lexer(std::istream& input, std::vector<diagnostic>& diagnostics); bool eof(); bool is_next(token_type type); bool is_next(token_type type, const std::string& value); bool has_newline(); token newline_token(); bool try_to_close(token_type type, const std::string& open, const std::string& close); token last(); token next(); token peek(); token consume(token_type type); token consume(token_type type, const std::string& value); token consume_msg(token_type type, const std::string& message); token consume_msg(token_type type, const std::string& value, const std::string& message); token read(token_type type); token read(token_type type, const std::string& value); token read_msg(token_type type, const std::string& message); token read_msg(token_type type, const std::string& value, const std::string& message); void save(); void restore(); void discard(); }; std::string encode_token(token token, bool include_value); }
brianush1/origin
Origin/diagnostics.h
#pragma once #include <stddef.h> #include <string> #include "lexer.h" namespace origin { extern std::string template_str; diagnostic error(const std::string& message, token start); diagnostic error(const std::string& message, token start, token end); diagnostic warn(const std::string& message, token start); diagnostic warn(const std::string& message, token start, token end); }
brianush1/origin
Origin/ast.h
<gh_stars>1-10 #pragma once #include <string> #include <variant> #include <unordered_map> #include "lexer.h" namespace origin { enum access { private_access, public_access, }; class block; class classdef; class typing { public: std::string name; std::string alias_name; bool alias; std::vector<typing*> templates; token start; token generic_token; token end; }; class expr { public: class typing* typing; token start; token end; virtual ~expr(); }; class un_expr : public expr { public: std::string op; class expr* expr; }; class bin_expr : public expr { public: token op_token; std::string op; expr* left; expr* right; }; class call_expr : public expr { public: expr* function; std::vector<expr*> args; }; class subscript : public expr { public: expr* left; expr* right; }; class member : public expr { public: expr* object; std::string name; token name_token; }; class variable : public expr { public: std::string name; }; class int_literal : public expr { public: std::string value; }; class parenthetical : public expr { public: class expr* expr; }; class lambda : public expr { public: class block* block; origin::typing* return_type; std::vector<origin::typing*> param_types; std::vector<std::string> param_names; }; class error_expr : public expr { public: }; class stat { public: token start; token end; virtual ~stat(); }; class return_stat : public stat { public: class expr* expr; }; class block : public stat { public: std::vector<stat*> stats; }; class expr_stat : public stat { public: class expr* expr; }; class if_stat : public stat { public: expr* cond; stat* body; stat* else_body; }; class vardecl : public stat { public: token var_token; std::string variable; class typing* typing; expr* init_value; }; class program { public: std::string namespace_name; std::vector<variable*> imports; std::vector<vardecl*> vardecls; std::vector<classdef*> classes; std::unordered_map<std::string, typing*> typedefs; }; typedef std::vector<program*> compilation_unit; class classdef { public: std::string name; token name_token; std::vector<vardecl*> vardecls; std::vector<access> accesses; bool is_struct; std::vector<std::string> generics; bool variadic; class program* program; }; }
brianush1/origin
Origin/parser.h
#pragma once #include <functional> #include <vector> #include <unordered_map> #include <string> #include "diagnostics.h" #include "lexer.h" #include "allocator.h" #include "ast.h" namespace origin { typedef std::function<expr*(token op)> prefix_parselet; typedef std::function<expr*(token op, expr* left)> infix_parselet; class parser { private: allocator memory; std::vector<diagnostic>& diagnostics; std::unordered_map<std::string, int> op_precedence; std::unordered_map<std::string, prefix_parselet> prefix_parselets; std::unordered_map<std::string, infix_parselet> infix_parselets; void semi(); public: class lexer& lexer; parser(origin::lexer& lexer, std::vector<diagnostic>& diagnostics); typing* read_typing(); expr* read_expr(const std::string& op); expr* read_expr(int precedence = -1); expr* read_expr(int precedence, std::function<expr*()> fail); variable* read_variable(); stat* read_stat(); block* read_block(); vardecl* read_vardecl(); lambda* read_func_part(typing* return_type); classdef* read_classdef(); program* read_program(); }; }
brianush1/origin
Origin/allocator.h
#pragma once #include <vector> #include <functional> namespace origin { class allocator { private: std::vector<std::function<void()>> cleanup; public: template<class T> T* allocate() { T* result = new T(); cleanup.push_back([=] { delete result; }); return result; } ~allocator(); }; }
uestczyh222/STM32F4_BootLoader
main.c
<filename>main.c #include "stm32f4xx.h" #define APPLICATION_ADDRESS 0x08004000 typedef void (*pFunction)(void); pFunction function; unsigned int JumpAddress; void RunToDFU() { JumpAddress = *(__IO uint32_t*) (0x1FFF0000 + 4); function = (pFunction) JumpAddress; __set_MSP(*(__IO uint32_t*) 0x1FFF0000); function(); } void RunToApplication() { JumpAddress = *(__IO uint32_t*) (APPLICATION_ADDRESS + 4); function = (pFunction) JumpAddress; __set_MSP(*(__IO uint32_t*) APPLICATION_ADDRESS); function(); } int main(void) { if (((*(__IO uint32_t*)APPLICATION_ADDRESS) & 0x2FFE0000 ) == 0x20000000) { RunToApplication(); } RunToDFU(); }
OpenARDF/Arducon
Software/AtmelStudio7/Arducon/Arducon/Goertzel.h
<gh_stars>1-10 /* * MIT License * * Copyright (c) 2021 DigitalConfections * * 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. * * See https://www.embedded.com/the-goertzel-algorithm * */ /* ensure this library description is only included once */ #ifndef Goertzel_h #define Goertzel_h /* include types & constants of Wiring core API */ #include "defs.h" #if !INIT_EEPROM_ONLY #ifdef ATMEL_STUDIO_7 #include "ardooweeno.h" #include <math.h> #include <stdlib.h> #else #include "Arduino.h" #endif /* ATMEL_STUDIO_7 */ #define MAXN 209 #define ADCCENTER 512 /* Adjustments that can be made to tune performance: N, Sampling Frequency (Sample Rate), Threshold, ADCCENTER, Minimum tone detection time */ class Goertzel { public: Goertzel(float, float); ~Goertzel(); void SetTargetFrequency(float); bool DataPoint(int); float Magnitude2(int *highCount); bool SamplesReady(void); void Flush(void); private: void ProcessSample(int); void ResetGoertzel(void); }; #endif // !INIT_EEPROM_ONLY #endif
OpenARDF/Arducon
Software/Arduino/Arducon/morse.h
/* * MIT License * * Copyright (c) 2021 DigitalConfections * * 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. */ #ifndef MORSE_H_ #define MORSE_H_ #include "defs.h" #ifdef __cplusplus extern "C" { #endif #define PROCESSSOR_CLOCK_HZ (16000000L) #define WPM_TO_MS_PER_DOT(w) (1200/(w)) #define THROTTLE_VAL_FROM_WPM(w) (PROCESSSOR_CLOCK_HZ / 8000000L) * ((7042 / (w)) / 10) /* */ typedef struct { uint8_t pattern; uint8_t lengthInSymbols; uint8_t lengthInElements; } MorseCharacter; /** Load a string to send by passing in a pointer to the string in the argument. Call this function with a NULL argument at intervals of 1 element of time to generate Morse code. Once loaded with a string each call to this function returns a BOOL indicating whether a CW carrier should be sent */ BOOL makeMorse(char* s, BOOL* repeating, BOOL* finished); /** Returns the number of milliseconds required to send the string pointed to by the first argument at the WPM code speed passed in the second argument. */ uint16_t timeRequiredToSendStrAtWPM(char* str, uint16_t spd); #ifdef __cplusplus } #endif #endif /* MORSE_H_ */
OpenARDF/Arducon
Software/Arduino/Arducon/defs.h
/* * MIT License * * Copyright (c) 2021 DigitalConfections * * 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. */ #ifndef DEFS_H #define DEFS_H #ifndef FALSE #define FALSE 0 #endif #ifndef TRUE #define TRUE !FALSE #endif /*********************************************************** * IMPORTANT: * * Compile for initializing EEPROM values * * Note: Build and run with the following compilation flag * * set to TRUE. Then build and run with the flag * * set to FALSE. */ /***********************************************************/ #define INIT_EEPROM_ONLY TRUE /***********************************************************/ /*********************************************************** * Uncomment the correct frequency for the Arduino Pro Mini * * you will be using */ /***********************************************************/ #define PROCESSOR_FREQ_HERTZ 16000000UL // #define PROCESSOR_FREQ_HERTZ 8000000UL /***********************************************************/ /************************************************************************* * IMPORTANT: CHANGING ANY COMPILE SETTINGS BELOW THIS LINE WILL REQUIRE * * BUILDING AND RUNNING THE PROGRAM WITH INIT_EEPROM_ONLY TRUE, * * AND THEN BUILDING AND RUNNING THE PROGRAM WITH INIT_EEPROM_ONLY FALSE. */ /*************************************************************************/ /*********************************************************** * OPTIONAL COMPILE: * * Compile for AM Attenuator Support * * Note: Setting the following compile flag to TRUE will * * disable software support for the AM attenuator, and * * will cause the Arduino Pro Mini's green LED to be used * * for visible enunciations. */ /***********************************************************/ #define SUPPORT_ONLY_80M FALSE /***********************************************************/ #ifdef F_CPU #undef F_CPU #endif #define F_CPU PROCESSOR_FREQ_HERTZ #ifdef ATMEL_STUDIO_7 #include <avr/io.h> #include <avr/interrupt.h> #define USE_WDT_RESET TRUE #else #include "Arduino.h" #define USE_WDT_RESET FALSE #endif /* ATMEL_STUDIO_7 */ #ifndef HIGH #define HIGH 0x1 #endif #ifndef LOW #define LOW 0x0 #endif #ifndef UP #define UP 1 #endif #ifndef DOWN #define DOWN 0 #endif #ifndef INPUT #define INPUT 0x0 #endif #ifndef OUTPUT #define OUTPUT 0x1 #endif #ifndef INPUT_PULLUP #define INPUT_PULLUP 0x3 #endif #define MAX_PATTERN_TEXT_LENGTH 20 #define TEMP_STRING_LENGTH (MAX_PATTERN_TEXT_LENGTH + 20) #define MAX_DTMF_ARG_LENGTH TEMP_STRING_LENGTH #define SIZE_OF_TEMPERATURE_TABLE 60 #define SIZE_OF_DATA_MODULATION 32 #define MAX_UNLOCK_CODE_LENGTH 8 #define MIN_UNLOCK_CODE_LENGTH 4 /****************************************************** * Set Hardware Settings */ #define INCLUDE_RV3028_SUPPORT FALSE #define INCLUDE_DS3231_SUPPORT TRUE #if !INCLUDE_DS3231_SUPPORT && !INCLUDE_RV3028_SUPPORT #error One real-time clock device must be supported #endif #if INCLUDE_DS3231_SUPPORT && INCLUDE_RV3028_SUPPORT #error Only one real-time clock device may be enabled #endif /*******************************************************/ #ifndef uint16_t_defined #define uint16_t_defined typedef unsigned int uint16_t; #endif #ifndef uint32_t_defined #define uint32_t_defined typedef unsigned long uint32_t; #endif #ifndef unit8_t_defined #define unit8_t_defined typedef unsigned char uint8_t; #endif #ifndef null #define null 0 #endif #ifndef PI #define PI 3.141592653589793 #endif #ifndef MINUTE #define MINUTE 60UL #endif #ifndef HOUR #define HOUR 3600UL #endif #ifndef DAY #define DAY 86400UL #endif #ifndef YEAR #define YEAR 31536000UL #endif /* * Arduino Pro Mini pin definitions per Arduino IDE */ #define D2 2 #define D3 3 #define D4 4 #define D5 5 #define D6 6 #define D7 7 #define D8 8 #define D9 9 #define D10 10 #define D11 11 #define D12 12 #define D13 13 #ifdef ATMEL_STUDIO_7 #define A0 14 #define A1 15 #define A2 16 #define A3 17 #define A4 18 #define A5 19 #define SDA A4 #define SCL A5 #define A6 20 #define A7 21 #endif /* ATMEL_STUDIO_7 */ /* * Arducon Pin Definitions */ #if SUPPORT_ONLY_80M #define PIN_RXD 0 /* Arduino Pro Mini pin# 1/28 = PD0 */ #define PIN_TXD 1 /* Arduino Pro Mini pin# 2/29 = PD1 */ // #define PIN_RESET /* Arduino Pro Mini pin# 3/22 = PC6 */ #define PIN_RTC_SQW D2 /* Arduino Pro Mini pin# 5 = PD2 */ #define PIN_UNUSED_1 D3 /* Arduino Pro Mini pin# 6 = PD3 */ #define PIN_PTT_LOGIC D4 /* Arduino Pro Mini pin# 7 = PD4 */ #define PIN_CW_TONE_LOGIC D5 /* Arduino Pro Mini pin# 8 = PD5 */ #define PIN_CW_KEY_LOGIC D6 /* Arduino Pro Mini pin# 9 = PD6 */ #define PIN_PWDN D7 /* Arduino Pro Mini pin# 10 = PD7 */ #define PIN_UNUSED_2 D8 /* Arduino Pro Mini pin# 11 = PB0 */ #define PIN_UNUSED_3 D9 /* Arduino Pro Mini pin# 12 = PB1 */ #define PIN_UNUSED_4 D10 /* Arduino Pro Mini pin# 13 = PB2 */ #define PIN_MOSI D11 /* Arduino Pro Mini pin# 14 = PB3 */ #define PIN_UNUSED_5 D11 /* Arduino Pro Mini pin# 14 = PB3 */ #define PIN_MISO D12 /* Arduino Pro Mini pin# 15 = PB4 */ #define PIN_UNUSED_6 D12 /* Arduino Pro Mini pin# 15 = PB4 */ #define PIN_LED D13 /* Arduino Pro Mini pin# 16 = PB5 = SCK Use LED on Pro Mini */ #define PIN_UNUSED_7 A0 /* Arduino Pro Mini pin# 17 = PC0 */ #define PIN_UNUSED_8 A1 /* Arduino Pro Mini pin# 18 = PC1 */ #define PIN_UNUSED_9 A2 /* Arduino Pro Mini pin# 19 = PC2 */ #define PIN_SYNC A3 /* Arduino Pro Mini pin# 20 = PC3 */ #define PIN_SDA SDA /* Arduino Pro Mini pin# 33 = SDA */ #define PIN_SCL SCL /* Arduino Pro Mini pin# 34 = SCL */ #define PIN_AUDIO_INPUT A6 /* Arduino Pro Mini pin# 31 = ADC6 */ #define PIN_BATTERY_LEVEL A7 /* Arduino Pro Mini pin# 32 = ADC7 */ #else #define PIN_RXD 0 /* Arduino Pro Mini pin# 1/28 = PD0 */ #define PIN_TXD 1 /* Arduino Pro Mini pin# 2/29 = PD1 */ // #define PIN_RESET /* Arduino Pro Mini pin# 3/22 = PC6 */ #define PIN_RTC_SQW D2 /* Arduino Pro Mini pin# 5 = PD2 */ #define PIN_UNUSED_1 D3 /* Arduino Pro Mini pin# 6 = PD3 */ #define PIN_PTT_LOGIC D4 /* Arduino Pro Mini pin# 7 = PD4 */ #define PIN_CW_TONE_LOGIC D5 /* Arduino Pro Mini pin# 8 = PD5 */ #define PIN_CW_KEY_LOGIC D6 /* Arduino Pro Mini pin# 9 = PD6 */ #define PIN_PWDN D7 /* Arduino Pro Mini pin# 10 = PD7 */ #define PIN_D0 D8 /* Arduino Pro Mini pin# 11 = PB0 */ #define PIN_D1 D9 /* Arduino Pro Mini pin# 12 = PB1 */ #define PIN_D2 D10 /* Arduino Pro Mini pin# 13 = PB2 */ #define PIN_MOSI D11 /* Arduino Pro Mini pin# 14 = PB3 */ #define PIN_D3 D11 /* Arduino Pro Mini pin# 14 = PB3 */ #define PIN_MISO D12 /* Arduino Pro Mini pin# 15 = PB4 */ #define PIN_D4 D12 /* Arduino Pro Mini pin# 15 = PB4 */ #define PIN_D5 D13 /* Arduino Pro Mini pin# 16 = PB5 = SCK Use LED on Arducon PCB */ #define PIN_UNUSED_2 A0 /* Arduino Pro Mini pin# 17 = PC0 */ #define PIN_UNUSED_3 A1 /* Arduino Pro Mini pin# 18 = PC1 */ #define PIN_LED A2 /* Arduino Pro Mini pin# 19 = PC2 */ #define PIN_SYNC A3 /* Arduino Pro Mini pin# 20 = PC3 */ #define PIN_SDA SDA /* Arduino Pro Mini pin# 33 = SDA */ #define PIN_SCL SCL /* Arduino Pro Mini pin# 34 = SCL */ #define PIN_AUDIO_INPUT A6 /* Arduino Pro Mini pin# 31 = ADC6 */ #define PIN_BATTERY_LEVEL A7 /* Arduino Pro Mini pin# 32 = ADC7 */ #endif /* SUPPORT_ONLY_80M */ typedef enum { UNSTABLE, STABLE_HIGH, STABLE_LOW } ButtonStability_t; typedef enum { BEACON = 0, FOX_1, FOX_2, FOX_3, FOX_4, FOX_5, FOXORING, SPECTATOR, SPRINT_S1, SPRINT_S2, SPRINT_S3, SPRINT_S4, SPRINT_S5, SPRINT_F1, SPRINT_F2, SPRINT_F3, SPRINT_F4, SPRINT_F5, INVALID_FOX, REPORT_BATTERY } Fox_t; typedef enum { NO_KEY = 0, ONE_KEY = '1', TWO_KEY = '2', THREE_KEY = '3', A_KEY = 'A', FOUR_KEY = '4', FIVE_KEY = '5', SIX_KEY = '6', B_KEY = 'B', SEVEN_KEY = '7', EIGHT_KEY = '8', NINE_KEY = '9', C_KEY = 'C', STAR_KEY = '*', ZERO_KEY = '0', POUND_KEY = '#', D_KEY = 'D' } DTMF_key_t; typedef enum { AM_DISABLED, AM_500Hz, AM_600Hz, AM_700Hz, AM_800Hz, AM_900Hz, AM_1000Hz } AM_Tone_Freq_t; #define Goertzel_N 201 #define MAX_CODE_SPEED_WPM 20 #define MIN_CODE_SPEED_WPM 5 #define SPRINT_FAST_CODE_SPEED 15 #define SPRINT_SLOW_CODE_SPEED 8 #define MAX_AM_TONE_FREQUENCY 6 #define MIN_AM_TONE_FREQUENCY 0 #define TEMPERATURE_POLL_INTERVAL_SECONDS 59 #define VOLTAGE_POLL_INTERVAL_SECONDS 11 #define LED_TIMEOUT_SECONDS 300 typedef enum { WD_SW_RESETS, WD_HW_RESETS, WD_FORCE_RESET, WD_DISABLE } WDReset; typedef enum { STATE_SHUTDOWN, STATE_SENTENCE_START, STATE_A, STATE_PAUSE_TRANSMISSIONS, STATE_START_TRANSMISSIONS, STATE_START_TRANSMISSIONS_WITH_RTC, STATE_START_TRANSMITTING_NOW, STATE_C, STATE_RECEIVING_CALLSIGN, STATE_RECEIVING_FOXFORMATANDID, STATE_RECEIVING_START_TIME, STATE_RECEIVING_FINISH_TIME, STATE_RECEIVING_UTC_OFFSET, STATE_RECEIVING_SET_CLOCK, #if !SUPPORT_ONLY_80M STATE_SET_AM_TONE_FREQUENCY, STATE_TEST_ATTENUATOR, /* Temporary test definition */ #endif /* !SUPPORT_ONLY_80M */ STATE_SET_PTT_PERIODIC_RESET, STATE_GET_BATTERY_VOLTAGE, STATE_SET_PASSWORD, STATE_CHECK_PASSWORD, STATE_RECEIVING_FOXES_TO_ADDRESS } KeyprocessState_t; /*******************************************************/ #ifndef SELECTIVELY_DISABLE_OPTIMIZATION #define SELECTIVELY_DISABLE_OPTIMIZATION #endif /****************************************************** * EEPROM definitions */ #define EEPROM_INITIALIZED_FLAG 0x00BB /* Never set to 0xFFFF */ #define EEPROM_UNINITIALIZED 0x00 #define EEPROM_START_TIME_DEFAULT 0 #define EEPROM_FINISH_TIME_DEFAULT 0 #define EEPROM_EVENT_ENABLED_DEFAULT FALSE #define EEPROM_ID_CODE_SPEED_DEFAULT 20 #define EEPROM_PATTERN_CODE_SPEED_DEFAULT 8 #define EEPROM_ON_AIR_TIME_DEFAULT 60 #define EEPROM_OFF_AIR_TIME_DEFAULT 240 #define EEPROM_INTRA_CYCLE_DELAY_TIME_DEFAULT 0 #define EEPROM_TEMP_CALIBRATION_DEFAULT 330 /* Use -110 for genuine ATMEGA328P) */ #define EEPROM_RV3028_OFFSET_DEFAULT 0 #define EEPROM_FOX_SETTING_DEFAULT (Fox_t)1 #define EEPROM_AM_AUDIO_FREQ_DEFAULT (AM_Tone_Freq_t)0 #define EEPROM_ENABLE_LEDS_DEFAULT 1 #define EEPROM_ENABLE_STARTTIMER_DEFAULT 0 #define EEPROM_ENABLE_TRANSMITTER_DEFAULT 1 #define EEPROM_START_EPOCH_DEFAULT 0 #define EEPROM_FINISH_EPOCH_DEFAULT 0 #define EEPROM_UTC_OFFSET_DEFAULT 0 #define EEPROM_PTT_PERIODIC_RESET_DEFAULT 0 #define EEPROM_DTMF_UNLOCK_CODE_DEFAULT ("1357") #define MINIMUM_EPOCH ((time_t)1609459200) /* 1 Jan 2021 00:00:00 */ #define SECONDS_24H 86400 typedef enum { NULL_CONFIG, WAITING_FOR_START, CONFIGURATION_ERROR, SCHEDULED_EVENT_DID_NOT_START, SCHEDULED_EVENT_WILL_NEVER_RUN, EVENT_IN_PROGRESS } ConfigurationState_t; #define ERROR_BLINK_PATTERN ((char*)"E ") #define WAITING_BLINK_PATTERN ((char*)"EE ") #define DTMF_ERROR_BLINK_PATTERN ((char*)"EEEEEEEE") #define DTMF_DETECTED_BLINK_PATTERN ((char*)"T") #ifndef BOOL typedef uint8_t BOOL; #endif #ifndef Frequency_Hz typedef unsigned long Frequency_Hz; #endif #ifndef UINT16_MAX #define UINT16_MAX __INT16_MAX__ #endif #define OFF 0 #define ON 1 #define TOGGLE 2 #define UNDETERMINED 3 #define MIN(A, B) ({ __typeof__(A)__a = (A); __typeof__(B)__b = (B); __a < __b ? __a : __b; }) #define MAX(A, B) ({ __typeof__(A)__a = (A); __typeof__(B)__b = (B); __a < __b ? __b : __a; }) #define CLAMP(low, x, high) ({ \ __typeof__(x)__x = (x); \ __typeof__(low)__low = (low); \ __typeof__(high)__high = (high); \ __x > __high ? __high : (__x < __low ? __low : __x); \ }) #define MAX_TIME 4294967295L #define MAX_UINT16 65535U #define MAX_INT16 32767 #define MIN_INT16 -32768 /* Periodic TIMER2 interrupt timing definitions */ #define TIMER2_57HZ 10 #define TIMER2_20HZ 49 #define TIMER2_5_8HZ 100 #define TIMER2_0_5HZ 1000 #define TIMER2_SECONDS_60 85680 #define TIMER2_SECONDS_30 42840 #define TIMER2_SECONDS_20 28560 #define TIMER2_SECONDS_10 14280 #define TIMER2_SECONDS_6 8566 #define TIMER2_SECONDS_5 7138 #define TIMER2_SECONDS_3 4283 #define TIMER2_SECONDS_2 2855 #define TIMER2_SECONDS_1 1428 #define TIMER2_MSECONDS_100 143 #define TIMER2_MSECONDS_200 286 #define BLINK_FAST 30 #define BLINK_SHORT 100 #define BLINK_LONG 500 /* TIMER0 tone frequencies */ #if F_CPU == 16000000UL #define DEFAULT_TONE_FREQUENCY 0x2F #define TONE_600Hz 0x1F #define TONE_500Hz 0x3F #define TONE_400Hz 0x4F #else #define DEFAULT_TONE_FREQUENCY 0x18 #define TONE_600Hz 0x0F #define TONE_500Hz 0x1F #define TONE_400Hz 0x27 #endif #define ADC_REF_VOLTAGE_mV 1100L #define VOLTAGE_MAX_MV 15000L #define VOLTS(x) ((x * VOLTAGE_MAX_MV) / 1023L) /* Input voltage thresholds */ #define VOLTAGE_THRESHOLD_LOW 1160 #define VOLTAGE_THRESHOLD_HIGH 1250 /****************************************************** * UI Hardware-related definitions */ typedef enum { FrequencyFormat, HourMinuteSecondFormat, HourMinuteSecondDateFormat } TextFormat; #define DISPLAY_WIDTH_STRING_SIZE (NUMBER_OF_LCD_COLS + 1) typedef enum { Minutes_Seconds, /* minutes up to 59 */ Hours_Minutes_Seconds, /* hours up to 23 */ Day_Month_Year_Hours_Minutes_Seconds, /* Year up to 99 */ Minutes_Seconds_Elapsed, /* minutes up to 99 */ Time_Format_Not_Specified } TimeFormat; #define NO_TIME_SPECIFIED (-1) #define SecondsFromHours(hours) ((hours) * 3600) #define SecondsFromMinutes(min) ((min) * 60) typedef enum { PATTERN_TEXT, STATION_ID } TextIndex; typedef enum { POWER_UP, PUSHBUTTON, PROGRAMMATIC, NO_ACTION } EventActionSource_t; typedef enum { START_NOTHING, START_EVENT_NOW, START_TRANSMISSIONS_NOW, START_EVENT_WITH_STARTFINISH_TIMES } EventAction_t; typedef enum { INIT_NOT_SPECIFIED, INIT_EVENT_STARTING_NOW, INIT_TRANSMISSIONS_STARTING_NOW, INIT_EVENT_IN_PROGRESS_WITH_STARTFINISH_TIMES } InitializeAction_t; typedef enum { AUDIO_SAMPLING, TEMPERATURE_SAMPLING, VOLTAGE_SAMPLING } ADCChannel_t; #endif /* DEFS_H */
OpenARDF/Arducon
Software/Arduino/Arducon/rv3028.h
<reponame>OpenARDF/Arducon<filename>Software/Arduino/Arducon/rv3028.h /********************************************************************************************** * Copyright (c) 2017 Digital Confections LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in the * Software without restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, subject to the * following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * ********************************************************************************************** * rv3028.h * * RV3028: Extremely Accurate I2C-Integrated RTC/TCXO/Crystal * The RV3028 is a low-cost, extremely accurate I2C real-time clock (RTC) with an integrated * crystal oscillator and crystal. The device incorporates a battery input, and maintains * accurate timekeeping when main power to the device is interrupted. * */ #ifndef RV3028_H_ #define RV3028_H_ #include "defs.h" #include "i2c.h" #include <time.h> #define RTC_STATUS_NORMAL 0x00 #define RTC_STATUS_I2C_ERROR 7 #define RTC_STATUS_BACKUP_SWITCHOVER_OCCURRED 5 #define RTC_STATUS_EVF_OCCURRED 1 #define RTC_STATUS_CLOCK_CORRUPT 0 #if INCLUDE_RV3028_SUPPORT #define RV3028_I2C_SLAVE_ADDR 0xA4 /* corresponds to slave address = 0b10100100x */ /** * Reads hours, minutes and seconds from the RV3028 and returns them in the memory location pointed to by * the first two arguments. * *val - if non-NULL will receive a dword value of the time in seconds since midnight. * *char - if non-NULL will receive a string representation of the time * format - specifies the string format to be used for the string time representation */ #ifdef DATE_STRING_SUPPORT_ENABLED void rv3028_read_date_time(int32_t* val, char* buffer, TimeFormat format); #endif /* DATE_STRING_SUPPORT_ENABLED */ /** * Reads time from the RV3028 and returns the epoch */ time_t RTC_get_epoch(bool *result, char *datetime); /** * Set year, month, date, day, hours, minutes and seconds of the rv3028 to the time passed in the argument. * dateString has the format 2018-03-23T18:00:00 * ClockSetting setting = clock or alarm to be set */ // BOOL rv3028_set_date_time(char * dateString); /** * Set or Get the UNIX epoch registers */ BOOL RTC_set_epoch(time_t epoch); time_t RTC_get_epoch(void); /** * Turn on 1-second square wave on the INT/SQW pin. */ BOOL RTC_1s_sqw(BOOL onOff); /** * Read current setting of temperature offset RAM */ int16_t rv3028_get_offset_RAM(void); /** * Set RAM value of temperature offset */ void rv3028_set_offset_RAM(uint16_t val); /** * Returns current state of 1-Hz clock pin */ BOOL rv3028_1Hz_enabled(void); #endif /* #ifdef INCLUDE_RV3028_SUPPORT */ #endif /* RV3028_H_ */
OpenARDF/Arducon
Software/Arduino/Arducon/i2c.h
<reponame>OpenARDF/Arducon<gh_stars>1-10 /********************************************************************************************** * Copyright (c) 2017 Digital Confections LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in the * Software without restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, subject to the * following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * ********************************************************************************************** * * i2c.h */ #include "defs.h" #ifndef I2C_H_ #define I2C_H_ #ifdef __cplusplus extern "C" { #endif #define I2C_TIMEOUT_SUPPORT /* limit number of tries for i2c success */ /* #define SUPPORT_I2C_CLEARBUS_FUNCTION */ #ifndef BOOL typedef uint8_t BOOL; #endif #ifndef FALSE #define FALSE 0 #endif #ifndef TRUE #define TRUE !FALSE #endif /** */ void i2c_init(void); /** */ BOOL i2c_device_read(uint8_t slaveAddr, uint8_t addr, uint8_t data[], uint8_t bytes2read); /** */ BOOL i2c_device_write(uint8_t slaveAddr, uint8_t addr, uint8_t data[], uint8_t bytes2write); #ifdef I2C_TIMEOUT_SUPPORT /** */ BOOL i2c_start(void); #else /** */ void i2c_start(void); #endif /** */ void i2c_stop(void); /** */ BOOL i2c_write_success(uint8_t, uint8_t); /** */ uint8_t i2c_read_ack(void); /** */ uint8_t i2c_read_nack(void); /** */ BOOL i2c_status(uint8_t); #ifdef SUPPORT_I2C_CLEARBUS_FUNCTION /** */ BOOL i2c_clearBus(void); #endif /* SUPPORT_I2C_CLEARBUS_FUNCTION */ #ifdef __cplusplus } #endif #endif /* I2C_H_ */
OpenARDF/Arducon
Software/Arduino/Arducon/linkbus.h
<reponame>OpenARDF/Arducon /* * MIT License * * Copyright (c) 2021 DigitalConfections * * 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. */ /* * linkbus.h - a simple serial inter-processor communication protocol. */ #ifndef LINKBUS_H_ #define LINKBUS_H_ #include "defs.h" #ifdef __cplusplus extern "C" { #endif #define LINKBUS_MAX_MSG_LENGTH 50 #define LINKBUS_MIN_MSG_LENGTH 2 /* shortest message: GO */ #define LINKBUS_MAX_MSG_FIELD_LENGTH 20 #define LINKBUS_MAX_MSG_NUMBER_OF_FIELDS 3 #define LINKBUS_NUMBER_OF_RX_MSG_BUFFERS 2 #define LINKBUS_MAX_TX_MSG_LENGTH 41 #define LINKBUS_NUMBER_OF_TX_MSG_BUFFERS 3 #define LINKBUS_MAX_COMMANDLINE_LENGTH ((1 + LINKBUS_MAX_MSG_FIELD_LENGTH) * LINKBUS_MAX_MSG_NUMBER_OF_FIELDS) #define LINKBUS_POWERUP_DELAY_SECONDS 6 #define LINKBUS_MIN_TX_INTERVAL_MS 100 #define BAUD 57600 #define MYUBRR(b) ((F_CPU + b * 8L) / (b * 16L) - 1) typedef enum { EMPTY_BUFF, FULL_BUFF } BufferState; /* Linkbus Messages * Message formats: * CMD [a1 [a2]] * * where * CMD = command * a1, a2 = optional arguments or data fields * */ typedef enum { MESSAGE_EMPTY = 0, /* ARDUCON MESSAGE FAMILY (SERIAL MESSAGING) */ MESSAGE_SET_FOX = 'F' * 100 + 'O' * 10 + 'X', /* Set the fox role to be used to define timing and signals */ #if !SUPPORT_ONLY_80M MESSAGE_SET_AM_TONE = 'A' * 10 + 'M', /* Set AM audio tone frequency */ #endif // !SUPPORT_ONLY_80M MESSAGE_UTIL = 'U' * 100 + 'T' * 10 + 'I', /* Temperature and Voltage data */ MESSAGE_SET_STATION_ID = 'I' * 10 + 'D', /* Sets amateur radio callsign text */ MESSAGE_SYNC = 'S' * 100 + 'Y' * 10 + 'N', /* Synchronizes transmissions */ MESSAGE_CODE_SETTINGS = 'S' * 100 + 'E' * 10 + 'T', /* Set Morse code speeds */ MESSAGE_CLOCK = 'C' * 100 + 'L' * 10 + 'K', /* Set or read the RTC */ MESSAGE_PASSWORD = 'P' * 100 + 'W' * 10 + 'D', /* Password command */ INVALID_MESSAGE = UINT16_MAX /* This value must never overlap a valid message ID */ } LBMessageID; typedef enum { LINKBUS_MSG_UNKNOWN = 0, LINKBUS_MSG_COMMAND, LINKBUS_MSG_QUERY, LINKBUS_MSG_REPLY, LINKBUS_MSG_INVALID } LBMessageType; typedef enum { FIELD1 = 0, FIELD2 = 1 } LBMessageField; typedef enum { BATTERY_BROADCAST = 0x0001, RSSI_BROADCAST = 0x0002, RF_BROADCAST = 0x0004, UPC_TEMP_BROADCAST = 0x0008, ALL_BROADCASTS = 0x000FF } LBbroadcastType; typedef enum { NO_ID = 0, CONTROL_HEAD_ID = 1, RECEIVER_ID = 2, TRANSMITTER_ID = 3 } DeviceID; typedef char LinkbusTxBuffer[LINKBUS_MAX_TX_MSG_LENGTH]; typedef struct { LBMessageType type; LBMessageID id; char fields[LINKBUS_MAX_MSG_NUMBER_OF_FIELDS][LINKBUS_MAX_MSG_FIELD_LENGTH]; } LinkbusRxBuffer; #define WAITING_FOR_UPDATE -1 /** */ void linkbus_init(uint32_t baud); /** * Immediately turns off receiver and flushes receive buffer */ void linkbus_disable(void); /** * Undoes linkbus_disable() */ void linkbus_enable(void); /** */ void linkbus_end_tx(void); /** */ void linkbus_reset_rx(void); /** */ LinkbusTxBuffer* nextEmptyTxBuffer(void); /** */ LinkbusTxBuffer* nextFullTxBuffer(void); /** */ BOOL linkbusTxInProgress(void); /** */ LinkbusRxBuffer* nextEmptyRxBuffer(void); /** */ LinkbusRxBuffer* nextFullRxBuffer(void); /** */ void lb_send_NewPrompt(void); /** */ void lb_send_NewLine(void); /** */ void lb_echo_char(uint8_t c); /** */ BOOL lb_send_string(char* str, BOOL wait); /** */ void lb_send_value(uint16_t value, char* label); /** */ BOOL lb_enabled(void); #ifdef __cplusplus } #endif #endif /* LINKBUS_H_ */
OpenARDF/Arducon
Software/Arduino/Arducon/f1975.h
/* * MIT License * * Copyright (c) 2021 DigitalConfections * * 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. */ #ifndef __f1975_H__ #define __f1975_H__ #include "defs.h" #ifdef __cplusplus extern "C" { #endif typedef uint16_t tenthDB_t; /* typedef enum{ dB0 = 0x00, dB_5 = 0x01, dB1_0 = 0x02, dB1_5 = 0x03, dB2_0 = 0x04, dB2_5 = 0x05, dB3_0 = 0x06, dB3_5 = 0x07, dB4_0 = 0x08, dB4_5 = 0x09, dB5_0 = 0x0a, dB5_5 = 0x0b, dB6_0 = 0x0c, dB6_5 = 0x0d, dB7_0 = 0x0e, dB7_5 = 0x0f, dB8_0 = 0x10, dB8_5 = 0x11, dB9_0 = 0x12, dB9_5 = 0x13, dB10_0 = 0x14, dB10_5 = 0x15, dB11_0 = 0x16, dB11_5 = 0x17, dB12_0 = 0x18, dB12_5 = 0x19, dB13_0 = 0x1a, dB13_5 = 0x1b, dB14_0 = 0x1c, dB14_5 = 0x1d, dB15_0 = 0x1e, dB15_5 = 0x1f, dB16_0 = 0x20, dB16_5 = 0x21, dB17_0 = 0x22, dB17_5 = 0x23, dB18_0 = 0x24, dB18_5 = 0x25, dB19_0 = 0x26, dB19_5 = 0x27, dB20_0 = 0x28, dB20_5 = 0x29, dB21_0 = 0x2a, dB21_5 = 0x2b, dB22_0 = 0x2c, dB22_5 = 0x2d, dB23_0 = 0x2e, dB23_5 = 0x2f, dB24_0 = 0x30, dB24_5 = 0x31, dB25_0 = 0x32, dB25_5 = 0x33, dB26_0 = 0x34, dB26_5 = 0x35, dB27_0 = 0x36, dB27_5 = 0x37, dB28_0 = 0x38, dB28_5 = 0x39, dB29_0 = 0x3a, dB29_5 = 0x3b, dB30_0 = 0x3c, dB30_5 = 0x3d, dB31_0 = 0x3e, dB31_5 = 0x3f } dB_t; */ #define MAX_ATTEN_TENTHS_DB (tenthDB_t)315 #define MAX_ATTEN_SETTING 0x3F void setAtten(tenthDB_t att); void setupPortsForF1975(BOOL enable); #ifdef __cplusplus } #endif #endif //__f1975_H__
OpenARDF/Arducon
Software/Arduino/Arducon/EepromManager.h
<gh_stars>1-10 /* * MIT License * * Copyright (c) 2021 DigitalConfections * * 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. */ #ifndef __EEPROMMANAGER_H__ #define __EEPROMMANAGER_H__ #include "defs.h" #ifdef ATMEL_STUDIO_7 #include <avr/eeprom.h> #endif /* ATMEL_STUDIO_7 */ #include <time.h> #if INCLUDE_RV3028_SUPPORT #if SUPPORT_ONLY_80M /* Set Firmware Version Here */ #define PRODUCT_NAME_LONG_TXT "*** Arducon Fox Controller Ver. S2.60A ***\n" #define HELP_TEXT_TXT "\nCommands:\n CLK [T|S|F|O [\"YYMMDDhhmmss\"]] - Read/set time/start/finish/offset\n FOX [fox]- Set fox role\n ID [callsign] - Set callsign\n SYN 0-3 - Synchronize\n PWD [pwd] - Set DTMF password\n UTI - Read volts & temp\n SET S|P [setting] - Set ID code speed or PTT reset" #else /* Set Firmware Version Here */ #define PRODUCT_NAME_LONG_TXT "*** Arducon Fox Controller Ver. S2.60B ***\n" #define HELP_TEXT_TXT "\nCommands:\n CLK [T|S|F|O [\"YYMMDDhhmmss\"]] - Read/set time/start/finish/offset\n FOX [fox]- Set fox role\n ID [callsign] - Set callsign\n SYN 0-3 - Synchronize\n PWD [<PASSWORD>] - Set DTMF <PASSWORD> AM [0-6] - Set AM tone frequency\n UTI - Read volts & temp\n SET S|P [setting] - Set ID code speed or PTT reset" #endif /* SUPPORT_ONLY_80M */ #elif INCLUDE_DS3231_SUPPORT #if SUPPORT_ONLY_80M /* Set Firmware Version Here */ #define PRODUCT_NAME_LONG_TXT "*** Arducon Fox Controller Ver. S2.60C ***\n" #define HELP_TEXT_TXT "\nCommands:\n CLK [T|S|F [\"YYMMDDhhmmss\"]] - Read/set time/start/finish/offset\n FOX [fox]- Set fox role\n ID [callsign] - Set callsign\n SYN 0-3 - Synchronize\n PWD [<PASSWORD>] - Set <PASSWORD> UTI - Read volts & temp\n SET S|P [setting] - Set ID code speed or PTT reset" #else /* Set Firmware Version Here */ #define PRODUCT_NAME_LONG_TXT "*** Arducon Fox Controller Ver. S2.60D ***\n" #define HELP_TEXT_TXT "\nCommands:\n CLK [T|S|F [\"YYMMDDhhmmss\"]] - Read/set time/start/finish/offset\n FOX [fox]- Set fox role\n ID [callsign] - Set callsign\n SYN 0-3 - Synchronize\n PWD [pwd] - Set DTMF password\n AM [0-6] - Set AM tone frequency\n UTI - Read volts & temp\n SET S|P [setting] - Set ID code speed or PTT reset" #endif /* SUPPORT_ONLY_80M */ #endif /* INCLUDE_RV3028_SUPPORT */ #define TEXT_SET_TIME_TXT "CLK T YYMMDDhhmmss <- Set current time\n" #define TEXT_SET_START_TXT "CLK S YYMMDDhhmmss <- Set start time\n" #define TEXT_SET_FINISH_TXT "CLK F YYMMDDhhmmss <- Set finish time\n" #define TEXT_SET_ID_TXT "ID [\"callsign\"] <- Set callsign\n" #define TEXT_ERR_FINISH_BEFORE_START_TXT "Err: Finish before start!\n" #define TEXT_ERR_FINISH_IN_PAST_TXT "Err: Finish in past!\n" #define TEXT_ERR_START_IN_PAST_TXT "Err: Start in past!\n" #define TEXT_ERR_INVALID_TIME_TXT "Err: Invalid time!\n" #define TEXT_ERR_TIME_IN_PAST_TXT "Err: Time in past!\n" #define TEXT_EEPROM_SUCCESS_MESSAGE_TXT "Success! EEPROM has been programmed. Program is done.\nReflash with #define INIT_EEPROM_ONLY FALSE\n" struct EE_prom { uint16_t eeprom_initialization_flag; uint16_t temperature_table[SIZE_OF_TEMPERATURE_TABLE]; int16_t atmega_temp_calibration; int16_t rv3028_offset; time_t event_start_epoch; time_t event_finish_epoch; char textVersion[sizeof(PRODUCT_NAME_LONG_TXT)]; char textHelp[sizeof(HELP_TEXT_TXT)]; char textSetTime[sizeof(TEXT_SET_TIME_TXT)]; char textSetStart[sizeof(TEXT_SET_START_TXT)]; char textSetFinish[sizeof(TEXT_SET_FINISH_TXT)]; char textSetID[sizeof(TEXT_SET_ID_TXT)]; char textErrFinishB4Start[sizeof(TEXT_ERR_FINISH_BEFORE_START_TXT)]; char textErrFinishInPast[sizeof(TEXT_ERR_FINISH_IN_PAST_TXT)]; char textErrStartInPast[sizeof(TEXT_ERR_START_IN_PAST_TXT)]; char textErrInvalidTime[sizeof(TEXT_ERR_INVALID_TIME_TXT)]; char textErrTimeInPast[sizeof(TEXT_ERR_TIME_IN_PAST_TXT)]; char stationID_text[MAX_PATTERN_TEXT_LENGTH + 1]; uint8_t dataModulation[SIZE_OF_DATA_MODULATION]; uint8_t unlockCode[MAX_UNLOCK_CODE_LENGTH + 1]; uint8_t id_codespeed; uint8_t fox_setting; uint8_t am_audio_frequency; uint8_t utc_offset; uint8_t ptt_periodic_reset; }; typedef enum { TextVersion, TextHelp, TextSetTime, TextSetStart, TextSetFinish, TextSetID, TextErrFinishB4Start, TextErrFinishInPast, TextErrStartInPast, TextErrInvalidTime, TextErrTimeInPast, StationID_text, Temperature_table, DataModulation, UnlockCode, Id_codespeed, Fox_setting, Am_audio_frequency, Atmega_temp_calibration, Rv3028_offset, Event_start_epoch, Event_finish_epoch, Utc_offset, Ptt_periodic_reset, Eeprom_initialization_flag } EE_var_t; class EepromManager { /*variables */ public: protected: private: /*functions */ public: EepromManager(); ~EepromManager(); static const struct EE_prom ee_vars; void initEEPROMStrings(void); void dumpEEPROMVars(void); BOOL initializeEEPROMVars(void); BOOL readNonVols(void); void send_Help(void); void sendEEPROMString(EE_var_t v); void updateEEPROMVar(EE_var_t v, void* val); uint16_t readTemperatureTable(int i); void resetEEPROMValues(void); #if INIT_EEPROM_ONLY void sendSuccessString(void); #endif /* INIT_EEPROM_ONLY */ protected: private: EepromManager( const EepromManager &c ); EepromManager& operator=( const EepromManager &c ); #if INIT_EEPROM_ONLY void sendPROGMEMString(const char* fl_addr); #endif /* INIT_EEPROM_ONLY */ }; /*EepromManager */ #endif /*__EEPROMMANAGER_H__ */
sunyazhou13/PlayLoadingDemo
PlayLoadingDemo/ViewController.h
// // ViewController.h // PlayLoadingDemo // // Created by sunyazhou on 2018/11/12. // Copyright © 2018 <EMAIL>. All rights reserved. // #import <UIKit/UIKit.h> @interface ViewController : UIViewController @end
chenxuedan/PrintViewCate
Example/PrivateHelloWorld/CXDAppDelegate.h
<filename>Example/PrivateHelloWorld/CXDAppDelegate.h // // CXDAppDelegate.h // PrivateHelloWorld // // Created by chenxuedan on 06/03/2020. // Copyright (c) 2020 chenxuedan. All rights reserved. // @import UIKit; @interface CXDAppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @end
chenxuedan/PrintViewCate
Example/PrivateHelloWorld/CXDViewController.h
<reponame>chenxuedan/PrintViewCate // // CXDViewController.h // PrivateHelloWorld // // Created by chenxuedan on 06/03/2020. // Copyright (c) 2020 chenxuedan. All rights reserved. // @import UIKit; @interface CXDViewController : UIViewController @end
chenxuedan/PrintViewCate
PrivateHelloWorld/Classes/PrintHelloWorldViewController.h
<gh_stars>0 // // PrintHelloWorldViewController.h // CXDVideoRecord // // Created by ZXY on 2020/6/3. // Copyright © 2020 cxd. All rights reserved. // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @interface PrintHelloWorldViewController : UIViewController + (void)printString; @end NS_ASSUME_NONNULL_END
H-M-H/TournamentDM
src/game/server/entities/walltele.h
#ifndef CWALLTELE_H #define CWALLTELE_H #include <game/server/entity.h> class CTeleDisp : public CEntity { public: CTeleDisp(CGameWorld *pGameWorld, vec2 Pos); virtual void Snap(int SnappingClient); private: int m_StartTick; }; class CWallTele : public CEntity { public: CWallTele(CGameWorld *pGameWorld, vec2 Pos); virtual void Tick(); virtual void Snap(int SnappingClient); private: void SetPosOut(); vec2 m_PosOut; vec2 m_Direction; int m_StartTick; }; #endif // CWALLTELE_H
H-M-H/TournamentDM
src/game/server/entities/pickup.h
<gh_stars>0 /* (c) <NAME>. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #ifndef GAME_SERVER_ENTITIES_PICKUP_H #define GAME_SERVER_ENTITIES_PICKUP_H #include <game/server/entity.h> const int PickupPhysSize = 14; class CPickup : public CEntity { public: CPickup(CGameWorld *pGameWorld, int Type, int SubType = 0, int Arena = -1); // Arena == -2: no arena yet, will be determined when picked up virtual void Reset(); virtual void Tick(); virtual void TickPaused(); virtual void Snap(int SnappingClient); private: int m_Type; int m_Subtype; int m_SpawnTick; }; #endif
H-M-H/TournamentDM
src/game/server/gamemodes/tourndm.h
<reponame>H-M-H/TournamentDM #ifndef TOURNDM_H #define TOURNDM_H #include <game/server/gamecontroller.h> // class that handles the overall tourney and fights class CGameControllerTournDM : public IGameController { public: CGameControllerTournDM(class CGameContext *pGameServer, int Subtype); virtual ~CGameControllerTournDM(); virtual void Tick(); virtual void PostReset(); virtual bool CanSpawn(int Team, vec2 *pOutPos, int CID = -1); virtual float EvaluateSpawnPos(CSpawnEval *pEval, vec2 Pos, int CID = -1); virtual void EvaluateSpawnType(CSpawnEval *pEval, int Type, int CID = -1); virtual bool OnEntity(int Index, vec2 Pos); virtual void OnPlayerLeave(int CID); virtual void OnCharacterSpawn(class CCharacter *pChr); virtual int OnCharacterDeath(class CCharacter *pVictim, class CPlayer *pKiller, int Weapon); virtual void DoWincheck(); virtual void StartRound(); virtual void EndRound(); virtual void OnPlayerInfoChange(class CPlayer *pP); virtual void Snap(int SnappingClient); void HandleBracket(); void HandleOddPlayers(); void StartTourney(); void AddTourneyState(char* Name, int size); // puts the players into tourney void SignIn(int CID); bool ChangeArena(int CID, int ID); class CGameControllerArena* Arena(int ID) { return m_apArenas[ID]; } static void ConArenaColor(IConsole::IResult *pResult, void *pUserData); enum { NUM_ARENAS=8 }; bool m_TourneyStarted; int m_NumMatches; int m_NumParticipants; int m_NumActiveParticipants; // those who still can win class CPlayer* m_apBracketPlayers[16]; // players tourney information struct CTInfo { int m_TourneyState; int m_Victories; int m_Losses; }m_aTPInfo[16]; // for normal Playerorder CTInfo* m_apTBInfo[16]; // bracket order private: void UpdateArenaStates(); // -1: no arena/spec/standard spawn | 0-7: arenas with their ID class CGameControllerArena* m_apArenas[NUM_ARENAS]; // stores wether arena can be used at all bool m_aActiveArenas[NUM_ARENAS]; int m_NumActiveArenas; // stores g_Config.m_SvArenas bool m_OldArenaMode; // Joincounter to determine TID int m_JoinCount; // wether odd tees are handled atm bool m_HandlingOdds; // stores g_Config.m_SvBracket for every tourney int m_BracketMode; }; // /////////////////////////////////////////// // // class that handles the fighting tees in their arenas class CGameControllerArena { friend class CGameControllerTournDM; typedef CGameControllerTournDM::CSpawnEval CSpawnEval; class CGameContext *m_pGameServer; class IServer *m_pServer; CGameControllerTournDM *m_pController; CGameContext *GameServer() const { return m_pGameServer; } IServer *Server() const { return m_pServer; } CGameControllerTournDM *Controller() { return m_pController; } protected: int m_RoundStartTick; int m_GameOverTick; int m_SuddenDeath; public: CGameControllerArena(class CGameControllerTournDM *pController); void Tick(); bool IsGameOver() const { return m_GameOverTick != -1; } void DoWincheck(); void DoWarmup(int Seconds); void StartRound(); void EndRound(int winnerID, bool Left = false); void StartFight(); void OnCharacterDeath(class CCharacter *pVictim, class CPlayer *pKiller, int Weapon); void OnPlayerEnter(int CID); void OnPlayerLeave(int CID); int OnPlayerArenaLeave(int CID); // returns m_apOpponents-ID from Arena void EvaluateSpawnType(CSpawnEval *pEval, int Type, int CID); void PostReset(); void ResetGame() { m_ResetRequested = true; } bool m_ResetRequested; bool m_Paused; int m_Warmup; int m_NumPlayers; bool m_TourneyStarted; bool m_RoundRunning; // wether tees are fighting here class CPlayer* m_apOpponents[2]; enum { MAX_OPPONENTS = 2 }; }; #endif // TOURNDM_H
PancakeSoftware/openHabAI
catflow/cpp/include/server/ApiServer.h
/* * File: ApiServer */ #ifndef OPENHABAI_APISERVER_H #define OPENHABAI_APISERVER_H #include <util/Log.h> #include <string> using namespace std; struct PacketIdentifier; /** * Abstract class ApiServer * Interface for network communication of catflow * - implement this class to define your own network backend */ class ApiServer: protected Log { public: ApiServer() :Log("ApiServer"){} /** * start server non blocking */ virtual void start() = 0; /** * start server blocking */ virtual void startBlocking() = 0; /** * send packet to connected client * @param packet * @param destination * @param packetIdentifier call sendDone() on this object after send is complete */ virtual void send(Json packet, Client &destination, PacketIdentifier &packetIdentifier) = 0; virtual void sendBroadcast(Json packet) = 0; }; /** * identifier for client who send a request */ class Client { public: Client() {} virtual string toString() = 0; virtual bool operator<(const Client &other) const = 0; }; /** * dummy void client */ class VoidClient: public Client { public: virtual string toString() override { return "Void-dummy-client"; }; virtual bool operator<(const Client &other) const override { return true; }; }; #endif //OPENHABAI_APISERVER_H
PancakeSoftware/openHabAI
trainServer/source/include/NeuralNetwork.h
<filename>trainServer/source/include/NeuralNetwork.h<gh_stars>1-10 // // Created by joshua on 15.07.17. // #ifndef NeuralNetwork_H #define NeuralNetwork_H #include <mxnet-cpp/MxNetCpp.h> #include <thread> #include <string> #include <Catflow.h> #include <ApiRoute.h> #include <Chart.h> #include <util/TaskManager.h> using namespace std; using namespace mxnet::cpp; class DataStructure; class Catflow; class OperationNode; class NeuralNetwork : public ApiRouteJson { public: DataStructure &structure; int id; TaskId trainTaskId; string name, optimizerType = "sgd"; float learnrate = 0.005; float weightDecay = 0.01; float initUniformDistributionScale = 0.01; int x; int hiddenLayers, neuronsPerLayer; vector<OperationNode> modelDefinition; bool modelValid = false; /* Json keys */ void params() override { JsonObject::params(); param("name", name); param("id", id); param("hidden", hiddenLayers); param("neuronsPerHidden", neuronsPerLayer); param("learnRate", learnrate); param("weightDecay", weightDecay); param("initUniformScale", initUniformDistributionScale); param("optimizer", optimizerType); paramWithFunction("modelDefinition", [this](Json j) { setModelDefinition(j); }, [this]() { return modelDefinition;}); paramReadOnly("modelValid", modelValid); } static void init(Context *mxContext); NeuralNetwork(); NeuralNetwork(DataStructure *structure); NeuralNetwork(DataStructure *structure, Json params); ~NeuralNetwork(); void train(); void trainInNewThread(); void joinTrainThread(); static void shutdown(); void stopTrain(); /* * charts */ ApiRoute charts; ParameterChart chartNetworkOutput; SeriesChart chartNetworkProgress; private: map<std::string, NDArray> graphValues; vector<std::string> graphValueNames; Symbol symLossOut; static Context *ctx; thread *trainThread; int batchSize; int iteration = 0; bool trainEnable; void printSymbolShapes(map<string, NDArray> map1); // train Executor* exe{nullptr}; Optimizer *optimizer{nullptr}; vector<float> trainDataX; void setModelDefinition(vector<OperationNode> json); void graphBindIo(); }; class OperationNode: public JsonObject { public: string operation; string name; Json opParams; vector<int> inputNodes; vector<int> editorPosition; int index = -1; void params() override { param("operation", operation); param("name", name); param("params", opParams); param("inputNodes", inputNodes); param("editorPosition", editorPosition); //param("index", index); } template <class T = string> T getOpParam(string name) { auto el = opParams.find(name); if (el == opParams.end()) throw JsonObjectException("OperationNode's field 'opParams' missing member '"+name+"'"); return el->get<T>(); } }; #endif //NeuralNetwork_H
PancakeSoftware/openHabAI
catflow/cpp/include/JsonObject.h
<gh_stars>1-10 /* * File: JsonObject.h * Author: <NAME> */ #ifndef OPENHABAI_JSONOBJECT_H #define OPENHABAI_JSONOBJECT_H #include <stdlib.h> using namespace std; #include <util/Log.h> #include <json.hpp> #include <string> #include <list> #include <memory> #include <boost/any.hpp> #include <unordered_map> #include "ApiProcessible.h" #include "Util.h" #include "ApiSubscribable.h" #include <cstdarg> using Json = nlohmann::json; using namespace std; class AJsonParam { public: virtual Json toJson() const {}; virtual void fromJson(Json j) {}; virtual bool isPrimitive(){ return true; }; /** * called when param change, before new value is applied to class member * -> you can compare old and new value */ void onChange(function<void ()> callback) {this->onChanceFunc = callback;}; /** * called after params change, after new value is applied to class member */ void onChanged(function<void ()> callback) {this->onChancedFunc = callback;}; /** * make param read only */ AJsonParam& readOnly() { _writable = false; return *this; }; /** * make param write only */ AJsonParam& writeOnly() { _readable = false; return *this; }; /** * make param non save changes in .json file */ AJsonParam& nonSave() { _savable = false; return *this; }; /** * make param hidden, value only visible on changes * @warning not implemented */ AJsonParam& hidden() { _hidden = true; return *this; }; function<void ()> onChanceFunc = nullptr; function<void ()> onChancedFunc = nullptr; bool _readable = true; bool _writable = true; bool _savable = true; bool _hidden = false; }; namespace internal { template <class T> class JsonParam: public AJsonParam{ public: T* valuePtr; string key; JsonParam(T &value, string key) { this->valuePtr = &value; this->key = key; // cout << "[JsonParam] ("<< key << ": " << ") " <<"create: "<< counter << endl; } Json toJson() const override { //cout << "[JsonParam] toJson() "<< key << ": " << static_cast<void*>(valuePtr) << endl; return Json(*valuePtr); } void fromJson(Json j) override; ~JsonParam() { //cout << "[JsonParam] ("<< key << ": " << ") " <<"delete: "<< counter << endl; } bool isPrimitive() override; }; template <class T> class JsonParamReadOnly: public AJsonParam{ public: T* valuePtr; string key; JsonParamReadOnly(T &value, string key) { this->valuePtr = &value; this->key = key; readOnly(); } Json toJson() const override { return Json(*valuePtr); } void fromJson(Json j) override { throw JsonObjectException("can't set '"+key+"' because it is readonly"); } bool isPrimitive() override; }; class JsonParamFunction: public AJsonParam{ public: function<void (Json)> onSet; function<Json ()> onGet; JsonParamFunction(function<void (Json)> onSet, function<Json ()> onGet, string key) {this->onGet = onGet; this->onSet = onSet;} Json toJson() const override { return onGet(); } void fromJson(Json j) override { onSet(j); } }; } class JsonObject { public: /** * @return configured class attributes as json * @param onlySavableParams skip all params that are marked as nonSave() * @param skipHiddenParams skip all params that are maked as hidden() * @see JsonObject::params() */ virtual Json toJson(bool onlySavableParams = false, bool skipHiddenParams = true) const { /* refresh param pointers * this is very inefficient but necessary (rebuild whole param list): * when the object is copied all param pointers have to be redefined (change pointer address) */ refreshParams(); Json json; for (auto &paramPtr: paramPointers) { const auto& key = paramPtr.first; const auto& memberPtr = paramPtr.second; if ((!onlySavableParams || memberPtr->_savable) && (!skipHiddenParams || !memberPtr->_hidden) && memberPtr->_readable) json[key] = memberPtr->toJson(); } return json; }; /** * @return configured class attributes as json, but only params that match a string in params parameter * @see JsonObject::params() * @param params only this params converted to json */ virtual Json toJson(vector<string> params) const { refreshParams(); Json json; for (auto &paramPtr: paramPointers) { const auto& key = paramPtr.first; const auto& memberPtr = paramPtr.second; if (find(params.begin(), params.end(), key) != params.end()) // if key in params if (memberPtr->_readable) json[key] = memberPtr->toJson(); } return json; } /** * @param params set configured class attributes to values in params * @see JsonObject::params() * @return vector of changed param names */ virtual vector<string> fromJson(Json params, bool catchParameterErrors = false) { /* refresh param pointers * this is very inefficient but necessary (rebuild whole param list): * when the object is copied all param pointers have to be redefined (change pointer address) */ refreshParams(); vector<string> willChange; vector<string> changed; // filter existing keys @TODO less redundant for (auto &paramPtr: paramPointers) { const auto &key = paramPtr.first; const auto &memberPtr = paramPtr.second; if (params.find(key) == params.end() && memberPtr->isPrimitive()) continue; willChange.push_back(key); if (memberPtr->onChanceFunc != nullptr) memberPtr->onChanceFunc(); } onParamsChange(willChange); for (auto &paramPtr: paramPointers) { const auto &key = paramPtr.first; const auto &memberPtr = paramPtr.second; if (params.find(key) == params.end()) continue; try { if (!memberPtr->_writable) throw JsonObjectException("can't set '"+key+"' because it is readonly"); //cout << "=fromJson= param " << key << ": " << params[key].dump() << endl; memberPtr->fromJson(params[key]); if (memberPtr->isPrimitive()) { changed.push_back(key); if (memberPtr->onChancedFunc != nullptr) memberPtr->onChancedFunc(); } } catch (Json::type_error &e) { l.err("can't set jsonObject key '" + key +"' : " + e.what()); if (!catchParameterErrors) throw JsonObjectException("can't set jsonObject key '" + key +"' because of wrong type : " + e.what()); } catch (JsonObjectException &e) { if (!catchParameterErrors) throw JsonObjectException("can't set jsonObject key '" + key +"' because of JsonObjectException : " + e.what()); else l.err("can't set jsonObject key '" + key +"' because of JsonObjectException : " + e.what()); } } onParamsChanged(changed); return changed; }; /** * links json key with class member's value * @warning use this function only inside your implementation of defineParams() ! * @see defineParams() */ template <class T> AJsonParam& param(string key, T &value) { auto param = make_shared<internal::JsonParam<T>>(value, key); paramPointers.emplace(key, param); // unique_ptr -> deletes JsonParam when JsonObject is deleted return *param; } /** * links json key with class member's value * @note this param is only readable * @warning use this function only inside your implementation of defineParams() ! * @see defineParams() */ template <class T> AJsonParam& paramReadOnly(string key, T &value) { auto param = make_shared<internal::JsonParamReadOnly<T>>(value, key); paramPointers.emplace(key, param); // unique_ptr -> deletes JsonParam when JsonObject is deleted return *param; } /** * links json key with getter and setter function * @warning use this function only inside your implementation of defineParams() ! * @see defineParams() */ AJsonParam& paramWithFunction(string key, function<void (Json)> onSet, function<Json ()> onGet) { auto param = make_shared<internal::JsonParamFunction>(onSet, onGet, key); paramPointers.emplace(key, param); // unique_ptr -> deletes JsonParam when JsonObject is deleted return *param; } /** * define json params * use function param() only inside this function! */ virtual void params() { }; /** * called when params change, before new value is applied to class member * -> you can compare old and new value * @param params the changed params */ virtual void onParamsChange(vector<string> params) {}; /** * called after params change, after new value is applied to class member * @param params the changed params */ virtual void onParamsChanged(vector<string> params) {}; ~JsonObject() { paramPointers.clear(); } private: map<string, shared_ptr<AJsonParam>> paramPointers; static Log l; void refreshParams() const { auto t = const_cast<JsonObject*>( this ); t->paramPointers.clear(); t->params(); } }; static void to_json(Json& j, const JsonObject& p) { j = p.toJson(); } static void from_json(const Json& j, JsonObject& p) { p.fromJson(j); } #include "../source/JsonObject.tpp" #endif //OPENHABAI_JSONOBJECT_H
PancakeSoftware/openHabAI
trainServer/source/include/Settings.h
<reponame>PancakeSoftware/openHabAI // // Created by <NAME> on 29.05.18. // #ifndef OPENHABAI_SETTINGS_H #define OPENHABAI_SETTINGS_H #include <string> #include <ApiJsonObject.h> #include <util/TaskManager.h> #include "SelectorView.h" using namespace std; class Settings : public ApiJsonObject { public: int trainRefreshRate{1000}; // The rate of how often the terminal will output the learn Progress SelectorView logLevel; // The level of log SelectorView computingTarget; // Where the computation should run (CPU/GPU) SelectorView showConsole; // show network console in frontend Settings() : computingTarget({ "CPU", "GPU" }), logLevel({"all", "trace", "info", "debug", "ok", "warning", "error", "fatal"}), showConsole({"show", "hide"}) { setLogName("Settings"); addAction("stopServer", [this](ApiRequest request) { info("Stopping server..."); TaskManager::stop(); // stop app return new ApiRespondOk(request); }); logLevel.onSelectionChange([&](vector<bool> values, vector<bool> changedValues) { setLogFilter(values); }); } private: void params() override { JsonObject::params(); param("trainRefreshRate", trainRefreshRate); param("computingTarget", computingTarget); param("logLevel", logLevel); param("showConsole", showConsole); } void setLogFilter(vector<bool> values) { int index = 1; // ALL (Standard) for (int i = 0; i < values.size(); i++) { if (values[i]) { index = i; break; } } info("set log level to: " + to_string(index)); switch (index) { case 0: Log::setLogLevel(Log::LOG_LEVEL_ALL); break; case 1: Log::setLogLevel(Log::LOG_LEVEL_TRACE); break; case 2: Log::setLogLevel(Log::LOG_LEVEL_INFORMATION); break; case 3: Log::setLogLevel(Log::LOG_LEVEL_DEBUG); break; case 4: Log::setLogLevel(Log::LOG_LEVEL_OK); break; case 5: Log::setLogLevel(Log::LOG_LEVEL_WARNING); break; case 6: Log::setLogLevel(Log::LOG_LEVEL_ERROR); break; case 7: Log::setLogLevel(Log::LOG_LEVEL_FATAL); break; default: Log::setLogLevel(Log::LOG_LEVEL_ALL); break; } } }; #endif //OPENHABAI_SETTINGS_H
PancakeSoftware/openHabAI
catflow/cpp/include/util/TaskManager.h
<reponame>PancakeSoftware/openHabAI /* * File: TaskManager.h * Author: <NAME> * */ #ifndef OPENHABAI_TASKMANAGER_H #define OPENHABAI_TASKMANAGER_H #include <functional> #include <list> #include <mutex> #include <condition_variable> #include "Log.h" using namespace std; class TaskId { public: TaskId(): isValidV(false) { } TaskId(list<function<void()>>::iterator iteratorV): iterator(iteratorV), isValidV(true){ } bool isValid() { return isValidV; } void setValid(bool valid) { this->isValidV = valid; } list<function<void()>>::iterator getIterator() { return iterator; } private: bool isValidV; list<function<void()>>::iterator iterator; }; /* * TaskManager class * add tasks to execute in main thread */ class TaskManager { public: /** * start executing tasks * @note this function is blocking */ static void start(); /** * stops blocking of start() */ static void stop(); /** * adds task that is executed repeating, endless * @param task task to execute * @param id */ static TaskId addTaskRepeating(function<void ()> task); /** * stops and removes repeating task * sets taskId.isValid to false when task has been removed * @param taskId * @return if task existed */ static bool removeTaskRepeating(TaskId &taskId); static bool containsTaskRepeating(TaskId &taskId); /** * adds task that is executed only once * @param task task to execute * @param id */ static void addTaskOnceOnly(function<void ()> task, void *id); static bool containsTaskOnceOnly(void *id); private: static Log l; static list<TaskId*> tasksRepeatingToRemove; static list<function<void ()>> tasksRepeating; static list<pair<void *, function<void ()>>> tasksOnceOnly; static mutex threadMutex; static condition_variable threadLockCondition; /* * if equals false start() will stop blocking */ static bool running; }; #endif //OPENHABAI_TASKMANAGER_H
PancakeSoftware/openHabAI
catflow/cpp/include/ApiMessage.h
<reponame>PancakeSoftware/openHabAI<filename>catflow/cpp/include/ApiMessage.h /* * File: ApiMessage.h * Author: <NAME> * */ #ifndef OPENHABAI_APIMESSAGE_H #define OPENHABAI_APIMESSAGE_H #include <json.hpp> #include <string> #include <arpa/inet.h> using Json = nlohmann::json; using namespace std; class Client; /** * parses route * /courses/0/students/1/ becomes to vector [courses, 0, students, 1] */ class ApiMessageRoute { public: string pathPrefix; // for storing objects, has to end with / vector<string> route; vector<string> routeAbsolute; // not effected by pop and push ApiMessageRoute() = default; ApiMessageRoute(string routeUrl) { fromString(routeUrl); } void fromString(string routeUrl) { route.clear(); istringstream ss(routeUrl); string token; while (std::getline(ss, token, '/')) { if (token.length() == 0) continue; route.push_back(token); } routeAbsolute = route; } string toString() const { string out = "/"; for (string token: route) out += token + "/"; return out; } string toStringAbsolute() const { string out = "/"; for (string token: routeAbsolute) out += token + "/"; return out; } /** * @return toSting with pathPrefix before */ string toStringStorePath() const { if (pathPrefix.empty()) return "." + toString(); else { if (pathPrefix.back() == '/') return pathPrefix.substr(0, pathPrefix.size()-1) + toString(); else return pathPrefix + toString(); } } /** * pushes element to end route * @param token not allowed to contain '/' */ void push(string token) { route.push_back(token); } /** * pops first element of route * @return */ string pop() { if (route.empty()) return ""; string token(route.front().c_str()); route.erase(route.begin()); return token; } bool isEmpty() { return route.empty(); } }; class ApiMessage { public: virtual Json toJson() { return Json(); }; }; /** * @param route route list, defines something similar to rest url * @param what defines action to perform, allowed values depend on route * @param data contains data that is necessary to perform action */ class ApiRequest: public ApiMessage { public: ApiMessageRoute route; string what; Json data; int respondId = -1; Client *client = nullptr; ApiRequest() = default; ApiRequest(ApiMessageRoute route, string what) { this->route = route; this->what = what; } ApiRequest(ApiMessageRoute route, string what, Json data) { this->route = route; this->what = what; this->data = data; } ApiRequest(ApiMessageRoute route, string what, Json data, int respondId) { this->route = route; this->what = what; this->data = data; this->respondId = respondId; } ApiRequest(string route, string what) : ApiRequest(ApiMessageRoute(route), what) {} ApiRequest(string route, string what, Json data) : ApiRequest(ApiMessageRoute(route), what, data) {} ApiRequest(string route, string what, Json data, int respondId) : ApiRequest(ApiMessageRoute(route), what, data, respondId) {} Json toJson() override { // @TODO route.toString in Request.toString string r = route.toString().size() <= 1 ? route.toStringAbsolute() : route.toString(); if (respondId >= 0) return Json { {"type", "request"}, {"route", r}, {"what", what}, {"data", data}, {"respondId", respondId} }; else return Json { {"type", "request"}, {"route", r}, {"what", what}, {"data", data} }; } }; class ApiRespond: public ApiMessage { public: string what; Json data; int respondId = -1; ApiRequest request; bool requestValid = false; ApiRespond() {} ApiRespond(ApiRequest request) { requestValid = true; this->request = request; this->respondId = request.respondId; } virtual Json toJson() override { return Json { {"type", "respond"}, {"what", what}, {"data", data}, {"respondId", respondId} }; } ~ApiRespond() { //if (request != nullptr) // delete request; } }; class ApiRespondError : public ApiRespond { public: ApiRespondError(string error) { this->data = Json{{"message", error}}; this->what = "error"; } ApiRespondError(string error, ApiMessageRoute route) : ApiRespond(request) { this->data.update(Json{{"route", route.toString()}}); } ApiRespondError(string error, ApiRequest request) : ApiRespond(request) { if (request.respondId < 0) this->data = Json{{"message", error},{"request", request.toJson()}}; else this->data = Json{{"message", error}, {"route", request.route.toStringAbsolute()}}; this->what = "error"; } ApiRespondError(string error, ApiRequest request, ApiMessageRoute route) : ApiRespondError(error, request) { this->data.update(Json{{"route", route.toString()}}); } ApiRespondError(string error, Json request) { this->data = Json{{"message", error},{"request", request}}; this->what = "error"; } }; class ApiRespondOk : public ApiRespond { public: ApiRespondOk(ApiRequest request) : ApiRespond(request) { this->data = nullptr; this->what = "ok"; } ApiRespondOk(Json data, ApiRequest request) : ApiRespond(request) { this->data = data; this->what = "ok"; } }; #endif //OPENHABAI_APIMESSAGE_H
PancakeSoftware/openHabAI
trainServer/source/include/dataStructures/DataStructure.h
/* * File: DataStructure.h * Author: <NAME> * */ #ifndef DATASTRUCTURE_H #define DATASTRUCTURE_H #include <json.hpp> #include <string> #include <ApiJsonObject.h> #include <JsonList.h> #include <ApiRoute.h> #include <util/util.h> #include "NeuralNetwork.h" using namespace std; /* * DataStructure class * provides/generates training data */ class DataStructure : public ApiRouteJson { public: int id; string name; string type; map<int, string> inputNames; map<int, string> outputNames; ParameterChart dataChart; JsonList<NeuralNetwork> networks; /* Json keys */ void params() override; DataStructure(); /** * because this is type and its child classes, of list * a virtual destructor is needed */ virtual ~DataStructure() = default; static DataStructure * create(Json params); // create right structure type by param 'type' inline bool operator == (int other) const; inline bool operator == (const DataStructure &other) const; /** * get data-batch (list of (input Values - output Values) pairs) * @param indexBegin first data-record index * @param indexEnd last data-record index * @return [ [one data-record: [inputValues: ], [outputValues]], * ...] * @note less effective because copy is made */ virtual vector<pair<vector<float>, vector<float>>> getDataBatch(int indexBegin, int indexEnd) { if ((indexBegin>= 0) && (indexBegin <= (getDataBatchIndices())) && (indexEnd <= (getDataBatchIndices())) && (indexBegin <= indexEnd)) return vector<pair<vector<float>, vector<float>>>(data.begin()+indexBegin, data.begin()+indexEnd); else { err("at getDataBatch(): indexBegin, indexEnd are not in range of " + to_string(getDataBatchIndices()) + " data-records"); return vector<pair<vector<float>, vector<float>>>(); } }; /** * get data-batch (list of (input Values - output Values) pairs) * @return [ [one data-record: [inputValues: ], [outputValues]], * ...] */ virtual vector<pair<vector<float>, vector<float>>>& getDataBatch() { return data; }; /** * get amount of data-records * -> index can be passed into getDataBatch(index) * @return max index of data-record */ virtual int getDataBatchIndices() { return data.size(); }; protected: vector<pair<vector<float>, vector<float>>> data; }; /* * Function DataStructure class */ class FunctionDataStructure : public DataStructure { public: string function; vector<RangeParam> inputRanges; /* Json keys */ void params() override { DataStructure::params(); param("function", function); param("inputRanges", inputRanges); } FunctionDataStructure(); void onParamsChanged(vector<string> params) override; }; #endif //DATASTRUCTURE_H