rotation.c 1.84 KB
#include "rotation.h"
#include <stdio.h>
#include <stdlib.h>

void free_image(struct image* img) {
    free(img->data);
    free(img);
}

struct image rotate_image(struct image* source, int angle) {
    struct image result;

    if (angle % LINE_ANGLE != 0) {
        result.width = source->height;
        result.height = source->width;
    } else {
        result.width = source->width;
        result.height = source->height;
    }

    result.data = calloc(result.width * result.height, sizeof(struct pixel));
    if (!result.data) {
        return (struct image){.width = 0, .height = 0, .data = NULL};
    }

    uint64_t source_width = source->width;
    uint64_t source_height = source->height;

    for (uint64_t y = 0; y < source_height; ++y) {
        for (uint64_t x = 0; x < source_width; ++x) {
            uint64_t source_index = y * source_width + x;
            uint64_t destination_x, destination_y;

            switch (angle) {
                case ANGLE_STEP:
                case -MAX_ANGLE:
                    destination_x = source_height - 1 - y;
                    destination_y = x;
                    break;
                case LINE_ANGLE:
                case -LINE_ANGLE:
                    destination_x = source_width - 1 - x;
                    destination_y = source_height - 1 - y;
                    break;
                case MAX_ANGLE:
                case -ANGLE_STEP:
                    destination_x = y;
                    destination_y = source_width - 1 - x;
                    break;
                default:
                    destination_x = x;
                    destination_y = y;
                    break;
            }

            uint64_t destination_index = destination_y * result.width + destination_x;
            result.data[destination_index] = source->data[source_index];
        }
    }

    return result;
}