How could I make this bounding box coordinates code faster?

This code is part of a function that is called thousands of times in the render stepped function of my code. Thing is, this takes up 1/3 of the time in the function and yet it isnt iterating through anything! This is a huge bottle neck and I want to see how I can make this faster. It’s goal is to return the min and max coordinates of a bounding box of a triangle

    local a=Vector2.new(math.floor(aP.X), math.floor(aP.Y))
    local b=Vector2.new(math.floor(bP.X), math.floor(bP.Y))
    local c=Vector2.new(math.floor(cP.X), math.floor(cP.Y))
    local maxX = a.x
    local maxY = a.y
    local minX = a.x
    local minY = a.y

    --max coordinate
    if maxX < b.x then
        maxX = b.x
    end
    if maxX < c.x then
        maxX = c.x
    end

    if maxY < b.y then
        maxY = b.y
    end
    if maxY < c.y then
        maxY = c.y
    end

    --min coordinate
    if minX >= b.x then
        minX = b.x
    end
    if minX >= c.x then
        minX = c.x
    end

    if minY >= b.y then
        minY = b.y
    end
    if minY >= c.y then
        minY = c.y
    end

The if-statements can be simplified using math.min and math.max.

local a = Vector2.new(math.floor(aP.X), math.floor(aP.Y))
local b = Vector2.new(math.floor(bP.X), math.floor(bP.Y))
local c = Vector2.new(math.floor(cP.X), math.floor(cP.Y))

local minX = math.min(a.X, b.X, c.X)
local maxX = math.max(a.X, b.X, c.X)
local minY = math.min(a.Y, b.Y, c.Y)
local maxY = math.max(a.Y, b.Y, c.Y)

I am not sure if optimizing this code will actually solve your performance issues. Maybe somehow calling the function less per RenderStep is the most effective solution.

That code doesnt work in my program

EDIT: yep, went from 1/3 to 1/15th

1 Like

I forgot to include the a vector.

I’m not sure if its faster, but I use this: http://www.sunshine2k.de/coding/java/TriangleRasterization/TriangleRasterization.html (Use the standard algorithm).

1 Like

Do ap.X, ap.Y, ... remain constant? If so, you can cache the vectors created instead of creating them every frame.

I have to use that due to internal reasons. I need them to rounded down for consistensy stakes and I need them to be actual for my barycentric coordinate algorithm (and they do change when i apply my perspective matrices/translations)