Add Emscripten example

This commit is contained in:
Alexander Popov 2024-01-27 23:59:02 +03:00
parent 2b3606c758
commit 362bbed6bd
Signed by: iiiypuk
GPG Key ID: E47FE0AB36CD5ED6
8 changed files with 503 additions and 0 deletions

View File

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

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();
}