VPN termux about China.net
Friday, 30 October 2026
Sunday, 2 August 2026
Drought escape calcium
#include <SDL2/SDL.h>
#include <vector>
#include <cstdlib>
#include <ctime>
const int SCREEN_WIDTH = 800;
const int SCREEN_HEIGHT = 600;
// Struktura dla surowców (gnój i wapno)
struct Resource {
SDL_Rect rect;
int type; // 0 = gnój, 1 = wapno
};
int main(int argc, char* argv[]) {
if (SDL_Init(SDL_INIT_VIDEO) != 0) return 1;
SDL_Window* window = SDL_CreateWindow("Skarabeusz: Alchemik Pustyni", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
bool running = true;
SDL_Event e;
// Gracz - Skarabeusz
SDL_Rect player = { SCREEN_WIDTH / 2 - 25, SCREEN_HEIGHT / 6 - 25, 50, 50 };
// Surowce na planszy
std::vector<Resource> resources;
std::srand(std::time(nullptr));
for (int i = 0; i < 15; ++i) {
Resource res;
res.rect = { std::rand() % (SCREEN_WIDTH - 20), std::rand() % (SCREEN_HEIGHT - 20), 20, 20 };
res.type = std::rand() % 2; // 50% szans na gnój, 50% na wapno
resources.push_back(res);
}
int inventoryGnoj = 0;
int inventoryWapno = 0;
int waterLevel = 0; // Nasz cel: zdobyć wodę
bool isNight = false;
Uint32 lastTime = SDL_GetTicks();
// Główna pętla gry
while (running) {
// Czas gry (przełączanie dzień/noc)
Uint32 currentTime = SDL_GetTicks();
if (currentTime - lastTime > 5000) { // Co 5 sekund zmiana
isNight = !isNight;
lastTime = currentTime;
// Jeśli zaczyna się noc, przetwarzamy zebrane zasoby w wodę
if (isNight) {
if (inventoryGnoj >= 5 && inventoryWapno >= 3) {
waterLevel += 10; // Sukces!
SDL_Log("Noc alchemii! Woda zdobyta! Poziom wody: %d", waterLevel);
} else {
SDL_Log("Noc nieudana. Za mało zasobów (potrzeba 5 gnoju, 3 wapna).");
}
// Reset zapasów po nocy
inventoryGnoj = 0; inventoryWapno = 0;
}
}
while (SDL_PollEvent(&e) != 0) {
if (e.type == SDL_QUIT) running = false;
else if (!isNight && e.type == SDL_MOUSEMOTION) {
player.x = e.motion.x - (player.w / 2);
player.y = e.motion.y - (player.h / 2);
}
}
// Dzień: zbieranie zasobów
if (!isNight) {
for (size_t i = 0; i < resources.size(); ++i) {
if (SDL_HasIntersection(&player, &resources[i].rect)) {
if (resources[i].type == 0) inventoryGnoj++;
else inventoryWapno++;
// Usuń zebrany zasób i dodaj nowy w losowym miejscu
resources.erase(resources.begin() + i);
Resource newRes;
newRes.rect = { std::rand() % (SCREEN_WIDTH - 20), std::rand() % (SCREEN_HEIGHT - 20), 20, 20 };
newRes.type = std::rand() % 2;
resources.push_back(newRes);
break; // Unikaj problemów z iteratorem
}
}
}
// Renderowanie
if (isNight) {
// Noc: ciemno, chłodno (granatowe tło)
SDL_SetRenderDrawColor(renderer, 10, 10, 50, 255);
} else {
// Dzień: jasno, gorąco (żółto-piaskowe tło)
SDL_SetRenderDrawColor(renderer, 240, 230, 140, 255);
}
SDL_RenderClear(renderer);
// Rysuj zasoby (tylko w dzień)
if (!isNight) {
for (const auto& res : resources) {
if (res.type == 0) SDL_SetRenderDrawColor(renderer, 165, 42, 42, 255); // Gnój - brąz
else SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255); // Wapno - biel
SDL_RenderFillRect(renderer, &res.rect);
}
}
// Rysuj skarabeusza (ciemny kolor)
SDL_SetRenderDrawColor(renderer, 85, 107, 47, 255);
SDL_RenderFillRect(renderer, &player);
int boxSize = 20 + waterLevel;
SDL_Rect waterBox = { 50, 50, boxSize, boxSize };
// Rysujemy niebieski kwadrat wody
SDL_SetRenderDrawColor(renderer, 0, 191, 255, 255);
SDL_RenderFillRect(renderer, &waterBox);
// SDL_RenderPresent(renderer);
// Wskaźnik wody w norce (np. prostokąt w rogu)
SDL_Rect waterBar = { 10, 10, waterLevel * 2, 20 };
SDL_SetRenderDrawColor(renderer, 0, 191, 255, 255);
SDL_RenderFillRect(renderer, &waterBar);
SDL_RenderPresent(renderer);
}
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}
Thursday, 28 May 2026
Server C try this ♠️
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <netdb.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <sys/wait.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <dirent.h>
/*
gcc serv.c -o serv
./serv 9999
in chrome tolbar 127.0.0.1:9999
*/
/* C is not C++ use gcc*/
#define BUFSIZE 1024
void cerror(FILE *stream, char *cause, char *errno_str, char *shortmsg, char *longmsg) {
fprintf(stream, "HTTP/1.1 %s %s\nContent-type: text/html\n\n", errno_str, shortmsg);
fprintf(stream, "<html><body><h1>%s: %s</h1><p>%s: %s</p></body></html>", errno_str, shortmsg, longmsg, cause);
fflush(stream);
}
void serve_directory(FILE *stream, char *dirname) {
DIR *dir = opendir(dirname);
if (!dir) {
cerror(stream, dirname, "403", "Forbidden", "Cannot read directory");
return;
}
fprintf(stream, "HTTP/1.1 200 OK\nContent-type: text/html\n\n");
fprintf(stream, "<html><body><h1>Index of %s</h1><ul>", dirname);
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
if (entry->d_name[0] == '.') continue;
// ZAWSZE generujemy link z wiodącym "/"
// Jeśli jesteśmy w ".", link to /nazwa. Jeśli w "./katalog", link to /katalog/nazwa
if (strcmp(dirname, ".") == 0) {
fprintf(stream, "<li><a href=\"/%s\">%s</a></li>", entry->d_name, entry->d_name);
} else {
fprintf(stream, "<li><a href=\"%s/%s\">%s</a></li>", dirname + 1, entry->d_name, entry->d_name);
}
}
fprintf(stream, "</ul></body></html>");
fflush(stream);
closedir(dir);
}
int main(int argc, char **argv) {
int parentfd, childfd, portno, optval;
socklen_t clientlen;
struct sockaddr_in serveraddr, clientaddr;
FILE *stream;
char buf[BUFSIZE], method[BUFSIZE], uri[BUFSIZE], version[BUFSIZE];
char filename[BUFSIZE], filetype[BUFSIZE];
struct stat sbuf;
if (argc != 2) { fprintf(stderr, "usage: %s <port>\n", argv[0]); exit(1); }
portno = atoi(argv[1]);
parentfd = socket(AF_INET, SOCK_STREAM, 0);
optval = 1;
setsockopt(parentfd, SOL_SOCKET, SO_REUSEADDR, (const void *)&optval, sizeof(int));
bzero((char *)&serveraddr, sizeof(serveraddr));
serveraddr.sin_family = AF_INET;
serveraddr.sin_addr.s_addr = htonl(INADDR_ANY);
serveraddr.sin_port = htons((unsigned short)portno);
bind(parentfd, (struct sockaddr *)&serveraddr, sizeof(serveraddr));
listen(parentfd, 5);
while (1) {
clientlen = sizeof(clientaddr);
childfd = accept(parentfd, (struct sockaddr *)&clientaddr, &clientlen);
stream = fdopen(childfd, "r+");
if (fgets(buf, BUFSIZE, stream) == NULL) { fclose(stream); continue; }
sscanf(buf, "%s %s %s", method, uri, version);
while(strcmp(buf, "\r\n") && strcmp(buf, "\n")) { fgets(buf, BUFSIZE, stream); }
if (strcasecmp(method, "GET")) {
cerror(stream, method, "501", "Not Implemented", "Tiny does not implement this method");
} else {
strcpy(filename, ".");
strcat(filename, uri);
if (stat(filename, &sbuf) < 0) {
cerror(stream, filename, "404", "Not found", "Couldn't find this file");
} else if (S_ISDIR(sbuf.st_mode)) {
serve_directory(stream, filename);
} else {
if (strstr(filename, ".html")) strcpy(filetype, "text/html");
else strcpy(filetype, "text/plain");
fprintf(stream, "HTTP/1.1 200 OK\nServer: Tiny Web Server\nContent-length: %d\nContent-type: %s\n\n", (int)sbuf.st_size, filetype);
fflush(stream);
int fd = open(filename, O_RDONLY);
void *p = mmap(0, sbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
fwrite(p, 1, sbuf.st_size, stream);
munmap(p, sbuf.st_size);
close(fd);
}
}
fclose(stream);
}
}
Tuesday, 5 May 2026
Tiny.c 2026 V
/* * tiny.c - a minimal HTTP server that serves static and
* dynamic content with the GET method. Neither
* robust, secure, nor modular. Use for instructional
* purposes only.
* Dave O'Hallaron, Carnegie Mellon
*Compile:gcc tiny.c -o tiny
* usage: tiny <port>
* dynamic content with the GET method. Neither
* robust, secure, nor modular. Use for instructional
* purposes only.
* Dave O'Hallaron, Carnegie Mellon
*Compile:gcc tiny.c -o tiny
* usage: tiny <port>
*usage tiny 9999
*Open chrome 127.0.0.1:9999/tiny.c
*/
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h> /* Zawiera deklaracje bzero */
#include <netdb.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <sys/wait.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define BUFSIZE 1024
#define MAXERRS 16
extern char **environ; /* the environment */
/*
* error - wrapper for perror used for bad syscalls
*/
void error(char *msg) {
perror(msg);
exit(1);
}
/*
* cerror - returns an error message to the client
*/
void cerror(FILE *stream, char *cause, char *errno_str,
char *shortmsg, char *longmsg) {
fprintf(stream, "HTTP/1.1 %s %s\n", errno_str, shortmsg);
fprintf(stream, "Content-type: text/html\n");
fprintf(stream, "\n");
fprintf(stream, "<html><title>Tiny Error</title>");
fprintf(stream, "<body bgcolor=\"#ffffff\">\n");
fprintf(stream, "%s: %s\n", errno_str, shortmsg);
fprintf(stream, "<p>%s: %s\n", longmsg, cause);
fprintf(stream, "<hr><em>The Tiny Web server</em>\n");
}
int main(int argc, char **argv) {
/* variables for connection management */
int parentfd; /* parent socket */
int childfd; /* child socket */
int portno; /* port to listen on */
int clientlen; /* byte size of client's address */
struct hostent *hostp; /* client host info */
char *hostaddrp; /* dotted decimal host addr string */
int optval; /* flag value for setsockopt */
struct sockaddr_in serveraddr; /* server's addr */
struct sockaddr_in clientaddr; /* client addr */
/* variables for connection I/O */
FILE *stream; /* stream version of childfd */
char buf[BUFSIZE]; /* message buffer */
char method[BUFSIZE]; /* request method */
char uri[BUFSIZE]; /* request uri */
char version[BUFSIZE]; /* request method */
char filename[BUFSIZE];/* path derived from uri */
char filetype[BUFSIZE];/* path derived from uri */
char cgiargs[BUFSIZE]; /* cgi argument list */
char *p; /* temporary pointer */
int is_static; /* static request? */
struct stat sbuf; /* file status */
int fd; /* static content filedes */
int pid; /* process id from fork */
int wait_status; /* status from wait */
/* check command line args */
if (argc != 2) {
fprintf(stderr, "usage: %s <port>\n", argv[0]);
exit(1);
}
portno = atoi(argv[1]);
/* open socket descriptor */
parentfd = socket(AF_INET, SOCK_STREAM, 0);
if (parentfd < 0)
error("ERROR opening socket");
/* allows us to restart server immediately */
optval = 1;
setsockopt(parentfd, SOL_SOCKET, SO_REUSEADDR,
(const void *)&optval , sizeof(int));
/* bind port to socket */
bzero((char *) &serveraddr, sizeof(serveraddr));
serveraddr.sin_family = AF_INET;
serveraddr.sin_addr.s_addr = htonl(INADDR_ANY);
serveraddr.sin_port = htons((unsigned short)portno);
if (bind(parentfd, (struct sockaddr *) &serveraddr,
sizeof(serveraddr)) < 0)
error("ERROR on binding");
/* get us ready to accept connection requests */
if (listen(parentfd, 5) < 0) /* allow 5 requests to queue up */
error("ERROR on listen");
/* * main loop: wait for a connection request, parse HTTP,
* serve requested content, close connection.
*/
clientlen = sizeof(clientaddr);
while (1) {
/* wait for a connection request */
childfd = accept(parentfd, (struct sockaddr *) &clientaddr, &clientlen);
if (childfd < 0)
error("ERROR on accept");
/* determine who sent the message */
hostp = gethostbyaddr((const char *)&clientaddr.sin_addr.s_addr,
sizeof(clientaddr.sin_addr.s_addr), AF_INET);
if (hostp == NULL)
error("ERROR on gethostbyaddr");
hostaddrp = inet_ntoa(clientaddr.sin_addr);
if (hostaddrp == NULL)
error("ERROR on inet_ntoa\n");
/* open the child socket descriptor as a stream */
if ((stream = fdopen(childfd, "r+")) == NULL)
error("ERROR on fdopen");
/* get the HTTP request line */
fgets(buf, BUFSIZE, stream);
printf("%s", buf);
sscanf(buf, "%s %s %s\n", method, uri, version);
/* tiny only supports the GET method */
if (strcasecmp(method, "GET")) {
cerror(stream, method, "501", "Not Implemented",
"Tiny does not implement this method");
fclose(stream);
close(childfd);
continue;
}
/* read (and ignore) the HTTP headers */
fgets(buf, BUFSIZE, stream);
printf("%s", buf);
while(strcmp(buf, "\r\n")) {
fgets(buf, BUFSIZE, stream);
printf("%s", buf);
}
/* parse the uri [crufty] */
if (!strstr(uri, "cgi-bin")) { /* static content */
is_static = 1;
strcpy(cgiargs, "");
strcpy(filename, ".");
strcat(filename, uri);
if (uri[strlen(uri)-1] == '/')
strcat(filename, "/sdcard");
}
/* else {
is_static = 0;
p = strchr(uri, '?');
if (p) {
strcpy(cgiargs, p+1);
*p = '\0';
}*/
else {
strcpy(cgiargs, "");
}
strcpy(filename, ".");
strcat(filename, uri);
// }
/* make sure the file exists */
if (stat(filename, &sbuf) < 0) {
cerror(stream, filename, "404", "Not found",
"Tiny couldn't find this file");
fclose(stream);
close(childfd);
continue;
}
/* serve static content */
if (is_static) {
if (strstr(filename, ".html"))
strcpy(filetype, "text/html");
else if (strstr(filename, ".gif"))
strcpy(filetype, "image/gif");
else if (strstr(filename, ".jpg"))
strcpy(filetype, "image/jpg");
else
strcpy(filetype, "text/plain");
/* print response header */
fprintf(stream, "HTTP/1.1 200 OK\n");
fprintf(stream, "Server: Tiny Web Server\n");
fprintf(stream, "Content-length: %d\n", (int)sbuf.st_size);
fprintf(stream, "Content-type: %s\n", filetype);
fprintf(stream, "\r\n");
fflush(stream);
/* Use mmap to return arbitrary-sized response body */
fd = open(filename, O_RDONLY);
p = mmap(0, sbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
fwrite(p, 1, sbuf.st_size, stream);
munmap(p, sbuf.st_size);
}
/* serve dynamic content */
else {
/* make sure file is a regular executable file */
if (!(S_IFREG & sbuf.st_mode) || !(S_IXUSR & sbuf.st_mode)) {
cerror(stream, filename, "403", "Forbidden",
"You are not allow to access this item");
fclose(stream);
close(childfd);
continue;
}
/* a real server would set other CGI environ vars as well*/
setenv("QUERY_STRING", cgiargs, 1);
/* print first part of response header */
sprintf(buf, "HTTP/1.1 200 OK\n");
write(childfd, buf, strlen(buf));
sprintf(buf, "Server: Tiny Web Server\n");
write(childfd, buf, strlen(buf));
/* create and run the child CGI process so that all child
output to stdout and stderr goes back to the client via the
childfd socket descriptor */
pid = fork();
if (pid < 0) {
perror("ERROR in fork");
exit(1);
}
else if (pid > 0) { /* parent process */
wait(&wait_status);
}
else { /* child process*/
close(0); /* close stdin */
dup2(childfd, 1); /* map socket to stdout */
dup2(childfd, 2); /* map socket to stderr */
if (execve(filename, NULL, environ) < 0) {
perror("ERROR in execve");
}
}
}
/* clean up */
fclose(stream);
close(childfd);
}
}
*/
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h> /* Zawiera deklaracje bzero */
#include <netdb.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <sys/wait.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define BUFSIZE 1024
#define MAXERRS 16
extern char **environ; /* the environment */
/*
* error - wrapper for perror used for bad syscalls
*/
void error(char *msg) {
perror(msg);
exit(1);
}
/*
* cerror - returns an error message to the client
*/
void cerror(FILE *stream, char *cause, char *errno_str,
char *shortmsg, char *longmsg) {
fprintf(stream, "HTTP/1.1 %s %s\n", errno_str, shortmsg);
fprintf(stream, "Content-type: text/html\n");
fprintf(stream, "\n");
fprintf(stream, "<html><title>Tiny Error</title>");
fprintf(stream, "<body bgcolor=\"#ffffff\">\n");
fprintf(stream, "%s: %s\n", errno_str, shortmsg);
fprintf(stream, "<p>%s: %s\n", longmsg, cause);
fprintf(stream, "<hr><em>The Tiny Web server</em>\n");
}
int main(int argc, char **argv) {
/* variables for connection management */
int parentfd; /* parent socket */
int childfd; /* child socket */
int portno; /* port to listen on */
int clientlen; /* byte size of client's address */
struct hostent *hostp; /* client host info */
char *hostaddrp; /* dotted decimal host addr string */
int optval; /* flag value for setsockopt */
struct sockaddr_in serveraddr; /* server's addr */
struct sockaddr_in clientaddr; /* client addr */
/* variables for connection I/O */
FILE *stream; /* stream version of childfd */
char buf[BUFSIZE]; /* message buffer */
char method[BUFSIZE]; /* request method */
char uri[BUFSIZE]; /* request uri */
char version[BUFSIZE]; /* request method */
char filename[BUFSIZE];/* path derived from uri */
char filetype[BUFSIZE];/* path derived from uri */
char cgiargs[BUFSIZE]; /* cgi argument list */
char *p; /* temporary pointer */
int is_static; /* static request? */
struct stat sbuf; /* file status */
int fd; /* static content filedes */
int pid; /* process id from fork */
int wait_status; /* status from wait */
/* check command line args */
if (argc != 2) {
fprintf(stderr, "usage: %s <port>\n", argv[0]);
exit(1);
}
portno = atoi(argv[1]);
/* open socket descriptor */
parentfd = socket(AF_INET, SOCK_STREAM, 0);
if (parentfd < 0)
error("ERROR opening socket");
/* allows us to restart server immediately */
optval = 1;
setsockopt(parentfd, SOL_SOCKET, SO_REUSEADDR,
(const void *)&optval , sizeof(int));
/* bind port to socket */
bzero((char *) &serveraddr, sizeof(serveraddr));
serveraddr.sin_family = AF_INET;
serveraddr.sin_addr.s_addr = htonl(INADDR_ANY);
serveraddr.sin_port = htons((unsigned short)portno);
if (bind(parentfd, (struct sockaddr *) &serveraddr,
sizeof(serveraddr)) < 0)
error("ERROR on binding");
/* get us ready to accept connection requests */
if (listen(parentfd, 5) < 0) /* allow 5 requests to queue up */
error("ERROR on listen");
/* * main loop: wait for a connection request, parse HTTP,
* serve requested content, close connection.
*/
clientlen = sizeof(clientaddr);
while (1) {
/* wait for a connection request */
childfd = accept(parentfd, (struct sockaddr *) &clientaddr, &clientlen);
if (childfd < 0)
error("ERROR on accept");
/* determine who sent the message */
hostp = gethostbyaddr((const char *)&clientaddr.sin_addr.s_addr,
sizeof(clientaddr.sin_addr.s_addr), AF_INET);
if (hostp == NULL)
error("ERROR on gethostbyaddr");
hostaddrp = inet_ntoa(clientaddr.sin_addr);
if (hostaddrp == NULL)
error("ERROR on inet_ntoa\n");
/* open the child socket descriptor as a stream */
if ((stream = fdopen(childfd, "r+")) == NULL)
error("ERROR on fdopen");
/* get the HTTP request line */
fgets(buf, BUFSIZE, stream);
printf("%s", buf);
sscanf(buf, "%s %s %s\n", method, uri, version);
/* tiny only supports the GET method */
if (strcasecmp(method, "GET")) {
cerror(stream, method, "501", "Not Implemented",
"Tiny does not implement this method");
fclose(stream);
close(childfd);
continue;
}
/* read (and ignore) the HTTP headers */
fgets(buf, BUFSIZE, stream);
printf("%s", buf);
while(strcmp(buf, "\r\n")) {
fgets(buf, BUFSIZE, stream);
printf("%s", buf);
}
/* parse the uri [crufty] */
if (!strstr(uri, "cgi-bin")) { /* static content */
is_static = 1;
strcpy(cgiargs, "");
strcpy(filename, ".");
strcat(filename, uri);
if (uri[strlen(uri)-1] == '/')
strcat(filename, "/sdcard");
}
/* else {
is_static = 0;
p = strchr(uri, '?');
if (p) {
strcpy(cgiargs, p+1);
*p = '\0';
}*/
else {
strcpy(cgiargs, "");
}
strcpy(filename, ".");
strcat(filename, uri);
// }
/* make sure the file exists */
if (stat(filename, &sbuf) < 0) {
cerror(stream, filename, "404", "Not found",
"Tiny couldn't find this file");
fclose(stream);
close(childfd);
continue;
}
/* serve static content */
if (is_static) {
if (strstr(filename, ".html"))
strcpy(filetype, "text/html");
else if (strstr(filename, ".gif"))
strcpy(filetype, "image/gif");
else if (strstr(filename, ".jpg"))
strcpy(filetype, "image/jpg");
else
strcpy(filetype, "text/plain");
/* print response header */
fprintf(stream, "HTTP/1.1 200 OK\n");
fprintf(stream, "Server: Tiny Web Server\n");
fprintf(stream, "Content-length: %d\n", (int)sbuf.st_size);
fprintf(stream, "Content-type: %s\n", filetype);
fprintf(stream, "\r\n");
fflush(stream);
/* Use mmap to return arbitrary-sized response body */
fd = open(filename, O_RDONLY);
p = mmap(0, sbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
fwrite(p, 1, sbuf.st_size, stream);
munmap(p, sbuf.st_size);
}
/* serve dynamic content */
else {
/* make sure file is a regular executable file */
if (!(S_IFREG & sbuf.st_mode) || !(S_IXUSR & sbuf.st_mode)) {
cerror(stream, filename, "403", "Forbidden",
"You are not allow to access this item");
fclose(stream);
close(childfd);
continue;
}
/* a real server would set other CGI environ vars as well*/
setenv("QUERY_STRING", cgiargs, 1);
/* print first part of response header */
sprintf(buf, "HTTP/1.1 200 OK\n");
write(childfd, buf, strlen(buf));
sprintf(buf, "Server: Tiny Web Server\n");
write(childfd, buf, strlen(buf));
/* create and run the child CGI process so that all child
output to stdout and stderr goes back to the client via the
childfd socket descriptor */
pid = fork();
if (pid < 0) {
perror("ERROR in fork");
exit(1);
}
else if (pid > 0) { /* parent process */
wait(&wait_status);
}
else { /* child process*/
close(0); /* close stdin */
dup2(childfd, 1); /* map socket to stdout */
dup2(childfd, 2); /* map socket to stderr */
if (execve(filename, NULL, environ) < 0) {
perror("ERROR in execve");
}
}
}
/* clean up */
fclose(stream);
close(childfd);
}
}
Friday, 29 August 2025
sip.cpp
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <termios.h>
#include <fcntl.h>
#include <netdb.h>
#include <sys/select.h>
#define DO 0xfd
#define WONT 0xfc
#define WILL 0xfb
#define DONT 0xfe
#define CMD 0xff
#define CMD_ECHO 1
#define CMD_WINDOW_SIZE 31
#define BUFLEN 20096
//#define BUFLEN 20
int len;
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <errno.h>
#include <pthread.h>
#define RESET "\033[0m"
#define RED "\033[1;31m"
#define GREEN "\033[1;32m"
#define YELLOW "\033[1;33m"
#define BLUE "\033[1;34m"
#define CYAN "\033[1;36m"
#define BOLD "\033[1m"
// Kolorowe printf-y
#define info(...) printf(GREEN __VA_ARGS__); printf(RESET)
#define warn(...) printf(YELLOW __VA_ARGS__); printf(RESET)
#define err(...) fprintf(stderr, RED __VA_ARGS__); fprintf(stderr, RESET)
#define debug(...) printf(CYAN __VA_ARGS__); printf(RESET)
#define START_PORT 1
#define END_PORT 1024
#define TIMEOUT_SEC 0
#define TIMEOUT_USEC 200000 // 200ms
const char *target_ip;
void *scan_port(void *arg) {
int port = *(int *)arg;
free(arg);
int sockfd;
struct sockaddr_in target;
struct timeval timeout;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) pthread_exit(NULL);
timeout.tv_sec = TIMEOUT_SEC;
timeout.tv_usec = TIMEOUT_USEC;
setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout));
setsockopt(sockfd, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout));
target.sin_family = AF_INET;
target.sin_port = htons(port);
target.sin_addr.s_addr = inet_addr(target_ip);
int result = connect(sockfd, (struct sockaddr *)&target, sizeof(target));
if (result == 0) {
printf("Port %d jest OTWARTY\n", port);
}
close(sockfd);
pthread_exit(NULL);
}
int scan(int argc, char *argv[]) {
if (argc != 2) {
printf("Użycie: %s <IP>\n", argv[0]);
return 1;
}
target_ip = argv[1];
printf(GREEN,"Skanowanie hosta %s w zakresie portów %d-%d...\n", target_ip, START_PORT, END_PORT);
pthread_t threads[END_PORT - START_PORT + 1];
int thread_count = 0;
for (int port = START_PORT; port <= END_PORT; port++) {
int *arg = (int *)malloc(sizeof(int));
if (!arg) {
perror("malloc");
continue;
}
*arg = port;
if (pthread_create(&threads[thread_count], NULL, scan_port, arg) != 0) {
perror("pthread_create");
free(arg);
} else {
thread_count++;
}
}
// Poczekaj na zakończenie wszystkich wątków
for (int i = 0; i < thread_count; i++) {
pthread_join(threads[i], NULL);
}
printf("Skanowanie zakończone.\n");
return 0;
}
unsigned char buf[BUFLEN + 1];
static struct termios tin;
int hostname_to_ip(char *hostname, char *ip) {
struct hostent *he;
struct in_addr **addr_list;
if ((he = gethostbyname(hostname)) == NULL) {
herror("gethostbyname");
return 1;
}
addr_list = (struct in_addr **)he->h_addr_list;
int i = 0;
while (addr_list[i] != NULL) {
printf(GREEN,"IP[%d]: %s\n", i, inet_ntoa(*addr_list[i]));
i++;
}
// Zwróć pierwszy IP jako główny
if (addr_list[0] != NULL) {
strcpy(ip, inet_ntoa(*addr_list[0]));
return 0;
}
return 1;
}
int hostname_to_ip2(char *hostname, char *ip) {
struct hostent *he;
struct in_addr **addr_list;
if ((he = gethostbyname(hostname)) == NULL) {
herror("gethostbyname");
return 1;
}
addr_list = (struct in_addr **)he->h_addr_list;
if (addr_list[0] != NULL) {
strcpy(ip, inet_ntoa(*addr_list[0]));
return 0;
printf("%s",inet_ntoa(*addr_list[1]));
}
printf(GREEN,"%s",inet_ntoa(*addr_list[0]));
return 1;
}
void parse_passive_mode(char *response, char *ip, int *port) {
int a, b, c, d, e, f;
if (sscanf(response, "227 Entering Passive Mode (%d,%d,%d,%d,%d,%d)", &a, &b, &c, &d, &e, &f) == 6) {
sprintf(ip, "%d.%d.%d.%d", a, b, c, d);
*port = (e * 256) + f;
}
}
void negotiate(int sock, unsigned char *buf, int len) {
int i;
if (buf[1] == DO && buf[2] == CMD_WINDOW_SIZE) {
unsigned char tmp1[10] = {255, 251, 31};
if (send(sock, tmp1, 3 , 0) < 0) exit(1);
unsigned char tmp2[10] = {255, 250, 31, 0, 80, 0, 24, 255, 240};
if (send(sock, tmp2, 9, 0) < 0) exit(1);
return;
}
for (i = 0; i < len; i++) {
if (buf[i] == DO) buf[i] = WONT;
else if (buf[i] == WILL) buf[i] = DONT;
}
if (send(sock, buf, len , 0) < 0) exit(1);
}
//static struct termios tin;
static void terminal_set(void) {
tcgetattr(STDIN_FILENO, &tin);
static struct termios tlocal;
memcpy(&tlocal, &tin, sizeof(tin));
cfmakeraw(&tlocal);
tcsetattr(STDIN_FILENO, TCSANOW, &tlocal);
}
static void terminal_reset(void) {
tcsetattr(STDIN_FILENO, TCSANOW, &tin);
}
void parse_url(char *url, char *hostname, char *path, int *port) {
char *p = url;
char *protocol_end;
// Domyślnie: HTTP
*port = 80;
if (strstr(p, "ftp://") == p) {
*port = 21;
protocol_end = p + strlen("ftp://");
} else if (strstr(p, "http://") == p) {
*port = 80;
protocol_end = p + strlen("http://");
} else if (strstr(p, "https://") == p) {
fprintf(stderr, "Protokół HTTPS nie jest wspierany (brak TLS)\n");
exit(1);
} else {
protocol_end = p;
}
char *host_end = strchr(protocol_end, '/');
if (host_end != NULL) {
strncpy(hostname, protocol_end, host_end - protocol_end);
hostname[host_end - protocol_end] = '\0';
strcpy(path, host_end);
} else {
strcpy(hostname, protocol_end);
strcpy(path, "/");
}
}
void usage(char *prog_name) {
printf(GREEN,"Użycie: %s URL [PORT] [opcje]\n", prog_name);
printf("Argumenty:\n");
printf(" URL Adres URL lub host (np. http://host lub ftp.gnu.org)\n");
printf(" PORT Port TCP (opcjonalny, domyślnie 80)\n");
printf("Opcje:\n");
printf(" -s Włącza skanowanie portów 1-1024 dla podanego hosta\n");
printf(" -m METHOD Metoda HTTP (GET, POST, PUT, HEAD, OPTIONS). Domyślnie: GET\n");
printf(" -b BODY Ciało żądania dla POST/PUT\n");
printf(" -h Wyświetla tę pomoc\n");
printf("\nPrzykłady:\n");
printf(" %s http://example.com -m GET\n", prog_name);
printf(" %s ftp.gnu.org -s\n", prog_name);
printf(" %s smtp.gmail.com 587\n", prog_name);
}
int main(int argc, char *argv[]) {
int sock;
struct sockaddr_in server;
char ip_str[INET_ADDRSTRLEN];
int port;
char*location[100];
char hostname[256];
char *url = NULL;
char *body = NULL;
char path[BUFLEN];
char *method = "GET";
int scan_mode = 0;
int bytes_received;
// char *path = "/";
char http_request[4006];
char*hearth[100];
int data_sock = socket(AF_INET, SOCK_STREAM, 0);
if (argc < 2) {
fprintf(stderr, "Brak URL-a!\n");
usage(argv[0]);
return 1;
}
// PARSOWANIE ARGUMENTÓW POZYCYJNYCH: URL + PORT (opcjonalny)
int arg_index = 1;
url = argv[arg_index++];
parse_url(url, hostname, path, &port); // ⬅️ najpierw parsuj URL i ustaw domyślny port
if (arg_index < argc && argv[arg_index][0] != '-') {
int custom_port = atoi(argv[arg_index++]);
if (custom_port <= 0 || custom_port > 65535) {
fprintf(stderr, "Nieprawidłowy port: %s\n", argv[arg_index - 1]);
return 1;
}
port = custom_port; // ⬅️ nadpisz tylko jeśli użytkownik podał jawnie
}
// Przestawienie argv tak, żeby getopt przetwarzał od prawidłowego miejsca
optind = arg_index;
int c;
while ((c = getopt(argc, argv, "m:b:sh")) != -1) {
switch (c) {
case 's':
scan_mode = 1;
break;
case 'm':
method = optarg;
break;
case 'b':
body = optarg;
break;
case 'h':
usage(argv[0]);
return 0;
case '?':
fprintf(stderr, "Nieznana opcja: -%c\n", optopt);
usage(argv[0]);
return 1;
}
}
// Parsowanie URL
// parse_url(url, hostname, path, &port);
printf("Parsed - Host: %s, Path: %s, Port: %d\n", hostname, path, port);
if (hostname_to_ip(hostname, ip_str) != 0) {
fprintf(stderr, "Nie mozna rozwiazac nazwy hosta: %s\n", hostname);
return 1;
}
if (scan_mode) {
char *scan_argv[] = { argv[0], ip_str };
return scan(2, scan_argv); // wywołuje funkcję skanera i kończy program
}
// Tworzenie i łączenie gniazda
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == -1) {
perror("Could not create socket. Error");
return 1;
}
server.sin_addr.s_addr = inet_addr(ip_str);
server.sin_family = AF_INET;
server.sin_port = htons(port);
if (connect(sock, (struct sockaddr *)&server, sizeof(server)) < 0) {
perror("connect failed. Error");
return 1;
}
puts("Connected...\n");
FILE *fp = fopen("index.html", "w");
if (fp == NULL) {
perror("Error opening file");
close(sock);
return 1;
}
/* sprintf(http_request, "%s %s HTTP/1.1\r\nHost:%s\r\nConnection:close\r\n\r\n", method, path, hostname);*/
if (strcasecmp(method, "POST") == 0 || strcasecmp(method, "PUT") == 0) {
if (body == NULL) {
body = ""; // żeby nie było NULL
}
sprintf(http_request,
"%s %s HTTP/1.1\r\n"
"Host: %s\r\n"
"Content-Type: application/x-www-form-urlencoded\r\n"
"Content-Length: %ld\r\n"
"Connection: close\r\n"
"\r\n"
"%s",
method, path, hostname, strlen(body), body);
} else if (strcasecmp(method, "DELETE") == 0) {
sprintf(http_request,
"DELETE %s HTTP/1.1\r\n"
"Host: %s\r\n"
"Connection: close\r\n"
"\r\n",
path, hostname);
} else {
sprintf(http_request,
"%s %s HTTP/1.1\r\n"
"Host: %s\r\n"
"Connection: close\r\n"
"\r\n",
method, path, hostname);
}
printf("%s",http_request);
struct timeval ts;
ts.tv_sec = 1;
ts.tv_usec = 0;
while (1) {
fd_set fds;
FD_ZERO(&fds);
FD_SET(sock, &fds);
FD_SET(0, &fds);
if (data_sock != -1) FD_SET(data_sock, &fds);
int max_fd = (data_sock > sock) ? data_sock : sock;
int nready = select(max_fd + 1, &fds, (fd_set *)0, (fd_set *)0, &ts);
if (nready < 0) {
perror("select. Error");
return 1;
} else if (nready == 0) {
ts.tv_sec = 1;
ts.tv_usec = 0;
}
if (port==80){
send(sock, http_request, strlen(http_request), 0);
}
// Obsługa danych z gniazda kontrolnego (sock)
if (FD_ISSET(sock, &fds)) {
int rv = recv(sock, buf, sizeof(buf) - 1, 0);
if (rv > 0) {
buf[rv] = '\0';
printf("%s", buf);
fprintf(fp,"%s",buf);
fflush(stdout);
if (strstr((char *)buf, "HTTP/1.1 301") != NULL) {
char *location_start = strstr((char *)buf, "Location:");
if (location_start) {
location_start += strlen("Location:");
while (*location_start == ' ') location_start++; // pomiń spacje
char new_url[BUFLEN];
int i = 0;
while (*location_start && *location_start != '\r' && *location_start != '\n' && i < BUFLEN - 1) {
new_url[i++] = *location_start++;
}
new_url[i] = '\0';
printf(YELLOW "301 Moved Permanently ➡️ Przekierowanie na: %s\n" RESET, new_url);
close(sock);
if (data_sock != -1) close(data_sock);
fclose(fp);
char *new_argv[] = { argv[0], new_url };
printf(YELLOW "▶️ Wznawiam żądanie pod nowym adresem...\n" RESET);
return main(2, new_argv); // rekurencyjnie wywołaj main z nowym URL
}
}
// Sprawdzamy, czy odebrana wiadomość to odpowiedź na PASV
if (strstr((char *)buf, "227 Entering Passive Mode") != NULL) {
char data_ip[INET_ADDRSTRLEN];
int data_port;
parse_passive_mode((char *)buf, data_ip, &data_port);
data_sock = socket(AF_INET, SOCK_STREAM, 0);
if (data_sock < 0) {
perror("socket (data)");
data_sock = -1;
continue;
}
struct sockaddr_in data_server_addr;
data_server_addr.sin_family = AF_INET;
data_server_addr.sin_port = htons(data_port);
inet_pton(AF_INET, data_ip, &data_server_addr.sin_addr);
if (connect(data_sock, (struct sockaddr *)&data_server_addr, sizeof(data_server_addr)) < 0) {
perror("connect (data socket)");
close(data_sock);
data_sock = -1;
}
}
} else if (rv == 0) {
printf("Connection closed by the remote end\n\r");
break;
} else {
perror("recv");
break;
}
}
// Obsługa danych z gniazda danych (data_sock)
if (data_sock != -1 && FD_ISSET(data_sock, &fds)) {
int rv = recv(data_sock, buf, sizeof(buf) - 1, 0);
if (rv > 0) {
buf[rv] = '\0';
printf("%s", buf);
} else {
close(data_sock);
data_sock = -1;
printf("\n--- Zakonczono transfer danych ---\n");
}
}
// Obsługa danych z klawiatury
if (FD_ISSET(0, &fds)) {
char input_buffer[BUFLEN];
if (fgets(input_buffer, sizeof(input_buffer), stdin) == NULL) break;
// Usunięcie znaku nowej linii
input_buffer[strcspn(input_buffer, "\n")] = 0;
if (strcmp(input_buffer, "quit") == 0) {
char quit_cmd[] = "QUIT\r\n";
send(sock, quit_cmd, strlen(quit_cmd), 0);
break;
}
// Wysyłanie komendy do serwera, kończąc ją CRLF
char full_cmd[BUFLEN + 2];
sprintf(full_cmd, "%s\r\n", input_buffer);
if (send(sock, full_cmd, strlen(full_cmd), 0) < 0) {
perror("send");
continue;
}
}
}
fclose(fp);
puts("save in index.html");
if (sock != -1) close(sock);
if (data_sock != -1) close(data_sock);
return 0;
}
Monday, 4 August 2025
Sdl assimp GL .fbx yml
name: Build and Deply SDL2 OpenGL Emscripten
on:
push:
branches:
- main
jobs:
build-and-deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup Emscripten SDK
run: |
git clone https://github.com/emscripten-core/emsdk.git
cd emsdk
./emsdk install 3.1.65
./emsdk activate 3.1.65
shell: bash
- name: Build Assimp (Emscripten)
run: |
source ./emsdk/emsdk_env.sh
git clone https://github.com/assimp/assimp.git
cd assimp
emcmake cmake \
-DASSIMP_BUILD_ALL_IMPORTERS_BY_DEFAULT=OFF \
-DASSIMP_BUILD_OBJ_IMPORTER=ON \
-DASSIMP_BUILD_OBJ_IMPORTER=ON \
-DASSIMP_BUILD_FBX_IMPORTER=ON \
-DASSIMP_BUILD_GLTF_IMPORTER=OFF \
-DASSIMP_BUILD_SHARED_LIBS=OFF \
-DASSIMP_NO_EXPORT=ON \
-DASSIMP_BUILD_ZLIB=ON \
-DASSIMP_BUILD_TESTS=OFF \
-DCMAKE_BUILD_TYPE=Release \
-DCMAKE_TOOLCHAIN_FILE=../emsdk/upstream/emscripten/cmake/Modules/Platform/Emscripten.cmake \
-DCMAKE_CROSSCOMPILING_EMULATOR=../emsdk/node/22.16.0_64bit/bin/node \
.
emmake make -j
shell: bash
- name: Check Assimp build output
run: |
ls -l assimp
ls -l assimp/lib
ls -l assimp/lib
shell: bash
- name: Compile C++ to WebAssembly with Assimp
run: |
source ./emsdk/emsdk_env.sh
mkdir -p dist
em++ sceny2.cpp \
-Iassimp/include \
-Iassimp/code \
-Lassimp/lib \
-lassimp \
-s WASM=1 \
-s USE_SDL=2 \
-s USE_ZLIB=1 \
-s USE_SDL_IMAGE=2 \
-s SDL2_IMAGE_FORMATS='["png"]' \
-s FULL_ES2=1 \
-s MIN_WEBGL_VERSION=1 \
-s MAX_WEBGL_VERSION=1 \
--preload-file asserts \
-s ALLOW_MEMORY_GROWTH=1 \
-s ASYNCIFY \
-o dist/index.html
shell: bash
- name: Deploy to GitHub Pages
uses: peaceiris/actions-gh-pages@v4
if: github.ref == 'refs/heads/main'
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
publish_dir: ./dist
on:
push:
branches:
- main
jobs:
build-and-deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup Emscripten SDK
run: |
git clone https://github.com/emscripten-core/emsdk.git
cd emsdk
./emsdk install 3.1.65
./emsdk activate 3.1.65
shell: bash
- name: Build Assimp (Emscripten)
run: |
source ./emsdk/emsdk_env.sh
git clone https://github.com/assimp/assimp.git
cd assimp
emcmake cmake \
-DASSIMP_BUILD_ALL_IMPORTERS_BY_DEFAULT=OFF \
-DASSIMP_BUILD_OBJ_IMPORTER=ON \
-DASSIMP_BUILD_OBJ_IMPORTER=ON \
-DASSIMP_BUILD_FBX_IMPORTER=ON \
-DASSIMP_BUILD_GLTF_IMPORTER=OFF \
-DASSIMP_BUILD_SHARED_LIBS=OFF \
-DASSIMP_NO_EXPORT=ON \
-DASSIMP_BUILD_ZLIB=ON \
-DASSIMP_BUILD_TESTS=OFF \
-DCMAKE_BUILD_TYPE=Release \
-DCMAKE_TOOLCHAIN_FILE=../emsdk/upstream/emscripten/cmake/Modules/Platform/Emscripten.cmake \
-DCMAKE_CROSSCOMPILING_EMULATOR=../emsdk/node/22.16.0_64bit/bin/node \
.
emmake make -j
shell: bash
- name: Check Assimp build output
run: |
ls -l assimp
ls -l assimp/lib
ls -l assimp/lib
shell: bash
- name: Compile C++ to WebAssembly with Assimp
run: |
source ./emsdk/emsdk_env.sh
mkdir -p dist
em++ sceny2.cpp \
-Iassimp/include \
-Iassimp/code \
-Lassimp/lib \
-lassimp \
-s WASM=1 \
-s USE_SDL=2 \
-s USE_ZLIB=1 \
-s USE_SDL_IMAGE=2 \
-s SDL2_IMAGE_FORMATS='["png"]' \
-s FULL_ES2=1 \
-s MIN_WEBGL_VERSION=1 \
-s MAX_WEBGL_VERSION=1 \
--preload-file asserts \
-s ALLOW_MEMORY_GROWTH=1 \
-s ASYNCIFY \
-o dist/index.html
shell: bash
- name: Deploy to GitHub Pages
uses: peaceiris/actions-gh-pages@v4
if: github.ref == 'refs/heads/main'
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
publish_dir: ./dist
Wednesday, 30 July 2025
Sunday, 27 July 2025
Friday, 25 July 2025
Wednesday, 11 September 2024
Telnet.c clijent FTP

/*
gcc -c -fPIE telnet.cpp -o telnet.o
gcc telnet.o -o telnet -pie
chmod +x telnet
./telnet
test
ftp.dlptest.com 21
dlpuser
rNrKYTX9g7z3RgJRmxWuGHbeu
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <termios.h>
#include <netdb.h>
#include <fcntl.h>
#include <sys/select.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <arpa/inet.h>
#include <termios.h>
#include <termios.h>
#include <fcntl.h>
#include<iostream>
#include<stdio.h> // printf
#include<string.h> // strlen
#include<string> // string
#include<sys/socket.h> // socket
#include<arpa/inet.h> // inet_addr
#include<netdb.h> // hostenta
#include <unistd.h>
#include<iostream>
#include<sys/socket.h> // socket
#include<arpa/inet.h> // inet_addr
#include <sys/time.h>
//using namespace std;
#define BUFLEN 20
int len;
unsigned char buf[BUFLEN + 1];
struct sockaddr_in server;
/*telnet*/
#define DO 0xfd
#define WONT 0xfc
#define WILL 0xfb
#define DONT 0xfe
#define CMD 0xff
#define CMD_ECHO 1
#define CMD_WINDOW_SIZE 31
#define BUFLEN 20
#define IAC 255
#define CMD 0xff
#define DONT 0xfe
#define DO 0xfd
#define WONT 0xfc
#define WILL 0xfb
#define SB 0xfa
#define GA 0xf9
#define EL 0xf8
#define EC 0xf7
#define AYT 0xf6
#define AO 0xf5
#define IP 0xf4
#define BREAK 0xf3
#define SYNCH 0xf2
#define NOP 0xf1
#define SE 0xf0
#define EOR 0xef
#define ABORT 0xee
#define SUSP 0xed
#define xEOF 0xec
//#define BUFLEN 512
#define PRELIM 1
#define COMPLETE 2
#define CONTINUE 3
#define TRANSIENT 4
#define ERROR 5
#define RRQ 01
#define WRQ 02
#define DATA 03
#define ACK 04
#define REC_ESC '\377'
#define REC_EOR '\001'
#define REC_EOF '\002'
#define BLK_EOR 0x80
#define BLK_EOF 0x40
#define BLK_ERRORS 0x20
#define BLK_RESTART 0x10
static struct termios tin;
// Konwersja hosta na IP
char* resolve_hostname(char* hostname) {
struct hostent* he;
struct in_addr** addr_list;
printf("Rozwiązywanie nazwy hosta: %s\n", hostname);
if ((he = gethostbyname(hostname)) == NULL) {
herror("gethostbyname");
return NULL;
}
addr_list = (struct in_addr**) he->h_addr_list;
if (addr_list[0] != NULL) {
printf("Rozwiązano IP: %s\n", inet_ntoa(*addr_list[0]));
return inet_ntoa(*addr_list[0]);
}
return NULL;
}
void negotiate2(int sock, unsigned char *buf, int len) {
int i;
if (buf[1] == DO && buf[2] == CMD_WINDOW_SIZE) {
unsigned char tmp1[10] = {255, 251, 31};
if (send(sock, tmp1, 3 , 0) < 0)
exit(1);
unsigned char tmp2[10] = {255, 250, 31, 0, 80, 0, 24, 255, 240};
if (send(sock, tmp2, 9, 0) < 0)
exit(1);
return;
}
for (i = 0; i < len; i++) {
if (buf[i] == DO)
buf[i] = WONT;
else if (buf[i] == WILL)
buf[i] = DO;
}
if (send(sock, buf, len , 0) < 0)
exit(1);
}
void negotiate(int sock, unsigned char *buf, int len) {
for (int i = 0; i < len; i += 3) {
if (buf[i] != IAC) continue; // Sprawdzamy, czy jest to komenda Telnetu
unsigned char option = buf[i+1]; // Druga wartość to opcja DO, DONT, WILL, WONT
unsigned char command = buf[i+2]; // Trzecia wartość to konkretna opcja, np. ECHO
if (option == DO) {
// Odrzucamy wszystkie opcje DO (nie chcemy ich obsługiwać)
unsigned char response[3] = { IAC, WONT, command };
send(sock, response, 3, 0);
} else if (option == DONT) {
// Potwierdzamy, że nie będziemy robić tego, o co prosi serwer
unsigned char response[3] = { IAC, WONT, command };
send(sock, response, 3, 0);
} else if (option == WILL) {
// Odrzucamy wszystkie opcje WILL (nie chcemy ich obsługiwać)
unsigned char response[3] = { IAC, DONT, command };
send(sock, response, 3, 0);
} else if (option == WONT) {
// Potwierdzamy, że serwer nie będzie tego robił
unsigned char response[3] = { IAC, DONT, command };
send(sock, response, 3, 0);
}
}
}
static void terminal_set(void) {
// save terminal configuration
tcgetattr(STDIN_FILENO, &tin);
static struct termios tlocal;
memcpy(&tlocal, &tin, sizeof(tin));
cfmakeraw(&tlocal);
tcsetattr(STDIN_FILENO,TCSANOW,&tlocal);
}
static void terminal_reset(void) {
// restore terminal upon exit
tcsetattr(STDIN_FILENO,TCSANOW,&tin);
}
int main(int argc, char* argv[]) {
if (argc < 3) {
printf("Użycie: %s <adres_serwera> <port>\n", argv[0]);
return 1;
}
char* hostname = argv[1];
int port = atoi(argv[2]);
struct timeval ts;
ts.tv_sec = 1; // Ustawienie timeoutu na 1 sekundę
ts.tv_usec = 0;
// Sprawdzenie, czy port jest dozwolony (omijanie portów 80 i 443)
if (port == 80 || port == 443) {
printf("Port %d jest zablokowany. Wybierz inny port.\n", port);
return 1;
}
// Rozwiązywanie nazwy hosta na IP
char* ip_address = resolve_hostname(hostname);
if (ip_address == NULL) {
printf("Nie udało się rozwiązać hosta.\n");
return 1;
}
// Tworzenie socketu
int sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == -1) {
printf("Nie można utworzyć socketu\n");
return 1;
}
// Konfiguracja serwera
server.sin_family = AF_INET;
server.sin_addr.s_addr = inet_addr(ip_address);
server.sin_port = htons(port);
// Łączenie z serwerem
if (connect(sock, (struct sockaddr*)&server, sizeof(server)) < 0) {
perror("Błąd połączenia");
close(sock);
return 1;
}
printf("Połączono z serwerem %s na porcie %d\n", ip_address, port);
// Inicjalizacja zmiennych dla select()
fd_set fds;
struct timeval timeout;
timeout.tv_sec = 1; // 1 sekunda
timeout.tv_usec = 0;
// Otwieranie pliku do zapisu
FILE* fp = fopen("telnet_output.txt", "w");
if (fp == NULL) {
printf("Błąd otwierania pliku\n");
close(sock);
return 1;
}
// Wstawiamy funkcję negotiate w odpowiednie miejsce w kodzie
while (1) {
// terminal_set();
atexit(terminal_reset);
fd_set fds;
/* Set up polling. */
FD_ZERO(&fds);
if (sock != 0)
FD_SET(sock, &fds);
FD_SET(0, &fds);
// wait for data
int nready = select(sock + 1, &fds, (fd_set *) 0, (fd_set *) 0, &ts);
if (nready < 0) {
perror("select. Error");
return 1;
}
else if (nready == 0) {
ts.tv_sec = 1; // 1 second
ts.tv_usec = 0;
}
else if (sock != 0 && FD_ISSET(sock, &fds)) {
// start by reading a single byte
int rv;
if ((rv = recv(sock, buf, 1, 0)) < 0) {
return 1;
}
else if (rv == 0) {
printf("Connection closed by the remote end\n\r");
return 0;
}
if (buf[0] == IAC) {
// Odczytujemy 2 dodatkowe bajty i negocjujemy
len = recv(sock, buf + 1, 2, 0);
if (len < 0) {
return 1;
} else if (len == 0) {
printf("Connection closed by the remote end\n\r");
return 0;
}
// Wywołanie funkcji negotiate
negotiate(sock, buf, 3);
} else {
len = 1;
buf[len] = '\0';
printf("%s", buf);
fprintf(fp, "%s", buf);
fflush(0);
}
} else if (FD_ISSET(0, &fds)) {
buf[0] = getc(stdin); //fgets(buf, 1, stdin);
if (send(sock, buf, 1, 0) < 0)
return 1;
if (buf[0] == '\n') // with the terminal in raw mode we need to force a LF
putchar('\r');
}
}
fclose(fp);
close(sock);
return 0;
}
Saturday, 7 September 2024
SDL2 openGl load obj
#include <iostream>
#include <vector>
#include <fstream>
#include <sstream>
#include <string>
#include <math.h>
#include <stdlib.h>
#include <SDL2/SDL.h>
#include <SDL_opengles.h>
#include <iostream>
#include <vector>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
#include <jni.h>
#include <errno.h>
#include <math.h>
#include <EGL/egl.h>
#include <GLES/gl.h>
#include "SDL2/SDL.h"
//#include<GL/gl.h>
//#include<GL/glxext.h>
//#include<GL/glu.h>
#include "SDL_test_common.h"
#if defined(__IPHONEOS__) || defined(__ANDROID__)
#define HAVE_OPENGLES
#endif
#include "SDL_opengles.h"
#include <iostream>
#include <vector>
#include <fstream>
#include <sstream>
#include <string>
#include <math.h>
#include <stdlib.h>
#include <SDL2/SDL.h>
#include <SDL_opengles.h>
#include "SDL_image.h"
#include <stdio.h>
#include <string.h>
#include <SDL_image.h>
#if defined(__IPHONEOS__) || defined(__ANDROID__)
#define HAVE_OPENGLES
#endif
#include "SDL_opengles.h"
#define PATH "/storage/emulated/0/img.jpg"
SDL_Surface* surface;
#define SCREEN_WIDTH 800
#define SCREEN_HEIGHT 600
#define SCREEN_BPP 255
#define FALSE 0
#define TRUE 1
GLuint texture[1];
SDLTest_CommonState *state;
SDL_Event *event;
SDL_GLContext *context; // No need to have this as a pointer
struct mouse_handle {
int x = 1;
int y = 1;
} mouse;
struct Vertex {
float x, y, z;
};
struct Normal {
float nx, ny, nz;
};
struct TexCoord {
float u, v;
};
std::vector<Vertex>* vertices = nullptr;
std::vector<Normal>* normals = nullptr;
std::vector<TexCoord>* texCoords = nullptr;
void loadObj(const char *filename) {
vertices = new std::vector<Vertex>();
normals = new std::vector<Normal>();
texCoords = new std::vector<TexCoord>();
std::ifstream objFile(filename);
if (!objFile) {
std::cerr << "Unable to open file: " << filename << std::endl;
exit(1);
}
std::vector<Vertex> tempVertices;
std::vector<Normal> tempNormals;
std::vector<TexCoord> tempTexCoords;
std::string line;
while (std::getline(objFile, line)) {
std::istringstream iss(line);
std::string prefix;
iss >> prefix;
if (prefix == "v") {
Vertex vertex;
iss >> vertex.x >> vertex.y >> vertex.z;
tempVertices.push_back(vertex);
} else if (prefix == "vn") {
Normal normal;
iss >> normal.nx >> normal.ny >> normal.nz;
tempNormals.push_back(normal);
} else if (prefix == "vt") {
TexCoord texCoord;
iss >> texCoord.u >> texCoord.v;
tempTexCoords.push_back(texCoord);
} else if (prefix == "f") {
std::vector<int> vIndices, tIndices, nIndices;
std::string vertexData;
while (iss >> vertexData) {
std::replace(vertexData.begin(), vertexData.end(), '/', ' ');
std::istringstream vertexStream(vertexData);
int vIndex, tIndex = 0, nIndex = 0;
vertexStream >> vIndex;
if (vertexStream.peek() == ' ') { vertexStream >> tIndex; }
if (vertexStream.peek() == ' ') { vertexStream >> nIndex; }
vIndices.push_back(vIndex);
tIndices.push_back(tIndex);
nIndices.push_back(nIndex);
}
// Tworzenie trójkątów
for (size_t i = 1; i < vIndices.size() - 1; i++) {
vertices->push_back(tempVertices[vIndices[0] - 1]);
vertices->push_back(tempVertices[vIndices[i] - 1]);
vertices->push_back(tempVertices[vIndices[i + 1] - 1]);
normals->push_back(tempNormals[nIndices[0] - 1]);
normals->push_back(tempNormals[nIndices[i] - 1]);
normals->push_back(tempNormals[nIndices[i + 1] - 1]);
// Dodanie współrzędnych tekstury, jeśli są dostępne
if (!tempTexCoords.empty()) {
texCoords->push_back(tempTexCoords[tIndices[0] - 1]);
texCoords->push_back(tempTexCoords[tIndices[i] - 1]);
texCoords->push_back(tempTexCoords[tIndices[i + 1] - 1]);
}
}
}
}
objFile.close();
}
int LoadGLTextures() {
SDL_Surface *TextureImage = IMG_Load("elo.bmp");
if (!TextureImage) {
std::cerr << "Unable to load texture: " << IMG_GetError() << std::endl;
return 0;
}
glGenTextures(1, &texture[0]); // Poprawka: indeks tekstury powinien być texture[0], nie [1]
glBindTexture(GL_TEXTURE_2D, texture[0]);
int mode = (TextureImage->format->BytesPerPixel == 4) ? GL_RGBA : GL_RGB;
glTexImage2D(GL_TEXTURE_2D, 0, mode, TextureImage->w, TextureImage->h, 0, mode, GL_UNSIGNED_BYTE, TextureImage->pixels);
glPixelStorei(GL_UNPACK_ALIGNMENT, 2);
glGenerateMipmapOES(GL_TEXTURE_2D); // OpenGL ES 2.0: zmieniono z glGenerateMipmapOES na glGenerateMipmap
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
SDL_FreeSurface(TextureImage); // Zwalnianie pamięci po załadowaniu tekstury
return 1;
}
void setPerspective(float fov, float aspect, float znear, float zfar) {
float ymax = znear * tanf(fov * M_PI / 360.0f);
float ymin = -ymax;
float xmin = ymin * aspect;
float xmax = ymax * aspect;
glFrustumf(xmin, xmax, ymin, ymax, znear, zfar);
}
void cleanup() {
delete vertices;
delete normals;
delete texCoords;
}
void renderScene() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
setPerspective(60.0f, 1.0f, 0.1f, 80.0f); // Adjusted FOV and aspect ratio
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
// Apply transformations
glTranslatef(0.0f, 0.0f, -5.0f); // Move the object back
glScalef(1.0f, 1.0f, 1.0f); // Scale the object
glRotatef(mouse.x % 360, 0.0f, 1.0f, 0.0f); // Rotate around Y-axis
glRotatef(mouse.y % 360, 1.0f, 0.0f, 0.0f); // Rotate around X-axis
// Lighting setup
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
GLfloat light_position[] = {0.0f, 1.0f, 1.0f, 0.0f};
glLightfv(GL_LIGHT0, GL_POSITION, light_position);
glEnable(GL_TEXTURE_2D);
glShadeModel( GL_SMOOTH );
// Enable and set vertex arrays
glShadeModel( GL_SMOOTH );
// glClearDepthx( 1.0f ); // specify the clear value for the depth buffer
glEnable( GL_DEPTH_TEST );
glDepthFunc( GL_LEQUAL );
glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ); // specify implementation-specific hints
GLfloat amb_light[] = { 0.1, 0.1, 0.1, 1.0 };
GLfloat diffuse[] = { 0.6, 0.6, 0.6, 1 };
GLfloat specular[] = { 0.7, 0.7, 0.3, 1 };
glLightModelfv( GL_LIGHT_MODEL_AMBIENT, amb_light );
glLightfv( GL_LIGHT0, GL_DIFFUSE, diffuse );
glLightfv( GL_LIGHT0, GL_SPECULAR, specular );
glEnable( GL_LIGHT0 );
glEnable( GL_COLOR_MATERIAL );
glShadeModel( GL_SMOOTH );
// glLightModelx( GL_LIGHT_MODEL_TWO_SIDE, GL_FALSE );
glDepthFunc( GL_LEQUAL );
glEnable( GL_DEPTH_TEST );
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glClearColor(0.0, 0.0, 0.0, 1.0); glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(3, GL_FLOAT, sizeof(Vertex), vertices->data());
// Enable and set normal arrays
glEnableClientState(GL_NORMAL_ARRAY);
glNormalPointer(GL_FLOAT, sizeof(Normal), normals->data());
// Enable and set texture coordinates arrays
if (!texCoords->empty()) {
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glTexCoordPointer(2, GL_FLOAT, sizeof(TexCoord), texCoords->data());
glBindTexture(GL_TEXTURE_2D, texture[0]);
}
//gluLookAt( 4,2,0, 0,0,0, 0,1,0);
//GLUquadricObj *sphere=NULL;
// sphere = gluNewQuadric();
//gluQuadricDrawStyle(sphere, GLU_FILL);
//gluQuadricTexture(sphere, TRUE);
// gluQuadricNormals(sphere, GLU_SMOOTH);
glBindTexture( GL_TEXTURE_2D,texture[0] );
// Draw the object
glDrawArrays(GL_TRIANGLES, 0, vertices->size());
// Disable client states
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_NORMAL_ARRAY);
if (!texCoords->empty()) {
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
}
// Swap buffers to display the scene
SDL_GL_SwapWindow(state->windows[0]);
}
int main(int argc, char *argv[]) {
if (!(IMG_Init(IMG_INIT_JPG) & IMG_INIT_JPG)) {
std::cerr << "IMG_Init failed: " << IMG_GetError() << std::endl;
return 0;
}
SDL_DisplayMode mode;
state = SDLTest_CommonCreateState(argv, SDL_INIT_EVERYTHING);
SDLTest_CommonInit(state);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 1);
bool sdlmainloop = true;
bool running = true;
LoadGLTextures();
loadObj("/sdcard/cubec.obj"); // Wczytanie pliku OBJ na początku
SDL_GL_CreateContext(*state->windows);
while (running) {
SDL_Event event;
while (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT) {
running = false;
}
if (event.type == SDL_MOUSEMOTION) {
mouse.x = event.motion.x;
mouse.y = event.motion.y;
}
//
// Render the scene
// SDL_GL_SwapWindow(state->windows[0]);
renderScene();
// SDL_GL_SwapWindow(*state->windows);
}
}
cleanup();
// Cleanup
SDL_GL_DeleteContext(context);
SDLTest_CommonQuit(state);
return 0;
}
#include <vector>
#include <fstream>
#include <sstream>
#include <string>
#include <math.h>
#include <stdlib.h>
#include <SDL2/SDL.h>
#include <SDL_opengles.h>
#include <iostream>
#include <vector>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
#include <jni.h>
#include <errno.h>
#include <math.h>
#include <EGL/egl.h>
#include <GLES/gl.h>
#include "SDL2/SDL.h"
//#include<GL/gl.h>
//#include<GL/glxext.h>
//#include<GL/glu.h>
#include "SDL_test_common.h"
#if defined(__IPHONEOS__) || defined(__ANDROID__)
#define HAVE_OPENGLES
#endif
#include "SDL_opengles.h"
#include <iostream>
#include <vector>
#include <fstream>
#include <sstream>
#include <string>
#include <math.h>
#include <stdlib.h>
#include <SDL2/SDL.h>
#include <SDL_opengles.h>
#include "SDL_image.h"
#include <stdio.h>
#include <string.h>
#include <SDL_image.h>
#if defined(__IPHONEOS__) || defined(__ANDROID__)
#define HAVE_OPENGLES
#endif
#include "SDL_opengles.h"
#define PATH "/storage/emulated/0/img.jpg"
SDL_Surface* surface;
#define SCREEN_WIDTH 800
#define SCREEN_HEIGHT 600
#define SCREEN_BPP 255
#define FALSE 0
#define TRUE 1
GLuint texture[1];
SDLTest_CommonState *state;
SDL_Event *event;
SDL_GLContext *context; // No need to have this as a pointer
struct mouse_handle {
int x = 1;
int y = 1;
} mouse;
struct Vertex {
float x, y, z;
};
struct Normal {
float nx, ny, nz;
};
struct TexCoord {
float u, v;
};
std::vector<Vertex>* vertices = nullptr;
std::vector<Normal>* normals = nullptr;
std::vector<TexCoord>* texCoords = nullptr;
void loadObj(const char *filename) {
vertices = new std::vector<Vertex>();
normals = new std::vector<Normal>();
texCoords = new std::vector<TexCoord>();
std::ifstream objFile(filename);
if (!objFile) {
std::cerr << "Unable to open file: " << filename << std::endl;
exit(1);
}
std::vector<Vertex> tempVertices;
std::vector<Normal> tempNormals;
std::vector<TexCoord> tempTexCoords;
std::string line;
while (std::getline(objFile, line)) {
std::istringstream iss(line);
std::string prefix;
iss >> prefix;
if (prefix == "v") {
Vertex vertex;
iss >> vertex.x >> vertex.y >> vertex.z;
tempVertices.push_back(vertex);
} else if (prefix == "vn") {
Normal normal;
iss >> normal.nx >> normal.ny >> normal.nz;
tempNormals.push_back(normal);
} else if (prefix == "vt") {
TexCoord texCoord;
iss >> texCoord.u >> texCoord.v;
tempTexCoords.push_back(texCoord);
} else if (prefix == "f") {
std::vector<int> vIndices, tIndices, nIndices;
std::string vertexData;
while (iss >> vertexData) {
std::replace(vertexData.begin(), vertexData.end(), '/', ' ');
std::istringstream vertexStream(vertexData);
int vIndex, tIndex = 0, nIndex = 0;
vertexStream >> vIndex;
if (vertexStream.peek() == ' ') { vertexStream >> tIndex; }
if (vertexStream.peek() == ' ') { vertexStream >> nIndex; }
vIndices.push_back(vIndex);
tIndices.push_back(tIndex);
nIndices.push_back(nIndex);
}
// Tworzenie trójkątów
for (size_t i = 1; i < vIndices.size() - 1; i++) {
vertices->push_back(tempVertices[vIndices[0] - 1]);
vertices->push_back(tempVertices[vIndices[i] - 1]);
vertices->push_back(tempVertices[vIndices[i + 1] - 1]);
normals->push_back(tempNormals[nIndices[0] - 1]);
normals->push_back(tempNormals[nIndices[i] - 1]);
normals->push_back(tempNormals[nIndices[i + 1] - 1]);
// Dodanie współrzędnych tekstury, jeśli są dostępne
if (!tempTexCoords.empty()) {
texCoords->push_back(tempTexCoords[tIndices[0] - 1]);
texCoords->push_back(tempTexCoords[tIndices[i] - 1]);
texCoords->push_back(tempTexCoords[tIndices[i + 1] - 1]);
}
}
}
}
objFile.close();
}
int LoadGLTextures() {
SDL_Surface *TextureImage = IMG_Load("elo.bmp");
if (!TextureImage) {
std::cerr << "Unable to load texture: " << IMG_GetError() << std::endl;
return 0;
}
glGenTextures(1, &texture[0]); // Poprawka: indeks tekstury powinien być texture[0], nie [1]
glBindTexture(GL_TEXTURE_2D, texture[0]);
int mode = (TextureImage->format->BytesPerPixel == 4) ? GL_RGBA : GL_RGB;
glTexImage2D(GL_TEXTURE_2D, 0, mode, TextureImage->w, TextureImage->h, 0, mode, GL_UNSIGNED_BYTE, TextureImage->pixels);
glPixelStorei(GL_UNPACK_ALIGNMENT, 2);
glGenerateMipmapOES(GL_TEXTURE_2D); // OpenGL ES 2.0: zmieniono z glGenerateMipmapOES na glGenerateMipmap
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
SDL_FreeSurface(TextureImage); // Zwalnianie pamięci po załadowaniu tekstury
return 1;
}
void setPerspective(float fov, float aspect, float znear, float zfar) {
float ymax = znear * tanf(fov * M_PI / 360.0f);
float ymin = -ymax;
float xmin = ymin * aspect;
float xmax = ymax * aspect;
glFrustumf(xmin, xmax, ymin, ymax, znear, zfar);
}
void cleanup() {
delete vertices;
delete normals;
delete texCoords;
}
void renderScene() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
setPerspective(60.0f, 1.0f, 0.1f, 80.0f); // Adjusted FOV and aspect ratio
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
// Apply transformations
glTranslatef(0.0f, 0.0f, -5.0f); // Move the object back
glScalef(1.0f, 1.0f, 1.0f); // Scale the object
glRotatef(mouse.x % 360, 0.0f, 1.0f, 0.0f); // Rotate around Y-axis
glRotatef(mouse.y % 360, 1.0f, 0.0f, 0.0f); // Rotate around X-axis
// Lighting setup
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
GLfloat light_position[] = {0.0f, 1.0f, 1.0f, 0.0f};
glLightfv(GL_LIGHT0, GL_POSITION, light_position);
glEnable(GL_TEXTURE_2D);
glShadeModel( GL_SMOOTH );
// Enable and set vertex arrays
glShadeModel( GL_SMOOTH );
// glClearDepthx( 1.0f ); // specify the clear value for the depth buffer
glEnable( GL_DEPTH_TEST );
glDepthFunc( GL_LEQUAL );
glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ); // specify implementation-specific hints
GLfloat amb_light[] = { 0.1, 0.1, 0.1, 1.0 };
GLfloat diffuse[] = { 0.6, 0.6, 0.6, 1 };
GLfloat specular[] = { 0.7, 0.7, 0.3, 1 };
glLightModelfv( GL_LIGHT_MODEL_AMBIENT, amb_light );
glLightfv( GL_LIGHT0, GL_DIFFUSE, diffuse );
glLightfv( GL_LIGHT0, GL_SPECULAR, specular );
glEnable( GL_LIGHT0 );
glEnable( GL_COLOR_MATERIAL );
glShadeModel( GL_SMOOTH );
// glLightModelx( GL_LIGHT_MODEL_TWO_SIDE, GL_FALSE );
glDepthFunc( GL_LEQUAL );
glEnable( GL_DEPTH_TEST );
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glClearColor(0.0, 0.0, 0.0, 1.0); glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(3, GL_FLOAT, sizeof(Vertex), vertices->data());
// Enable and set normal arrays
glEnableClientState(GL_NORMAL_ARRAY);
glNormalPointer(GL_FLOAT, sizeof(Normal), normals->data());
// Enable and set texture coordinates arrays
if (!texCoords->empty()) {
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glTexCoordPointer(2, GL_FLOAT, sizeof(TexCoord), texCoords->data());
glBindTexture(GL_TEXTURE_2D, texture[0]);
}
//gluLookAt( 4,2,0, 0,0,0, 0,1,0);
//GLUquadricObj *sphere=NULL;
// sphere = gluNewQuadric();
//gluQuadricDrawStyle(sphere, GLU_FILL);
//gluQuadricTexture(sphere, TRUE);
// gluQuadricNormals(sphere, GLU_SMOOTH);
glBindTexture( GL_TEXTURE_2D,texture[0] );
// Draw the object
glDrawArrays(GL_TRIANGLES, 0, vertices->size());
// Disable client states
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_NORMAL_ARRAY);
if (!texCoords->empty()) {
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
}
// Swap buffers to display the scene
SDL_GL_SwapWindow(state->windows[0]);
}
int main(int argc, char *argv[]) {
if (!(IMG_Init(IMG_INIT_JPG) & IMG_INIT_JPG)) {
std::cerr << "IMG_Init failed: " << IMG_GetError() << std::endl;
return 0;
}
SDL_DisplayMode mode;
state = SDLTest_CommonCreateState(argv, SDL_INIT_EVERYTHING);
SDLTest_CommonInit(state);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 1);
bool sdlmainloop = true;
bool running = true;
LoadGLTextures();
loadObj("/sdcard/cubec.obj"); // Wczytanie pliku OBJ na początku
SDL_GL_CreateContext(*state->windows);
while (running) {
SDL_Event event;
while (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT) {
running = false;
}
if (event.type == SDL_MOUSEMOTION) {
mouse.x = event.motion.x;
mouse.y = event.motion.y;
}
//
// Render the scene
// SDL_GL_SwapWindow(state->windows[0]);
renderScene();
// SDL_GL_SwapWindow(*state->windows);
}
}
cleanup();
// Cleanup
SDL_GL_DeleteContext(context);
SDLTest_CommonQuit(state);
return 0;
}
Thursday, 5 September 2024
Try texture
#include <iostream>
#include <vector>
#include <fstream>
#include <sstream>
#include <string>
#include <math.h>
#include <stdlib.h>
#include <SDL2/SDL.h>
#include <SDL_opengles.h>
#include <iostream>
#include <vector>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
#include "SDL2/SDL.h"
#include "SDL_test_common.h"
#if defined(__IPHONEOS__) || defined(__ANDROID__)
#define HAVE_OPENGLES
#endif
#include "SDL_opengles.h"
#include <iostream>
#include <vector>
#include <fstream>
#include <sstream>
#include <string>
#include <math.h>
#include <stdlib.h>
#include <SDL2/SDL.h>
#include <SDL_opengles.h>
#include "SDL_image.h"
#include <stdio.h>
#include <string.h>
#include <SDL_image.h>
#if defined(__IPHONEOS__) || defined(__ANDROID__)
#define HAVE_OPENGLES
#endif
#include "SDL_opengles.h"
#define PATH "/storage/emulated/0/img.jpg"
GLuint texture[1]; // Changed to have at least one texture slot
SDLTest_CommonState *state;
SDL_Event *event;
SDL_GLContext *context; // No need to have this as a pointer
struct mouse_handle {
int x = 1;
int y = 1;
} mouse;
struct Vertex {
float x, y, z;
};
struct Normal {
float nx, ny, nz;
};
struct TexCoord {
float u, v;
};
std::vector<Vertex>* vertices = nullptr;
std::vector<Normal>* normals = nullptr;
std::vector<TexCoord>* texCoords = nullptr;
void loadObj(const char *filename) {
vertices = new std::vector<Vertex>();
normals = new std::vector<Normal>();
texCoords = new std::vector<TexCoord>();
std::ifstream objFile(filename);
if (!objFile) {
std::cerr << "Unable to open file: " << filename << std::endl;
exit(1);
}
std::vector<Vertex> tempVertices;
std::vector<Normal> tempNormals;
std::vector<TexCoord> tempTexCoords;
std::string line;
while (std::getline(objFile, line)) {
std::istringstream iss(line);
std::string prefix;
iss >> prefix;
if (prefix == "v") {
Vertex vertex;
iss >> vertex.x >> vertex.y >> vertex.z;
tempVertices.push_back(vertex);
} else if (prefix == "vn") {
Normal normal;
iss >> normal.nx >> normal.ny >> normal.nz;
tempNormals.push_back(normal);
}
else if (prefix == "vt") {
TexCoord texCoord;
iss >> texCoord.u >> texCoord.v;
texCoords->push_back(texCoord);
// tempTexCoords.push_back(texCoord);
}
else if (prefix == "f") {
std::vector<int> vIndices, nIndices;
std::string vertexData;
while (iss >> vertexData) {
std::replace(vertexData.begin(), vertexData.end(), '/', ' ');
std::istringstream vertexStream(vertexData);
int vIndex, tIndex, nIndex;
vertexStream >> vIndex >> tIndex >> nIndex;
vIndices.push_back(vIndex);
nIndices.push_back(nIndex);
}
for (size_t i = 1; i < vIndices.size() - 1; i++) {
vertices->push_back(tempVertices[vIndices[0] - 1]);
vertices->push_back(tempVertices[vIndices[i] - 1]);
vertices->push_back(tempVertices[vIndices[i + 1] - 1]);
normals->push_back(tempNormals[nIndices[0] - 1]);
normals->push_back(tempNormals[nIndices[i] - 1]);
normals->push_back(tempNormals[nIndices[i + 1] - 1]);
}
}
}
objFile.close();
}
int LoadGLTextures() {
SDL_Surface *TextureImage = IMG_Load(PATH);
if (!TextureImage) {
std::cerr << "Unable to load texture" << std::endl;
return 0;
}
glGenTextures(1, &texture[1]);
glBindTexture(GL_TEXTURE_2D, texture[1]);
// Determine the texture format (RGB or RGBA)
int mode = (TextureImage->format->BytesPerPixel == 4) ? GL_RGBA : GL_RGB;
// Assuming TextureImage is a structure containing width, height, and image data
glBindTexture(GL_TEXTURE_2D, texture[1]); // Bind the texture object
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, TextureImage->w, TextureImage->h, 0, GL_RGB, GL_UNSIGNED_BYTE,TextureImage->pixels);
// Upload the texture
// glTexImage2D(GL_TEXTURE_2D, 0, mode, TextureImage->w, TextureImage->h, 0, mode, GL_UNSIGNED_BYTE, TextureImage->image);
// Optionally generate mipmaps
glGenerateMipmapOES(GL_TEXTURE_2D);
// Set filtering
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); // Use mipmaps
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
//glEnable(GL_TEXTURE_2D);
SDL_FreeSurface(TextureImage);
return 1;
}
void setPerspective(float fov, float aspect, float znear, float zfar) {
float ymax = znear * tanf(fov * M_PI / 360.0f);
float ymin = -ymax;
float xmin = ymin * aspect;
float xmax = ymax * aspect;
glFrustumf(xmin, xmax, ymin, ymax, znear, zfar);
}
void cleanup() {
delete vertices;
delete normals;
delete texCoords;
}
void renderScene() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
setPerspective(60.0f, 1.0f, 0.1f, 80.0f); // Adjusted FOV and aspect ratio
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
// Apply transformations here
glTranslatef(0.0f, 0.0f, 0.0f); // Move the object back
glScalef(1.0f, 1.0f, 1.0f); // Scale the object
glRotatef(mouse.x % 360, 0.0f, 1.0f, 0.0f); // Rotate around Y-axis
glRotatef(mouse.y % 360, 1.0f, 0.0f, 0.0f); // Rotate around X-axis
// Lighting setup
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
GLfloat light_position[] = {0.0f, 1.0f, 1.0f, 0.0f};
glLightfv(GL_LIGHT0, GL_POSITION, light_position);
// Vertex and normal array setup
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(3, GL_FLOAT, sizeof(Vertex), vertices->data());
glEnableClientState(GL_NORMAL_ARRAY);
glNormalPointer(GL_FLOAT, sizeof(Normal), normals->data());
// Texture array setup
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, texture[1]);
glGenTextures(1, &texture[1]);
glBindTexture(GL_TEXTURE_2D, texture[1]); glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glTexCoordPointer(2, GL_FLOAT, sizeof(TexCoord), texCoords->data());
//TexCoord(texCoords->data());
// Render the object
glDrawArrays(GL_TRIANGLES, 0, vertices->size());
// Cleanup states
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_NORMAL_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
// Swap buffers to display the scene
SDL_GL_SwapWindow(state->windows[0]);
}
int main(int argc, char *argv[]) {
if (!(IMG_Init(IMG_INIT_JPG) & IMG_INIT_JPG)) {
std::cerr << "IMG_Init failed: " << IMG_GetError() << std::endl;
return 0;
}
SDL_DisplayMode mode;
state = SDLTest_CommonCreateState(argv, SDL_INIT_EVERYTHING);
SDLTest_CommonInit(state);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 1);
bool sdlmainloop = true;
bool running = true;
LoadGLTextures();
loadObj("/sdcard/sphere.obj"); // Wczytanie pliku OBJ na początku
SDL_GL_CreateContext(*state->windows);
while (running) {
SDL_Event event;
while (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT) {
running = false;
}
if (event.type == SDL_MOUSEMOTION) {
mouse.x = event.motion.x;
mouse.y = event.motion.y;
}
//
// Render the scene
renderScene();
// SDL_GL_SwapWindow(*state->windows);
}
}
cleanup();
// Cleanup
SDL_GL_DeleteContext(context);
SDLTest_CommonQuit(state);
return 0;
}
Subscribe to:
Posts (Atom)

