// Copyright (c) 2013 Jascha Wetzel. All rights reserved.

#include "lib_tfd.h"

namespace tfd
{

const int
    ID_LIBRARY_TURBULENCEFD = 1023830;

static TurbulenceFDLibrary*
    tfd_lib_cache = NULL;

static TurbulenceFDLibrary*
CheckTFDLib(Int32 offset)
{ return (TurbulenceFDLibrary*)CheckLib(ID_LIBRARY_TURBULENCEFD, offset, (C4DLibrary**)&tfd_lib_cache); }

#define LIB_CALL(f,...)\
    do { TurbulenceFDLibrary* lib = CheckTFDLib(LIBOFFSET(TurbulenceFDLibrary, f));\
    if ( lib && lib->f ) lib->f(__VA_ARGS__); } while (0)

#define LIB_CALL_PTR(f,T,...)\
    do { TurbulenceFDLibrary* lib = CheckTFDLib(LIBOFFSET(TurbulenceFDLibrary, f));\
    if ( !lib || !lib->f ) return shared_ptr<T>();\
    return shared_ptr<T>(lib->f(__VA_ARGS__), lib->delete_##T); } while (0)

#define LIB_CALL_RET(f,def,...)\
    do { TurbulenceFDLibrary* lib = CheckTFDLib(LIBOFFSET(TurbulenceFDLibrary, f));\
    if ( !lib || !lib->f ) return def;\
    return lib->f(__VA_ARGS__); } while (0)

void TFDFluidContainer::
get_world_to_voxel(Matrix64& m, Vector64& bbox_neg, Vector64& bbox_pos)
{ LIB_CALL(get_world_to_voxel, this, m, bbox_neg, bbox_pos); }

shared_ptr<ChannelC4D> TFDFluidContainer::
get_channel(const ::String& channel)
{ LIB_CALL_PTR(get_channel, ChannelC4D, this, channel); }

float TFDFluidContainer::
sample_channel(shared_ptr<ChannelC4D>& channel, const Vector64& p, Interpolation interp)
{ LIB_CALL_RET(sample_channel, 0.f, channel.get(), p, interp); }

shared_ptr<ShaderC4D> TFDFluidContainer::
get_shader(const ::String& shader)
{ LIB_CALL_PTR(get_shader, ShaderC4D, this, shader); }

Vector4d32 TFDFluidContainer::
sample_shader(shared_ptr<ShaderC4D>& shader, const Vector64& p)
{ LIB_CALL_RET(sample_shader, Vector4d32(0.f), shader.get(), p); }

::String TFDFluidContainer::
get_cache_directory() const
{ LIB_CALL_RET(get_cache_directory, ::String(), this); }

void TFDFluidContainer::
get_shader_parameters(api::ShaderParameters& params) const
{ LIB_CALL(get_shader_parameters, this, &params); }

int TFDFluidContainer::
get_cache_frame_number() const
{ LIB_CALL_RET(get_cache_frame_number, 0, this); }

} // namespace tfd
