void Camera_Init(EditorCamera* camera, int imageWidth, int imageHeight, int windowWidth, int windowHeight) {
camera->zoom = 1.0f;
camera->minZoom = 0.1f; // Minimum zoom level
camera->maxZoom = 10.0f; // Maximum zoom level
code
// Initialize camera dimensions based on initial zoom
float aspectRatio = (float)windowWidth / windowHeight;
camera->w = imageWidth / camera->zoom;
camera->h = camera->w / aspectRatio;
// Center the camera on the image
camera->x = (imageWidth - camera->w) / 2.0f;
camera->y = (imageHeight - camera->h) / 2.0f;
}
void Camera_HandleEvent(EditorCamera* camera, SDL_Event* event, int imageWidth, int imageHeight, int windowWidth, int windowHeight) {
if (event->type == SDL_MOUSEWHEEL) {
// Get mouse position in window coordinates
int mouseX, mouseY;
SDL_GetMouseState(&mouseX, &mouseY);
code
Assistant
// Store world coordinates under mouse before zooming
float prev_camera_w = camera->w;
float prev_camera_h = camera->h;
float world_mouseX_before = camera->x + ((float)mouseX / windowWidth) * prev_camera_w;
float world_mouseY_before = camera->y + ((float)mouseY / windowHeight) * prev_camera_h;
// Zoom factor
float zoomFactor = 1.1f;
// Zoom in or out
if (event->wheel.y > 0) { // Scroll up - zoom in
camera->zoom *= zoomFactor;
if (camera->zoom > camera->maxZoom) {
camera->zoom = camera->maxZoom;
}
} else if (event->wheel.y < 0) { // Scroll down - zoom out
camera->zoom /= zoomFactor;
if (camera->zoom < camera->minZoom) {
camera->zoom = camera->minZoom;
}
}
// Update camera dimensions based on new zoom
float aspectRatio = (float)windowWidth / windowHeight;
camera->w = imageWidth / camera->zoom;
camera->h = camera->w / aspectRatio;
// Ensure camera size does not exceed image bounds
if (camera->w > imageWidth) {
camera->w = imageWidth;
camera->h = camera->w / aspectRatio;
}
if (camera->h > imageHeight) {
camera->h = imageHeight;
camera->w = camera->h * aspectRatio;
}
// Adjust camera x and y to keep the world coordinate under mouse cursor stationary
camera->x = world_mouseX_before - ((float)mouseX / windowWidth) * camera->w;
camera->y = world_mouseY_before - ((float)mouseY / windowHeight) * camera->h;
// Ensure camera x and y stay within image bounds
if (camera->x < 0) camera->x = 0;
if (camera->y < 0) camera->y = 0;
if (camera->x + camera->w > imageWidth) camera->x = imageWidth - camera->w;
if (camera->y + camera->h > imageHeight) camera->y = imageHeight - camera->h;
}
}
void Camera_Update(EditorCamera* camera, int windowWidth, int windowHeight, int imageWidth, int imageHeight) {
// Update camera dimensions based on zoom and window aspect ratio
float aspectRatio = (float)windowWidth / windowHeight;
code
// Compute desired camera width and height based on zoom
camera->w = imageWidth / camera->zoom;
camera->h = camera->w / aspectRatio;
// Ensure camera size does not exceed image bounds
if (camera->w > imageWidth) {
camera->w = imageWidth;
camera->h = camera->w / aspectRatio;
}
if (camera->h > imageHeight) {
camera->h = imageHeight;
camera->w = camera->h * aspectRatio;
}
// Ensure camera position stays within image bounds
if (camera->x < 0) camera->x = 0;
if (camera->y < 0) camera->y = 0;
if (camera->x + camera->w > imageWidth) camera->x = imageWidth - camera->w;
if (camera->y + camera->h > imageHeight) camera->y = imageHeight - camera->h;
// Инициализация SDL_image
if (!(IMG_Init(IMG_INIT_PNG) & IMG_INIT_PNG)) {
printf("Ошибка инициализации SDL_image: %s\n", IMG_GetError());
SDL_Quit();
return 1;
}
// Создание окна с возможностью изменения размера
SDL_Window* window = SDL_CreateWindow("Отображение изображения",
SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED,
800, 600,
SDL_WINDOW_RESIZABLE);
if (!window) {
printf("Ошибка создания окна: %s\n", SDL_GetError());
IMG_Quit();
SDL_Quit();
return 1;
}
// Создание рендерера
SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
if (!renderer) {
printf("Ошибка создания рендерера: %s\n", SDL_GetError());
SDL_DestroyWindow(window);
IMG_Quit();
SDL_Quit();
return 1;
}
// Загрузка изображения
SDL_Surface* imageSurface = IMG_Load("../Maps/world/provinces.png");
if (!imageSurface) {
printf("Ошибка загрузки изображения: %s\n", IMG_GetError());
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
IMG_Quit();
SDL_Quit();
return 1;
}
// Создание текстуры из поверхности изображения
SDL_Texture* texture = SDL_CreateTextureFromSurface(renderer, imageSurface);
SDL_FreeSurface(imageSurface); // Освобождение поверхности
if (!texture) {
printf("Ошибка создания текстуры: %s\n", SDL_GetError());
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
IMG_Quit();
SDL_Quit();
return 1;
}
// Получение размеров изображения
int imageWidth, imageHeight;
SDL_QueryTexture(texture, NULL, NULL, &imageWidth, &imageHeight);
// Инициализация переменных размера окна
int windowWidth = 800, windowHeight = 600;
// Получение размеров окна
SDL_GetWindowSize(window, &windowWidth, &windowHeight);
// Создание и инициализация камеры
EditorCamera camera;
Camera_Init(&camera, imageWidth, imageHeight, windowWidth, windowHeight);
// Основной цикл приложения
int running = 1;
while (running) {
SDL_Event event;
// Обработка событий
while (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT) {
running = 0;
} else if (event.type == SDL_WINDOWEVENT && event.window.event == SDL_WINDOWEVENT_SIZE_CHANGED) {
// Обновляем размеры окна
SDL_GetWindowSize(window, &windowWidth, &windowHeight);
} else {
// Обработка событий камеры (зум)
Camera_HandleEvent(&camera, &event, imageWidth, imageHeight);
}
}
// Обновление камеры
Camera_Update(&camera, windowWidth, windowHeight, imageWidth, imageHeight);
// Установка исходного прямоугольника на основе позиции и размера камеры
SDL_Rect srcRect = { (int)camera.x, (int)camera.y, (int)camera.w, (int)camera.h };
SDL_Rect destRect = { 0, 0, windowWidth, windowHeight };
// Очистка рендерера
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255); // Черный фон
SDL_RenderClear(renderer);
// Отрисовка текстуры с масштабированием
SDL_RenderCopy(renderer, texture, &srcRect, &destRect);
// Обновление экрана
SDL_RenderPresent(renderer);
}
// Освобождение ресурсов
SDL_DestroyTexture(texture);
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
IMG_Quit();
SDL_Quit();
return 0;
}
#ifndef EDITOR_CAMERA_H
#define EDITOR_CAMERA_H
#include <SDL.h>
typedef struct {
float x; // Camera's X position on the image
float y; // Camera's Y position on the image
float w; // Width of the camera view
float h; // Height of the camera view
float zoom; // Current zoom level
float minZoom; // Minimum allowed zoom level
float maxZoom; // Maximum allowed zoom level
} EditorCamera;
// Initializes the camera with the image and window dimensions
void Camera_Init(EditorCamera* camera, int imageWidth, int imageHeight, int windowWidth, int windowHeight);
// Handles events like mouse wheel scrolling for zooming
void Camera_HandleEvent(EditorCamera* camera, SDL_Event* event, int imageWidth, int imageHeight);
// Updates the camera view based on the current zoom level and window size
void Camera_Update(EditorCamera* camera, int windowWidth, int windowHeight, int imageWidth, int imageHeight);
#endif // EDITOR_CAMERA_H
Исправь в этом коде следующие ошибки и предупреждения:
MapEditor.c: В функции «main»:
MapEditor.c:8:14: предупреждение: неиспользуемый параметр «argc» [-Wunused-parameter]
8 | int main(int argc, char* argv[]) {
| ~~~~^~~~
MapEditor.c:8:26: предупреждение: неиспользуемый параметр «argv» [-Wunused-parameter]
8 | int main(int argc, char* argv[]) {
| ~~~~~~^~~~~~
gcc -Wall -Wextra -O2 sdl2-config --cflagspkg-config --cflags SDL2_image -c EditorCamera.c -o EditorCamera.o
EditorCamera.c:20:6: ошибка: conflicting types for «Camera_HandleEvent»; have «void(EditorCamera , SDL_Event , int, int, int, int)»
20 | void Camera_HandleEvent(EditorCamera camera, SDL_Event event, int imageWidth, int imageHeight, int windowWidth, int windowHeight) {
| ^~~~~~~~~~~~~~~~~~
In file included from EditorCamera.c:3:
EditorCamera.h:20:6: замечание: previous declaration of «Camera_HandleEvent» with type «void(EditorCamera , SDL_Event , int, int)»
20 | void Camera_HandleEvent(EditorCamera camera, SDL_Event event, int imageWidth, int imageHeight);
| ^~~~~~~~~~~~~~~~~~
make: *** [Makefile:31: EditorCamera.o] Ошибка 1
Конфликт типов для функции Camera_HandleEvent возникает из-за несоответствия между декларацией функции в EditorCamera.h и ее определением в EditorCamera.c. В EditorCamera.c функция имеет 6 параметров, а в EditorCamera.h — только 4. Кроме того, предупреждения в MapEditor.c возникают из-за неиспользуемых параметров argc и argv в функции main.
Вот исправленный код:
EditorCamera.h:
c
#ifndef EDITOR_CAMERA_H
#define EDITOR_CAMERA_H
#include <SDL.h>
typedef struct {
float x; // Camera's X position on the image
float y; // Camera's Y position on the image
float w; // Width of the camera view
float h; // Height of the camera view
float zoom; // Current zoom level
float minZoom; // Minimum allowed zoom level
float maxZoom; // Maximum allowed zoom level
} EditorCamera;
// Initializes the camera with the image and window dimensions
void Camera_Init(EditorCamera* camera, int imageWidth, int imageHeight, int windowWidth, int windowHeight);
// Handles events like mouse wheel scrolling for zooming
void Camera_HandleEvent(EditorCamera* camera, SDL_Event* event, int imageWidth, int imageHeight, int windowWidth, int windowHeight);
// Updates the camera view based on the current zoom level and window size
void Camera_Update(EditorCamera* camera, int windowWidth, int windowHeight, int imageWidth, int imageHeight);
#endif // EDITOR_CAMERA_H
EditorCamera.c (без изменений, за исключением того, что все соответствует декларации в заголовочном файле):
c
#include "EditorCamera.h"
void Camera_Init(EditorCamera* camera, int imageWidth, int imageHeight, int windowWidth, int windowHeight) {
camera->zoom = 1.0f;
camera->minZoom = 0.1f; // Minimum zoom level
camera->maxZoom = 10.0f; // Maximum zoom level
// Initialize camera dimensions based on initial zoom
float aspectRatio = (float)windowWidth / windowHeight;
camera->w = imageWidth / camera->zoom;
camera->h = camera->w / aspectRatio;
// Center the camera on the image
camera->x = (imageWidth - camera->w) / 2.0f;
camera->y = (imageHeight - camera->h) / 2.0f;
}
void Camera_HandleEvent(EditorCamera* camera, SDL_Event* event, int imageWidth, int imageHeight, int windowWidth, int windowHeight) {
if (event->type == SDL_MOUSEWHEEL) {
// Get mouse position in window coordinates
int mouseX, mouseY;
SDL_GetMouseState(&mouseX, &mouseY);
// Store world coordinates under mouse before zooming
float prev_camera_w = camera->w;
float prev_camera_h = camera->h;
float world_mouseX_before = camera->x + ((float)mouseX / windowWidth) * prev_camera_w;
float world_mouseY_before = camera->y + ((float)mouseY / windowHeight) * prev_camera_h;
// Zoom factor
float zoomFactor = 1.1f;
// Zoom in or out
if (event->wheel.y > 0) { // Scroll up - zoom in
camera->zoom *= zoomFactor;
if (camera->zoom > camera->maxZoom) {
camera->zoom = camera->maxZoom;
}
} else if (event->wheel.y < 0) { // Scroll down - zoom out
camera->zoom /= zoomFactor;
if (camera->zoom < camera->minZoom) {
camera->zoom = camera->minZoom;
}
}
// Update camera dimensions based on new zoom
float aspectRatio = (float)windowWidth / windowHeight;
camera->w = imageWidth / camera->zoom;
camera->h = camera->w / aspectRatio;
// Ensure camera size does not exceed image bounds
if (camera->w > imageWidth) {
camera->w = imageWidth;
camera->h = camera->w / aspectRatio;
}
if (camera->h > imageHeight) {
camera->h = imageHeight;
camera->w = camera->h * aspectRatio;
}
// Adjust camera x and y to keep the world coordinate under mouse cursor stationary
camera->x = world_mouseX_before - ((float)mouseX / windowWidth) * camera->w;
camera->y = world_mouseY_before - ((float)mouseY / windowHeight) * camera->h;
// Ensure camera x and y stay within image bounds
if (camera->x < 0) camera->x = 0;
if (camera->y < 0) camera->y = 0;
if (camera->x + camera->w > imageWidth) camera->x = imageWidth - camera->w;
if (camera->y + camera->h > imageHeight) camera->y = imageHeight - camera->h;
}
}
void Camera_Update(EditorCamera* camera, int windowWidth, int windowHeight, int imageWidth, int imageHeight) {
// Update camera dimensions based on zoom and window aspect ratio
float aspectRatio = (float)windowWidth / windowHeight;
// Compute desired camera width and height based on zoom
camera->w = imageWidth / camera->zoom;
camera->h = camera->w / aspectRatio;
// Ensure camera size does not exceed image bounds
if (camera->w > imageWidth) {
camera->w = imageWidth;
camera->h = camera->w / aspectRatio;
}
if (camera->h > imageHeight) {
camera->h = imageHeight;
camera->w = camera->h * aspectRatio;
}
// Ensure camera position stays within image bounds
if (camera->x < 0) camera->x = 0;
if (camera->y < 0) camera->y = 0;
if (camera->x + camera->w > imageWidth) camera->x = imageWidth - camera->w;
if (camera->y + camera->h > imageHeight) camera->y = imageHeight - camera->h;
}
MapEditor.c (исправлены предупреждения и передаются корректные параметры функции Camera_HandleEvent):
c
Пояснение внесенных изменений:
Исправлено несоответствие типов функции Camera_HandleEvent:
В EditorCamera.h изменена декларация функции Camera_HandleEvent, чтобы она соответствовала определению в EditorCamera.c и принимала 6 параметров:
c
void Camera_HandleEvent(EditorCamera* camera, SDL_Event* event, int imageWidth, int imageHeight, int windowWidth, int windowHeight);
Обновлен вызов функции Camera_HandleEvent в MapEditor.c:
При вызове Camera_HandleEvent теперь передаются все необходимые параметры, включая windowWidth и windowHeight:
Подавлены предупреждения о неиспользуемых параметрах argc и argv в функции main в MapEditor.c:
Добавлены следующие строки в начале функции main, чтобы явно указать, что параметры не используются:
c
(void)argc;
(void)argv;
Альтернативно, можно было бы удалить параметры argc и argv из сигнатуры функции main, но в данном случае они оставлены, так как это стандартная сигнатура функции main.
После внесения этих изменений, ошибки и предупреждения при компиляции должны исчезнуть.