Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save JujuAdams/98160a0294fa621dea7197a1e1918152 to your computer and use it in GitHub Desktop.

Select an option

Save JujuAdams/98160a0294fa621dea7197a1e1918152 to your computer and use it in GitHub Desktop.
AlphaProportion
/// Returns the alpha coverage of a region of a sprite image. This is approximate. The value
/// returned will be between `0` and `1` where higher values indicate more of the sprite is opaque.
///
/// @param sprite
/// @param image
/// @param left
/// @param top
/// @param width
/// @param height
function AlphaProportion(_sprite, _image, _left, _top, _width, _height)
{
static _staticSurfaceA = -1;
static _staticSurfaceB = -1;
static _staticSurfacePixel = -1;
static _buffer = buffer_create(4, buffer_grow, 1);
static _funcGuaranteeSurface = function(_surface, _width, _height)
{
if (not surface_exists(_surface))
{
_surface = surface_create(_width, _height);
}
else if ((surface_get_width(_surface) < _width) || (surface_get_height(_surface) < _height))
{
surface_free(_surface);
_surface = surface_create(_width, _height);
}
return _surface;
}
var _steps = ceil(max(log2(_width), log2(_height)));
var _maxSize = power(2, _steps);
_staticSurfaceA = _funcGuaranteeSurface(_staticSurfaceA, _maxSize, _maxSize);
_staticSurfaceB = _funcGuaranteeSurface(_staticSurfaceB, _maxSize, _maxSize);
_staticSurfacePixel = _funcGuaranteeSurface(_staticSurfacePixel, 1, 1);
var _surfaceA = _staticSurfaceA;
var _surfaceB = _staticSurfaceB;
var _oldTexFilter = gpu_get_tex_filter();
gpu_set_blendmode_ext(bm_one, bm_zero);
gpu_set_tex_filter(_oldTexFilter);
surface_set_target(_surfaceA);
draw_clear_alpha(c_black, 0);
draw_sprite_part(_sprite, _image, _left, _top, _width, _height, 0, 0);
surface_reset_target();
var _currentSize = _maxSize;
repeat(_steps-1)
{
surface_set_target(_surfaceB);
draw_surface_part_ext(_surfaceA, 0, 0, _currentSize, _currentSize, 0, 0, 0.5, 0.5, c_white, 1);
surface_reset_target();
var _temp = _surfaceA;
_surfaceA = _surfaceB
_surfaceB = _temp;
_currentSize /= 2;
}
surface_set_target(_staticSurfacePixel);
draw_surface_part_ext(_surfaceA, 0, 0, _currentSize, _currentSize, 0, 0, 0.5, 0.5, c_white, 1);
surface_reset_target();
gpu_set_blendmode(bm_normal);
gpu_set_tex_filter(_oldTexFilter);
buffer_get_surface(_buffer, _staticSurfacePixel, 0);
var _alpha = buffer_peek(_buffer, 0, buffer_u8) / 0xFF;
_alpha *= (_maxSize*_maxSize) / (_width*_height);
_alpha = clamp(_alpha, 0, 1);
return _alpha;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment