102 lines
2.9 KiB
C
102 lines
2.9 KiB
C
#include <X11/Xlib.h>
|
|
#include <math.h>
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
|
|
#define WIDTH 800 // Width of the window
|
|
#define HEIGHT 600 // Height of the window
|
|
#define SCALE_X 50 // Scale factor for x-axis
|
|
#define SCALE_Y 100 // Scale factor for y-axis
|
|
#define OFFSET_X 100 // Horizontal offset
|
|
#define OFFSET_Y 300 // Vertical offset (middle of the window)
|
|
#define GRID_SPACING_X 50 // Grid spacing for x-axis
|
|
#define GRID_SPACING_Y 50 // Grid spacing for y-axis
|
|
|
|
void draw_grid(Display *display, Window window, GC gc) {
|
|
int x, y;
|
|
|
|
// Set color for grid lines (light gray)
|
|
XSetForeground(display, gc, 0xcccccc);
|
|
|
|
// Draw vertical grid lines
|
|
for (x = OFFSET_X; x < WIDTH; x += GRID_SPACING_X) {
|
|
XDrawLine(display, window, gc, x, 0, x, HEIGHT);
|
|
}
|
|
|
|
// Draw horizontal grid lines
|
|
for (y = 0; y < HEIGHT; y += GRID_SPACING_Y) {
|
|
XDrawLine(display, window, gc, OFFSET_X, y, WIDTH, y);
|
|
}
|
|
}
|
|
|
|
void draw_sine_wave(Display *display, Window window, GC gc) {
|
|
double x;
|
|
int prev_x = OFFSET_X;
|
|
int prev_y = OFFSET_Y;
|
|
|
|
// Set color for sine wave (black)
|
|
XSetForeground(display, gc, BlackPixel(display, DefaultScreen(display)));
|
|
|
|
for (x = 0; x < 2 * M_PI * 4; x += 0.01) {
|
|
// Compute screen coordinates for the sine wave
|
|
int screen_x = OFFSET_X + (int)(x * SCALE_X);
|
|
int screen_y = OFFSET_Y - (int)(sin(x) * SCALE_Y);
|
|
|
|
// Draw a line from the previous point to the current point
|
|
XDrawLine(display, window, gc, prev_x, prev_y, screen_x, screen_y);
|
|
|
|
// Update previous coordinates
|
|
prev_x = screen_x;
|
|
prev_y = screen_y;
|
|
}
|
|
}
|
|
|
|
int main(void) {
|
|
Display *display;
|
|
Window window;
|
|
int screen;
|
|
GC gc;
|
|
|
|
// Open connection to X server
|
|
display = XOpenDisplay(NULL);
|
|
if (display == NULL) {
|
|
fprintf(stderr, "Unable to open X display\n");
|
|
exit(1);
|
|
}
|
|
|
|
screen = DefaultScreen(display);
|
|
|
|
// Create a simple window
|
|
window = XCreateSimpleWindow(display, RootWindow(display, screen), 10, 10, WIDTH, HEIGHT, 1,
|
|
BlackPixel(display, screen), WhitePixel(display, screen));
|
|
|
|
// Set window properties and show it
|
|
XSelectInput(display, window, ExposureMask | KeyPressMask);
|
|
XMapWindow(display, window);
|
|
|
|
// Create graphics context
|
|
gc = XCreateGC(display, window, 0, NULL);
|
|
|
|
// Event loop
|
|
XEvent event;
|
|
while (1) {
|
|
XNextEvent(display, &event);
|
|
|
|
if (event.type == Expose) {
|
|
// When the window is exposed, first draw the grid, then the sine wave
|
|
draw_grid(display, window, gc);
|
|
draw_sine_wave(display, window, gc);
|
|
}
|
|
|
|
if (event.type == KeyPress)
|
|
break; // Exit the loop on any keypress
|
|
}
|
|
|
|
// Clean up
|
|
XFreeGC(display, gc);
|
|
XDestroyWindow(display, window);
|
|
XCloseDisplay(display);
|
|
|
|
return 0;
|
|
}
|