Compare commits

...

2 Commits

Author SHA1 Message Date
Alexander Popov 362bbed6bd
Add Emscripten example 2024-01-27 23:59:02 +03:00
Alexander Popov 2b3606c758
Add `nuklear` example 2024-01-27 23:54:37 +03:00
11 changed files with 655 additions and 0 deletions

View File

@ -1,4 +1,6 @@
# Примеры кода, алгоритмов и библиотек на Си (C++)
- [rxi/log](rxi/log) — ...
- [nuklear] — Пример простого окна на GLFW3 и Nuklear (WIP)
- [CppLinuxSerial](communication/cpp_linux_serial) — Библиотека для работы с Serial в связке с Arduino
- [sdl_emscripten] — Пример использования emscripten и SDL (WIP)

6
nuklear/.gitignore vendored Normal file
View File

@ -0,0 +1,6 @@
test
*.ttf
nuklear_glfw_gl2.h
stb_image.h
canvas.c

16
nuklear/Makefile Normal file
View File

@ -0,0 +1,16 @@
PROGRAM = test
CC = gcc
CFLAGS = -std=c99 -Wall -O2
CFLAGS += -I/home/user/Git/Nuklear
LDFLAGS =
LIBS = -lglfw -lGL -lm -lGLU
.PHONY: $(PROGRAM)
all: $(PROGRAM)
$(PROGRAM):
$(CC) $(CFLAGS) -o $@ main.c $(LIBS)
clean:
rm -f $(PROGRAM)

130
nuklear/main.c Normal file
View File

@ -0,0 +1,130 @@
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdarg.h>
#include <string.h>
#include <math.h>
#include <assert.h>
#include <limits.h>
#include <time.h>
#include <GLFW/glfw3.h>
#define NK_INCLUDE_FIXED_TYPES
#define NK_INCLUDE_STANDARD_IO
#define NK_INCLUDE_STANDARD_VARARGS
#define NK_INCLUDE_DEFAULT_ALLOCATOR
#define NK_INCLUDE_VERTEX_BUFFER_OUTPUT
#define NK_INCLUDE_FONT_BAKING
#define NK_INCLUDE_DEFAULT_FONT
#define NK_IMPLEMENTATION
#define NK_GLFW_GL2_IMPLEMENTATION
#define NK_KEYSTATE_BASED_INPUT
#include <nuklear.h>
#include "nuklear_glfw_gl2.h"
#define WINDOW_WIDTH 230
#define WINDOW_HEIGHT 250
static void error_callback(int e, const char *d) {
printf("Error %d: %s\n", e, d);
}
int main(void) {
/* Platform */
static GLFWwindow *win;
int width = 0, height = 0;
/* GUI */
struct nk_context *ctx;
struct nk_colorf bg;
/* GLFW */
glfwSetErrorCallback(error_callback);
if (!glfwInit()) {
fprintf(stdout, "[GFLW] failed to init!\n");
exit(1);
}
win = glfwCreateWindow(WINDOW_WIDTH, WINDOW_HEIGHT, "Demo", NULL, NULL);
glfwMakeContextCurrent(win);
glfwGetWindowSize(win, &width, &height);
/* GUI */
ctx = nk_glfw3_init(win, NK_GLFW3_INSTALL_CALLBACKS);
/* Load Fonts: if none of these are loaded a default font will be used */
/* Load Cursor: if you uncomment cursor loading please hide the cursor */
{
struct nk_font_atlas *atlas;
nk_glfw3_font_stash_begin(&atlas);
/*struct nk_font *droid = nk_font_atlas_add_from_file(atlas,
* "../../../extra_font/DroidSans.ttf", 14, 0);*/
/*struct nk_font *roboto = nk_font_atlas_add_from_file(atlas,
* "../../../extra_font/Roboto-Regular.ttf", 14, 0);*/
/*struct nk_font *future = nk_font_atlas_add_from_file(atlas,
* "../../../extra_font/kenvector_future_thin.ttf", 13, 0);*/
/*struct nk_font *clean = nk_font_atlas_add_from_file(atlas,
* "../../../extra_font/ProggyClean.ttf", 12, 0);*/
/*struct nk_font *tiny = nk_font_atlas_add_from_file(atlas,
* "../../../extra_font/ProggyTiny.ttf", 10, 0);*/
nk_rune ranges_latin[] = {
0x0020, 0x007E, /* Ascii */
0x00A1, 0x00FF, /* Symbols + Umlaute */
0x0410, 0x044F, /* Main Cyrillic */
0
};
struct nk_font_config cfg_japan = nk_font_config(0);
cfg_japan.range = ranges_latin;
struct nk_font *compassgold_font = nk_font_atlas_add_from_file(atlas, "Ubuntu-R.ttf", 18, 0, &cfg_japanm );
nk_style_set_font(ctx, &compassgold_font->handle);
nk_glfw3_font_stash_end();
}
bg.r = 0.10f, bg.g = 0.18f, bg.b = 0.24f, bg.a = 1.0f;
while (!glfwWindowShouldClose(win)) {
/* Input */
glfwPollEvents();
nk_glfw3_new_frame();
/* GUI */
if (nk_begin(ctx, "Demo", nk_rect(0, 0, 230, 250), NK_WINDOW_BORDER)) {
enum { EASY, HARD };
static int op = EASY;
static char text[1][64];
static int text_len[3];
nk_layout_row_static(ctx, 30, 80, 1);
nk_label(ctx, "Введите URL", NK_TEXT_CENTERED);
nk_edit_string(ctx, NK_EDIT_FIELD, text[0], &text_len[2], 64, nk_filter_default);
if (nk_button_label(ctx, "button"))
fprintf(stdout, "button pressed\n");
nk_layout_row_dynamic(ctx, 30, 2);
if (nk_option_label(ctx, "easy", op == EASY))
op = EASY;
if (nk_option_label(ctx, "hard", op == HARD))
op = HARD;
}
nk_end(ctx);
/* Draw */
glfwGetWindowSize(win, &width, &height);
glViewport(0, 0, width, height);
glClear(GL_COLOR_BUFFER_BIT);
glClearColor(bg.r, bg.g, bg.b, bg.a);
/* IMPORTANT: `nk_glfw_render` modifies some global OpenGL state
* with blending, scissor, face culling and depth test and defaults
* everything back into a default state. Make sure to either save and
* restore or reset your own state after drawing rendering the UI. */
nk_glfw3_render(NK_ANTI_ALIASING_ON);
glfwSwapBuffers(win);
}
nk_glfw3_shutdown();
glfwTerminate();
return 0;
}

7
sdl_emscripten/.gitignore vendored Normal file
View File

@ -0,0 +1,7 @@
game
*.out.*
*.png
html/
index.html
index.js
index.wasm

22
sdl_emscripten/Makefile Normal file
View File

@ -0,0 +1,22 @@
PROGRAM = game
OBJ = main.o
CC = gcc
CC_WASM = /home/user/Git/emsdk/upstream/emscripten/emcc
CFLAGS = -O2 -g
LFLAGS = $(shell pkg-config --libs SDL2_image)
.PHONY: html
all: $(PROGRAM)
$(PROGRAM): $(OBJ)
$(CC) $(CFLAGS) -o $@ $(OBJ) $(LFLAGS)
main.o:
$(CC) $(CFLAGS) -c $(shell pkg-config --cflags sdl2) -o $@ main.c
html:
$(CC_WASM) -O2 -sUSE_SDL=2 -sUSE_SDL_IMAGE=2 -sSDL2_IMAGE_FORMATS=' ["png"]' -sUSE_SDL_TTF=2 main.c -o html/index.html --shell-file shell.html
clean:
rm -f $(OBJ) $(PROGRAM) html/*

44
sdl_emscripten/abc.c Normal file
View File

@ -0,0 +1,44 @@
#include <SDL2/SDL.h>
int main(int argc, char **argv) {
SDL_Init(SDL_INIT_VIDEO);
SDL_Window *window = NULL;
window =
SDL_CreateWindow("Jeu de la vie", SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED, 640, 480, SDL_WINDOW_SHOWN);
// Setup renderer
SDL_Renderer *renderer = NULL;
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
// Set render color to red ( background will be rendered in this color )
SDL_SetRenderDrawColor(renderer, 255, 0, 0, 255);
// Clear winow
SDL_RenderClear(renderer);
// Creat a rect at pos ( 50, 50 ) that's 50 pixels wide and 50 pixels high.
SDL_Rect r;
r.x = 50;
r.y = 50;
r.w = 50;
r.h = 50;
// Set render color to blue ( rect will be rendered in this color )
SDL_SetRenderDrawColor(renderer, 0, 0, 255, 255);
// Render rect
SDL_RenderFillRect(renderer, &r);
// Render the rect to the screen
SDL_RenderPresent(renderer);
// Wait for 5 sec
SDL_Delay(5000);
SDL_DestroyWindow(window);
SDL_Quit();
return EXIT_SUCCESS;
}

205
sdl_emscripten/main.c Normal file
View File

@ -0,0 +1,205 @@
#include <stdio.h>
#include <assert.h>
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#ifdef __EMSCRIPTEN__
#include <emscripten.h>
#endif
const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;
int main(int argc, char **argv) {
if (SDL_Init(SDL_INIT_VIDEO) != 0) {
printf("error initializing SDL: %s\n", SDL_GetError());
return 1;
}
SDL_Window *window = NULL;
window =
SDL_CreateWindow("Hello, SDL 2!", SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH, SCREEN_HEIGHT, 0);
if (window == NULL) {
return 1;
}
SDL_Renderer* renderer = NULL;
renderer = SDL_CreateRenderer( window, -1, SDL_RENDERER_ACCELERATED);
SDL_SetRenderDrawColor( renderer, 255, 0, 0, 255 );
SDL_RenderClear( renderer );
SDL_Rect dest;
dest.w= 50;
dest.h= 50;
dest.x = 10;
dest.y = 10;
SDL_SetRenderDrawColor( renderer, 0, 0, 255, 255 );
SDL_RenderFillRect( renderer, &dest );
// SDL_Surface *image = IMG_Load("girl_faces.png");
// if (!image) {
// printf("IMG_Load: %s\n", IMG_GetError());
// return 0;
// }
// SDL_Texture *tex = SDL_CreateTextureFromSurface(rend, image);
// SDL_FreeSurface(image);
// SDL_QueryTexture(tex, NULL, NULL, &dest.w, &dest.h);
// SDL_RenderClear(rend);
// SDL_RenderCopy(rend, tex, NULL, &dest);
SDL_RenderPresent(renderer);
SDL_Delay(2000);
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
// printf("hello, world!\n");
// puts("0");
// if (SDL_Init(SDL_INIT_EVERYTHING) != 0) {
// printf("error initializing SDL: %s\n", SDL_GetError());
// return 1;
// }
// SDL_Surface *screen_surface = NULL;
// SDL_Window *window = NULL;
// puts("1");
// window =
// SDL_CreateWindow("Hello, SDL 2!", SDL_WINDOWPOS_CENTERED,
// SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH, SCREEN_HEIGHT,
// 0);
// if (window == NULL) {
// return 1;
// }
// Uint32 render_flags = SDL_RENDERER_ACCELERATED;
// // creates a renderer to render our images
// SDL_Renderer* rend = SDL_CreateRenderer(window, -1, render_flags);
// screen_surface = SDL_GetWindowSurface(window);
// // creates a surface to load an image into the main memory
// SDL_Surface *surface;
// // please provide a path for your image
// surface = IMG_Load("girl_faces.png");
// // loads image to our graphics hardware memory.
// SDL_Texture *tex = SDL_CreateTextureFromSurface(rend, surface);
// // clears main-memory
// SDL_FreeSurface(surface);
// // let us control our image position
// // so that we can move it with our keyboard.
// SDL_Rect dest;
// // connects our texture with dest to control position
// SDL_QueryTexture(tex, NULL, NULL, &dest.w, &dest.h);
// // adjust height and width of our image box.
// dest.w /= 6;
// dest.h /= 6;
// // sets initial x-position of object
// dest.x = (1000 - dest.w) / 2;
// // sets initial y-position of object
// dest.y = (1000 - dest.h) / 2;
// puts("13");
// // controls animation loop
// int close = 0;
// // speed of box
// int speed = 300;
// // animation loop
// while (!close) {
// SDL_Event event;
// // Events management
// while (SDL_PollEvent(&event)) {
// switch (event.type) {
// case SDL_QUIT:
// // handling of close button
// close = 1;
// break;
// case SDL_KEYDOWN:
// // keyboard API for key pressed
// switch (event.key.keysym.scancode) {
// case SDL_SCANCODE_ESCAPE:
// close = 1;
// break;
// case SDL_SCANCODE_W:
// case SDL_SCANCODE_UP:
// dest.y -= speed / 30;
// break;
// case SDL_SCANCODE_A:
// case SDL_SCANCODE_LEFT:
// dest.x -= speed / 30;
// break;
// case SDL_SCANCODE_S:
// case SDL_SCANCODE_DOWN:
// dest.y += speed / 30;
// break;
// case SDL_SCANCODE_D:
// case SDL_SCANCODE_RIGHT:
// dest.x += speed / 30;
// break;
// default:
// break;
// }
// }
// }
// // right boundary
// if (dest.x + dest.w > 1000)
// dest.x = 1000 - dest.w;
// // left boundary
// if (dest.x < 0)
// dest.x = 0;
// // bottom boundary
// if (dest.y + dest.h > 1000)
// dest.y = 1000 - dest.h;
// // upper boundary
// if (dest.y < 0)
// dest.y = 0;
// // clears the screen
// SDL_RenderClear(rend);
// SDL_RenderCopy(rend, tex, NULL, &dest);
// ///
// /// Section 4: SDL ttf and rendering text
// ///
// // triggers the double buffers
// // for multiple rendering
// SDL_RenderPresent(rend);
// // calculates to 60 fps
// SDL_Delay(1000 / 60);
// }
// SDL_Delay(2000);
// SDL_DestroyWindow(window);
// SDL_Quit();
}

142
sdl_emscripten/shell.html Normal file
View File

@ -0,0 +1,142 @@
<!doctype html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Emscripten-Generated Code</title>
<style>
.emscripten { padding-right: 0; margin-left: auto; margin-right: auto; display: block; }
textarea.emscripten { font-family: monospace; width: 80%; }
div.emscripten { text-align: center; }
div.emscripten_border { border: 1px solid black; }
/* the canvas *must not* have any border or padding, or mouse coords will be wrong */
canvas.emscripten { border: 0px none; background-color: black; }
.spinner {
height: 50px;
width: 50px;
margin: 0px auto;
-webkit-animation: rotation .8s linear infinite;
-moz-animation: rotation .8s linear infinite;
-o-animation: rotation .8s linear infinite;
animation: rotation 0.8s linear infinite;
border-left: 10px solid rgb(0,150,240);
border-right: 10px solid rgb(0,150,240);
border-bottom: 10px solid rgb(0,150,240);
border-top: 10px solid rgb(100,0,200);
border-radius: 100%;
background-color: rgb(200,100,250);
}
@-webkit-keyframes rotation {
from {-webkit-transform: rotate(0deg);}
to {-webkit-transform: rotate(360deg);}
}
@-moz-keyframes rotation {
from {-moz-transform: rotate(0deg);}
to {-moz-transform: rotate(360deg);}
}
@-o-keyframes rotation {
from {-o-transform: rotate(0deg);}
to {-o-transform: rotate(360deg);}
}
@keyframes rotation {
from {transform: rotate(0deg);}
to {transform: rotate(360deg);}
}
</style>
</head>
<body>
<figure style="overflow:visible;" id="spinner"><div class="spinner"></div><center style="margin-top:0.5em"><strong>emscripten</strong></center></figure>
<div class="emscripten" id="status">Downloading...</div>
<div class="emscripten">
<progress value="0" max="100" id="progress" hidden=1></progress>
</div>
<div>
<canvas class="emscripten" id="canvas" oncontextmenu="event.preventDefault()" tabindex=-1></canvas>
</div>
<div class="emscripten">
<input type="checkbox" id="resize">Resize canvas
<input type="checkbox" id="pointerLock" checked>Lock/hide mouse pointer
&nbsp;&nbsp;&nbsp;
<input type="button" value="Fullscreen" onclick="Module.requestFullscreen(document.getElementById('pointerLock').checked,
document.getElementById('resize').checked)">
</div>
<textarea class="emscripten" id="output" rows="8" style="display: none;"></textarea>
<script type='text/javascript'>
var statusElement = document.getElementById('status');
var progressElement = document.getElementById('progress');
var spinnerElement = document.getElementById('spinner');
var Module = {
print: (function() {
var element = document.getElementById('output');
if (element) element.value = ''; // clear browser cache
return function(text) {
if (arguments.length > 1) text = Array.prototype.slice.call(arguments).join(' ');
// These replacements are necessary if you render to raw HTML
//text = text.replace(/&/g, "&amp;");
//text = text.replace(/</g, "&lt;");
//text = text.replace(/>/g, "&gt;");
//text = text.replace('\n', '<br>', 'g');
console.log(text);
if (element) {
element.value += text + "\n";
element.scrollTop = element.scrollHeight; // focus on bottom
}
};
})(),
canvas: (() => {
var canvas = document.getElementById('canvas');
// As a default initial behavior, pop up an alert when webgl context is lost. To make your
// application robust, you may want to override this behavior before shipping!
// See http://www.khronos.org/registry/webgl/specs/latest/1.0/#5.15.2
canvas.addEventListener("webglcontextlost", (e) => { alert('WebGL context lost. You will need to reload the page.'); e.preventDefault(); }, false);
return canvas;
})(),
setStatus: (text) => {
if (!Module.setStatus.last) Module.setStatus.last = { time: Date.now(), text: '' };
if (text === Module.setStatus.last.text) return;
var m = text.match(/([^(]+)\((\d+(\.\d+)?)\/(\d+)\)/);
var now = Date.now();
if (m && now - Module.setStatus.last.time < 30) return; // if this is a progress update, skip it if too soon
Module.setStatus.last.time = now;
Module.setStatus.last.text = text;
if (m) {
text = m[1];
progressElement.value = parseInt(m[2])*100;
progressElement.max = parseInt(m[4])*100;
progressElement.hidden = false;
spinnerElement.hidden = false;
} else {
progressElement.value = null;
progressElement.max = null;
progressElement.hidden = true;
if (!text) spinnerElement.hidden = true;
}
statusElement.innerHTML = text;
},
totalDependencies: 0,
monitorRunDependencies: (left) => {
this.totalDependencies = Math.max(this.totalDependencies, left);
Module.setStatus(left ? 'Preparing... (' + (this.totalDependencies-left) + '/' + this.totalDependencies + ')' : 'All downloads complete.');
}
};
Module.setStatus('Downloading...');
window.onerror = () => {
Module.setStatus('Exception thrown, see JavaScript console');
spinnerElement.style.display = 'none';
Module.setStatus = (text) => {
if (text) console.error('[post-exception status] ' + text);
};
};
</script>
{{{ SCRIPT }}}
</body>
</html>

54
sdl_emscripten/simple.c Normal file
View File

@ -0,0 +1,54 @@
#include <stdbool.h>
#include <SDL2/SDL.h>
const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;
int main(int argc, char **args) {
if (SDL_Init(SDL_INIT_EVERYTHING) != 0) {
return 1;
}
SDL_Surface *screen_surface = NULL;
SDL_Window *window = NULL;
window = SDL_CreateWindow("Hello, SDL 2!", SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH,
SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
if (window == NULL) {
return 1;
}
screen_surface = SDL_GetWindowSurface(window);
SDL_FillRect(screen_surface, NULL,
SDL_MapRGB(screen_surface->format, 0, 255, 0));
SDL_UpdateWindowSurface(window);
SDL_Event e;
bool quit = false;
while (!quit) {
while (SDL_PollEvent(&e)) {
if (e.type == SDL_QUIT) {
quit = true;
}
if (e.type == SDL_KEYDOWN) {
quit = true;
}
if (e.type == SDL_MOUSEBUTTONDOWN) {
quit = true;
}
}
}
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
};

27
sdl_emscripten/simple2.c Normal file
View File

@ -0,0 +1,27 @@
#include <SDL2/SDL.h>
int main() {
SDL_Init(SDL_INIT_VIDEO);
SDL_Window *window;
SDL_Renderer *renderer;
SDL_CreateWindowAndRenderer(300, 300, 0, &window, &renderer);
SDL_SetRenderDrawColor(renderer, /* RGBA: green */ 0x00, 0x80, 0x00, 0xFF);
SDL_Rect rect = {.x = 10, .y = 10, .w = 150, .h = 100};
SDL_RenderFillRect(renderer, &rect);
SDL_RenderPresent(renderer);
while (1) {
SDL_Event event;
SDL_PollEvent(&event);
if (event.type == SDL_QUIT) {
break;
}
}
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
}