RW_Drivable = {}

-- ##################################################################################################################################################

-- NOTES

-- Used for defining the brake force generated by a vehicle
-- I've altered this significantly (before it was just giving a static number with no flexibility whatsoever)
-- Now, the brake force is changed depending on the friction generated by each tire and the amount of tires

-- Less friction (tire type, road conditions, tire width) will result in significantly longer braking times
-- More tires will result in shorter braking times

-- Having skinnier tires will result in more friction in non-dry weather whereas wider tires result in more friction in dry weather
-- Having dual wheels will now have an actual purpose
-- These changes necessitate using appropriate wheels for different road conditions and different situations to simulate realistic driving scenarios

-- ##################################################################################################################################################

function RW_Drivable:getBrakeForce(_)

    local force = self.brakeForce

    if self.vehicle == nil or self.vehicle.spec_wheels == nil or self.vehicle.spec_wheels.wheels == nil then return force end

    local wheels = self.vehicle.spec_wheels.wheels
    local totalWheels = 0
    local friction = 0
    local frictionDefined = false
    local isCrawler = false

    for _, wheel in ipairs(wheels) do
        totalWheels = totalWheels + 1
        if wheel.physics == nil or wheel.physics.tireGroundFrictionCoeff == nil then continue end
        local physics = wheel.physics

        friction = friction + physics.tireGroundFrictionCoeff
        local tireType = WheelsUtil.getTireTypeName(physics.tireType)
        if tireType == "CRAWLER" then isCrawler = true end
        frictionDefined = true

        if #wheel.visualWheels <= 1 then continue end

        for i, visualWheel in pairs(wheel.visualWheels) do
            if i == 1 then continue end
            friction = friction + physics.tireGroundFrictionCoeff
            totalWheels = totalWheels + 1
        end

    end

    if not frictionDefined then return force end

    friction = friction / (totalWheels == 0 and 1 or totalWheels)
    force = math.max(force * friction * ((isCrawler and 4 or totalWheels) / 4), force * 0.05)

    return force

end

VehicleMotor.getBrakeForce = Utils.overwrittenFunction(VehicleMotor.getBrakeForce, RW_Drivable.getBrakeForce)