/*
 * This file is part of Afterwarp Framework (https://afterwarp.io).
 * Copyright (c) 2015 - 2025 Dr. Yuriy Kotsarenko. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License at
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License is
 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and limitations under the License.
 */

// Afterwarp.Types.h
#pragma once

#ifdef __cplusplus
  #include "Afterwarp.Types.hpp"
#else
  #include "Afterwarp.Types.h"
#endif

// Calling conventions for library functions.
#if defined(_WIN32) || defined(__CYGWIN__)
  #ifdef PXT_LIBRARY
    #ifdef __GNUC__
      #define __AFTERWARP_API __attribute__ ((dllexport))
    #else
      #define __AFTERWARP_API __declspec(dllexport)
    #endif
  #else
    #ifdef __GNUC__
      #define __AFTERWARP_API __attribute__ ((dllimport))
    #else
      #define __AFTERWARP_API __declspec(dllimport)
    #endif
  #endif
#else
  #define __AFTERWARP_API __attribute__ ((visibility ("default")))
#endif

#if defined(__cplusplus)
  #define AFTERWARP_API extern "C" __AFTERWARP_API
#else
  #define AFTERWARP_API __AFTERWARP_API
#endif

#ifdef __cplusplus
  inline namespace pxt {
#endif

/*! \mainpage Afterwarp Framework
 *
 * Afterwarp Framework &reg; is a cross-platform framework for development of scientific, industrial and
 * interactive real-time applications. The framework includes both low-level API with full hardware
 * abstraction, allowing development of custom graphics engine using programmable pipeline and shaders,
 * including compute shaders for GPGPU work, and a high-level framework that can be used to quickly develop
 * 3D applications without knowledge of shaders.
 */

// General types and enumerations.

/// Generic untyped handle.
typedef void* UntypedHandle;

/// Boolean type returned by the library.
typedef uint8_t LibraryBool;

/// Custom object's payload.
typedef void* ObjectPayload;

// Device types and structures.

/// Swap-chain that enables double-buffered rendering to a particular window.
struct SwapChain_t;

#ifndef __cplusplus
  /// Swap-chain that enables double-buffered rendering to a particular window.
  typedef struct SwapChain_t SwapChain;
#endif

/// One or more device attribute flags combined (ORed) together.
typedef uint32_t DeviceAttributes;

/// Device behavior flags that affect the rendering code path.
typedef uint32_t DeviceBehavior;

/// Legacy feature bits that define older hardware features.
typedef uint32_t DeviceLegacyBits;

/// Returns device attribute bits that define level of extensions to be queried. This value can vary from
/// zero (0), which means no extensions (other than debug context) should be used to three (3), which means
/// all extensions. Note that a value of one is added to the given extension level before returning - this
/// means that extension level bits are present. If all extension level bits are unset (default), this is
/// the same as maximum level, meaning that all available extensions should be used.
#ifdef __cplusplus
  #ifndef PXT_AFTERWARP_FRAMEWORK
    inline uint32_t deviceAttributeExtensions(uint8_t const extensionLevel)
    {
      return static_cast<uint32_t>(extensionLevel + 1u) << 29;
    }
  #endif
#else
  #define DEVICE_ATTRIBUTE_EXTENSIONS(X) ((uint32_t)((X) + 1u) << 29)
#endif

/// Stencil state that is independent for each front and back facing.
struct StencilState
{
  /// Stencil test function.
  ComparisonFunc func;

  /// Action to take when stencil test fails.
  StencilOp failOp;

  /// Action to take when stencil test passes but depth test fails.
  StencilOp depthFailOp;

  /// Action to take when both stencil and depth tests pass, or when stencil test passes and either there
  /// is no depth buffer or depth testing is disabled.
  StencilOp depthPassOp;
};

/// Blending parameters that are specific to a certain component, or a portion of color.
struct Blend
{
  /// Blending factor used for the source component.
  BlendFactor source;

  /// Blending factor used for the destination component.
  BlendFactor dest;

  /// Blending operation used between source and destination components.
  BlendOp op;
};

/// Parameters that define \c depth, \c stencil, \c rasterizer and \c blending operations.
typedef struct RenderingState
{
  /// Combination of state flags that define rendering operation.
  uint32_t states;

  /// How triangle faces should be culled.
  TriangleFace cullFace;

  /// Depth buffer comparison function.
  ComparisonFunc depthFunc;

  /// Constant offset added to depth to alleviate z-fighting issues.
  float depthBias;

  /// Slope coefficient used for relative depth when calculating depth bias.
  float slopeDepthBias;

  /// Value to clamp depth bias, preventing artifacts on very high slopes.
  float clampDepthBias;

  /// Reference value for the stencil test.
  uint8_t stencilRefValue;

  /// Mask that is applied to reference value and stored value after the test.
  uint8_t stencilRefMask;

  /// Mask that is used to enable or disable writing of individual bits to stencil buffer.
  uint8_t stencilWriteMask;

  /// Custom alpha-blending constant.
  FloatColor blendConstant;

  /// Stencil function and operation that are performed for front-facing triangles.
  struct StencilState stencilFront;

  /// Stencil function and operation that are performed for back-facing triangles.
  struct StencilState stencilBack;

  /// Blending parameters that should be applied to color portion of components.
  struct Blend blendColor;

  /// Blending parameters that should be applied to alpha portion of components.
  struct Blend blendAlpha;
} RenderingState;

/// Graphics device that handles rendering state and scheduling.
struct Device_t;

#ifndef __cplusplus
  /// Graphics device that handles rendering state and scheduling.
  typedef struct Device_t Device;
#endif

// Buffer types and structures.

/// Buffer that is typically stored on graphics hardware.
typedef struct Buffer_t Buffer_t;

#ifndef __cplusplus
  /// Buffer that is typically stored on graphics hardware.
  typedef Buffer_t Buffer;
#endif

// Program types and structures.

/// Structure that describes the layout of a single buffer element.
typedef struct VertexElement
{
  /// Name of the component (variable name in GLSL or semantic name in HLSL).
  char name[64];

  /// Data format of each value in this element.
  ElementFormat format;

  /// Number of values used by this element.
  /// If "format" is "Undefined", this indicates number of bytes the element occupies.
  int32_t count;

  /// Channel to which the values of this element will be bound to. The most significant bit of this field
  /// has a special purpose, meaning that the data values are normalized (applies only to integers), so the
  /// number of channel is stored in first 31 bits.
  uint32_t channel;

  /// Offset in bytes relative to origin of the first buffer element to the current one.
  uint32_t offset;
} VertexElement;

/// Structure that describes a single physical element of shader program.
typedef struct ProgramElement
{
  /// Name of the element (e.g. variable, buffer or texture name, null-terminated).
  char name[64];

  /// Type of shader element.
  ShaderElement element;

  /// Shader to which this element belongs to.
  ShaderType shader;

  /// A virtual channel index, which will be associated with the appropriate buffer attached to that channel.
  uint32_t channel;

  /// Index of physical slot to which the element should be bound to. This can be either an actual binding
  /// point or a register number.
  int32_t index;

  /// Size of element in bytes.
  uint32_t size;
} ProgramElement;

/// Structure that describes a single (uniform) variable in a shader program.
typedef struct ProgramVariable
{
  /// Name of the element (e.g. variable, buffer or texture name, null-terminated).
  char name[64];

  /// Index that uniquely identifies this variable.
  int32_t index;

  /// Shader to which this element belongs to.
  ShaderType shader;

  /// Data format of each value in this variable.
  ElementFormat format;

  /// Number of values used by this variable.
  /// If "format" is "Undefined", this indicates number of bytes the element occupies.
  int32_t count;

  /// Size of variable in bytes.
  uint32_t size;

  /// Offset in a buffer where variable starts.
  uint32_t offset;
} ProgramVariable;

/// Shader program that is typically executed on graphics hardware.
typedef struct Program_t Program_t;

#ifndef __cplusplus
  /// Shader program that is typically executed on graphics hardware.
  typedef Program_t Program;
#endif

// Compute structures.

/// Compute texture parameters and characteristics.
typedef struct ComputeBindTextureFormat
{
  /// Channel to which the texture is bound to.
  uint32_t channel;

  /// Number of mipmap level that should be attached.
  int32_t mipLevel;

  /// Layer number from a volume or array texture to bound (-1 means an entire texture should be bound).
  int32_t layer;

  /// Type of access that will be used with the texture.
  ComputeTextureAccess access;

  /// Format of the texture's pixels.
  PixelFormat format;
} ComputeBindTextureFormat;

/// Compute shader program for general processing on GPU (GPGPU).
typedef struct ComputeProgram_t ComputeProgram_t;

#ifndef __cplusplus
  /// Compute shader program for general processing on GPU (GPGPU).
  typedef ComputeProgram_t ComputeProgram;
#endif

// Sampler structures.

/// Sampler parameters that are associated with a particular texture unit.
typedef struct SamplerState
{
  /// Minification texture filtering.
  TextureFilter filterMin;

  /// Magnification texture filtering.
  TextureFilter filterMag;

  /// Mipmapping texture filtering.
  TextureFilter filterMip;

  /// Texture coordinate addressing for S, T and R (U, V and W) coordinates.
  TextureAddress address[3];

  /// Special color constant to be used for TextureAddress::Border addressing mode.
  FloatColor borderColor;

  /// Total number of samples to be used with anisotropic filtering.
  int32_t anisotropy;

  /// Minimum level of detail for texture mipmap range.
  float minLOD;

  /// Maximum level of detail for texture mipmap range.
  float maxLOD;

  /// Offset from the calculated mipmap level.
  float biasLOD;

  /// Comparison function for texture values.
  ComparisonFunc compareFunc;

  /// Indicates whether comparison should be made against a particular reference value or simply fetched.
  uint8_t compareToRef; // 0 - false, 1 - true
} SamplerState;

/// Sampler object that defines how texture is read by the shaders.
typedef struct Sampler_t Sampler_t;

#ifndef __cplusplus
  /// Sampler object that defines how texture is read by the shaders.
  typedef Sampler_t Sampler;
#endif

// Texture structures.

/// One or more texture attribute flags combined together.
typedef uint32_t TextureAttributes;

/// Texture parameters and characteristics.
typedef struct TextureParameters
{
  /// Texture width (in pixels).
  int32_t width;

  /// Texture height (in pixels).
  int32_t height;

  /// Number of texture layers in case of Texture Array or depth in case of 3D textures.
  int32_t layers;

  /// Format of the texture's pixels.
  PixelFormat format;

  /// Texture type that defines how it is composed.
  TextureType type;

  /// Attributes that define the characteristics of the texture.
  TextureAttributes attributes;

  /// Number of multisamples used in the render target.
  int32_t multisamples;

  /// Depth/stencil format that will be used to create an associated buffer.
  PixelFormat depthStencil;
} TextureParameters;

/// Texture that contains image data typically stored in GPU memory.
typedef struct Texture_t Texture_t;

#ifndef __cplusplus
  /// Texture that contains image data typically stored in GPU memory.
  typedef Texture_t Texture;
#endif

// Surface types.

/// Raster surface that contains image in memory for pixel manipulation.
typedef struct Surface_t Surface_t;

#ifndef __cplusplus
  /// Raster surface that contains image in memory for pixel manipulation.
  typedef Surface_t Surface;
#endif

// Canvas types and structures.

/// One or more canvas attributes that define rendering behavior.
typedef uint32_t CanvasAttributes;

/// Signed Distance Field (SDF) parameters.
typedef struct SignedDistanceField
{
  /// Type of super-sampling for the field's rendering.
  SuperSampleSDF superSampleSDF;

  /// Distance that was used for generating the field.
  float signedFieldDistance;

  /// Color offset in YCH color space for rendering the shape's outline.
  Vector outlineOffsetSDF;

  /// Minimum field distance for the shape's outline.
  float outlineDistanceMinSDF;

  /// Maximum field distance for the shape's outline.
  float outlineDistanceMaxSDF;
} SignedDistanceField;

/// Sampler parameters that can be easily configured by the canvas.
typedef struct CanvasSamplerState
{
  /// Minification texture filtering.
  TextureFilter filterMin;

  /// Magnification texture filtering.
  TextureFilter filterMag;

  /// Mipmapping texture filtering.
  TextureFilter filterMip;

  /// Horizontal texture coordinate addressing.
  TextureAddress addressU;

  /// Vertical texture coordinate addressing.
  TextureAddress addressV;

  /// Special color constant to be used for TextureAddress::Border addressing mode.
  Color borderColor;
} CanvasSamplerState;

/// An image region defined by its texture number and bounding rectangle on that texture.
typedef struct ImageRegion
{
#ifdef __cplusplus
  /// Modifier flags that can be combined together.
  enum {
    /// Flip region vertically.
    Flip = 0x01,

    /// Mirror region horizontally.
    Mirror = 0x02,

    /// Rotate region by 90 degrees clockwise.
    Rotate = 0x04};
#endif

  /// Left position of the region.
  uint16_t left;

  /// Top position of the region.
  uint16_t top;

  /// Width of the region.
  uint16_t width;

  /// Height of the region.
  uint16_t height;

  /// Texture index associated with this region.
  uint16_t index;
} ImageRegion;

/// A single element in path declaration.
union PathElement
{
  /// Tag that defines a combination of command and number of values following such tag.
  struct
  {
    /// Path command enumeration combined with one of its attribute bits.
    uint8_t command;

    /// Field reserved for future use.
    uint8_t reserved;

    /// Number of "value" elements that follows this declaration.
    uint16_t length;
  } tag;

  /// A single 32-bit floating-point value of the path coordinates.
  float value;

#ifdef __cplusplus
  /// Creates a new path element uninitialized.
  PathElement() = default;

  /// Creates a new path element with the given command and length.
  PathElement(uint8_t command, uint16_t length = 0u)
  {
    tag.command = command;
    tag.reserved = 0;
    tag.length = length;
  }

  /// Creates a new path element with the given data value.
  PathElement(float value) { this->value = value; }
#endif
};

#ifndef __cplusplus
  /// A single element in path declaration.
  typedef union PathElement PathElement;
#endif

/// Canvas that can render geometry either in 2D or on a particular plane in 3D world.
typedef struct Canvas_t Canvas_t;

#ifndef __cplusplus
  /// Canvas that can render geometry either in 2D or on a particular plane in 3D world.
  typedef Canvas_t Canvas;
#endif

/// Image atlas, containing sub-images that can be rendered with canvas.
typedef struct ImageAtlas_t ImageAtlas_t;

#ifndef __cplusplus
  /// Image atlas, containing sub-images that can be rendered with canvas.
  typedef ImageAtlas_t ImageAtlas;
#endif

// TextRenderer types and structures.

/// 32-bit Unicode character type
typedef uint32_t UnicodeChar;

/// Individual text entry that will appear as rendered.
typedef struct TextEntryRect
{
  /// Starting character position inside the text (for Unicode, first byte).
  intptr_t position;

  /// Character's rectangle.
  RectF rectangle;
} TextEntryRect;

/// Modifier attributes that can be applied to the rendered text.
typedef struct TextRenderModifiers
{
  /// Global font scale that is applied to the whole rendered text. A default value of zero means that font
  /// scale will not be modified. Using values other than zero or one would likely result in not
  /// pixel-perfect text rendering, appearing blurry. However, this can be used for real-time text
  /// animations.
  float scale;

  /// Global spacing that will be added horizontally between text letters. This can be used to expand or
  /// shrink the text.
  float interleave;

  /// Global spacing that will be added vertically when drawing multiple lines of text.
  float verticalSpace;

  /// Blending effect to use (if left \c undefined, \c normal blending effect will be used).
  BlendingEffect effect;
} TextRenderModifiers;

/// Attributes and characteristics that define how font glyphs are rasterized.
typedef struct FontEffect
{
  /// Brightness of the letter's fill in range of [0, 1], where zero means the letter will appear completely
  /// dark and one means that letter will appear completely white.
  float fillBrightness;

  /// Opacity of the letter's fill in range of [0, 1], where zero means the letter will appear completely
  /// transparent (that is, not appear at all) and one means that the letter will appear completely opaque.
  float fillOpacity;

  /// Type of border that will appear around the text.
  FontBorder borderType;

  /// Thickness of the font's border in pixels.
  float borderThickness;

  /// Brightness of the font's border in range of [0, 1], where zero means the border will appear
  /// completely dark and one means that the border will appear completely white.
  float borderBrightness;

  /// Opacity of the font's border in range of [0, 1], where zero means the border will appear completely
  /// transparent (that is, not appear at all) and one means that the border will appear completely opaque.
  float borderOpacity;

  /// How strong the blur should be applied to letter's shadow (number of steps).
  float shadowSmoothness;

  /// Distance between letter and its shadow in pixels.
  PointF shadowDistance;

  /// Brightness of the letter's shadow in range of [0, 1], where zero means the shadow will appear
  /// completely dark and one means that the shadow will appear completely white.
  float shadowBrightness;

  /// Opacity of the letter's shadow in range of [0, 1], where zero means the shadow will appear completely
  /// transparent (that is, not appear at all) and one means that the shadow will appear completely opaque.
  float shadowOpacity;

  /// Distance in pixels for generation of Signed Distance Field (SDF) font glyphs. This parameter must be
  /// greater or equal to zero. If the value is not zero, then the font is considered SDF.
  float signedFieldDistance;
} FontEffect;

/// Parameters that define the appearance and important characteristics of the font.
typedef struct FontParameters
{
  /// Font family (e.g. "Helvetica").
  char family[128];

  /// Size of the font.
  float size;

  /// Font letter weight.
  FontWeight weight;

  /// Font letter stretch.
  FontStretch stretch;

  /// Font letter slant.
  FontSlant slant;

  /// Additional font attributes.
  FontAttributes attributes;

  /// Effect parameters that contribute to font rasterization.
  FontEffect effect;

#ifdef __cplusplus
  /// Creates font settings uninitialized.
  FontSettings() = default;

  /// Creates font settings with the given parameters.
  FontParameters(char const* family, float size, FontWeight weight = FontWeight::Normal,
    FontStretch stretch = FontStretch::Normal, FontSlant slant = FontSlant::None)
  : family{}, size(size), weight(weight), stretch(stretch), slant(slant), attributes(0),
    effect{1.0f, 1.0f, FontBorder::None, 1.0f, 0.25f, 0.75f, 3.0f, {2.0f, 2.0f}, 0.15f, 0.0f, 0.0f}
  { strncpy_s(this->family, sizeof(this->family), family, sizeof(this->family) - 1); }
#endif
} FontParameters;

/// Text renderer utility that can draw text on the canvas.
typedef struct TextRenderer_t TextRenderer_t;

#ifndef __cplusplus
  /// Text renderer utility that can draw text on the canvas.
  typedef TextRenderer_t TextRenderer;
#endif

/// 2D and 3D text rendering module.
typedef struct TextModeller_t TextModeller_t;

#ifndef __cplusplus
  /// 2D and 3D text rendering module.
  typedef TextModeller_t TextModeller;
#endif

// Grapher types.

/// 3D graph plotting module.
typedef struct Grapher_t Grapher_t;

#ifndef __cplusplus
  /// 3D graph plotting module.
  typedef Grapher_t Grapher;
#endif

// MeshModel types and structures.

/// 3D mesh model that has vertex and optionally index buffers for rendering.
typedef struct MeshModel_t MeshModel_t;

#ifndef __cplusplus
  /// 3D mesh model that has vertex and optionally index buffers for rendering.
  typedef MeshModel_t MeshModel;
#endif

// MeshBuffer types and structures.

/// Notification event regarding mesh loading or saving process. The notification callback must return 0 to
/// indicate that the process should continue; a non-zero value means that the loading process should be
/// interrupted.
typedef int32_t(*MeshLoadSaveFeedback)(char const* message, int32_t progress, void* user);

/// Calculated values for a single mesh vertex that can be modified by callback.
typedef struct MeshBufferEntry
{
  /// Vertex 3D position.
  Vector position;

  /// Vertex 3D normal (normalized).
  Vector normal;

  /// Vertex 3D tangent (normalized).
  Vector tangent;

  /// Vertex 2D texture coordinates.
  PointF texCoord;

  /// Vertex RGBA color.
  FloatColor color;
} MeshBufferEntry;

/// A portion of the mesh corresponding to a particular tag.
typedef struct MeshMetaTagPortion
{
  /// Starting index of the tag.
  int32_t firstIndex;

  /// Number of indices of the tag.
  int32_t indexCount;

  /// Starting vertex of the tag.
  int32_t firstVertex;

  /// Number of vertices of the tag.
  int32_t vertexCount;

  /// Tag's minimum boundaries.
  Vector boundsMin;

  /// Tag's maximum boundaries.
  Vector boundsMax;
} MeshMetaTagPortion;

/// Meta-tag, which describes a certain important axis-aligned bounding area inside a mesh.
typedef struct MeshMetaTag_t MeshMetaTag_t;

#ifndef __cplusplus
  /// Meta-tag, which describes a certain important axis-aligned bounding area inside a mesh.
  typedef MeshMetaTag_t MeshMetaTag;
#endif

/// List of meta-tags that describe important axis-aligned bounding areas inside a mesh.
typedef struct MeshMetaTags_t MeshMetaTags_t;

#ifndef __cplusplus
  /// List of meta-tags that describe important axis-aligned bounding areas inside a mesh.
  typedef MeshMetaTags_t MeshMetaTags;
#endif

/// Buffer that contains 3D mesh information.
typedef struct MeshBuffer_t MeshBuffer_t;

#ifndef __cplusplus
  /// Buffer that contains 3D mesh information.
  typedef MeshBuffer_t MeshBuffer;
#endif

// GaussianBlur types.

/// Gaussian Blur module.
typedef struct GaussianBlur_t GaussianBlur_t;

#ifndef __cplusplus
  /// Gaussian Blur module.
  typedef GaussianBlur_t GaussianBlur;
#endif

// KawaseBlur types.

/// Kawase Blur module.
typedef struct KawaseBlur_t KawaseBlur_t;

#ifndef __cplusplus
  /// Kawase Blur module.
  typedef KawaseBlur_t KawaseBlur;
#endif

// ColorDithering types.

/// Color dithering module.
typedef struct ColorDithering_t ColorDithering_t;

#ifndef __cplusplus
  /// Color dithering module.
  typedef ColorDithering_t ColorDithering;
#endif

// SelectionHighlight types.

/// Parameters that define how selection highlight technique is performed.
typedef struct SelectionHighlightParameters
{
  /// Color of the selection glow's outline.
  FloatColorRGB outlineColor;

  /// At which position outline begins (values of 1 or higher mean no outline).
  float outlineStart;

  /// How intense should the glow appear.
  float glowIntensity;

  /// Number of passes for the blur effect.
  int32_t blurPasses;

  /// Offset for the blur effect.
  PointF blurOffset;
} SelectionHighlightParameters;

/// Selection highlight module.
typedef struct SelectionHighlight_t SelectionHighlight_t;

#ifndef __cplusplus
  /// Selection highlight module.
  typedef SelectionHighlight_t SelectionHighlight;
#endif

// SpatialFog types.

/// Structure containing spatial fog characteristics.
typedef struct FogParameters
{
  /// Fog color.
  FloatColor color;

  /// Fog opacity.
  float opacity;

  /// Equation of the plane for ground fog.
  Vector4 groundPlane;

  /// Ground fog density factor.
  float densityGround;

  /// Either a distance (far plane) for linear fog or an in-scattering parameter for exponential fog.
  union {
    float distance;
    float scattering;
  };

  /// Either a bias for linear fog or an extinction parameter for exponential fog.
  union {
    float bias;
    float extinction;
  };
} FogParameters;

/// Module that performs both ground fog and distance-based fog simultaneously.
typedef struct SpatialFog_t SpatialFog_t;

#ifndef __cplusplus
  /// Module that performs both ground fog and distance-based fog simultaneously.
  typedef SpatialFog_t SpatialFog;
#endif

// Scene types and structures.

/// Parameters that define how shadows are rendered.
typedef struct ShadowParameters
{
  /// Primary exponent for ESM and EVSM techniques.
  float exponent1;

  /// Secondary exponent for ESM and EVSM techniques.
  float exponent2;

  /// Maximum variance delimiter used with VSM and EVSM techniques.
  float variance;

  /// Light bleeding sigma for reducing light bleeding artifacts with VSM and EVSM techniques.
  float bleedSigma;

  /// Bias parameter that is applied to depth derivatives in VSM technique.
  float bias;

  /// Sigma value for shadow map's gaussian blur.
  float blurSigma;

  /// Number of samples for shadow map's gaussian blur.
  int32_t blurSamples;
} ShadowParameters;

/// Parameters that define behavior of tone-mapping and bloom effects.
typedef struct ToneMappingBloom
{
  /// Amount to be subtracted from initial HDR colors to determine bloom.
  float bloomThreshold;

  /// Inverse gamma power to adjust the bloom color after threshold.
  float bloomGamma;

  /// Grayscale coefficients for red, green and blue components.
  Vector bloomCoefficients;

  /// Amount of color to shift into grayscale.
  float bloomColorShift;

  /// Sigma value of Gaussian Blur for bloom pixels.
  float bloomBlurSigma;

  /// Number of bloom pixels to sample during Gaussian blur.
  int32_t bloomBlurSamples;

  /// Maximum allowed level of white for tone-mapping.
  float toneWhite;

  /// Conversion coefficients to calculate Luma from RGB during tone-mapping.
  Vector toneFactors;

  /// Power used to adjust the curve of frosted glass equation.
  float frostedPower;

  /// Number of buckets per pixel for OIT technique.
  float glassyBuckets;
} ToneMappingBloom;

/// Parameters that define how ambient occlusion is performed.
typedef struct AmbientOcclusionParameters
{
  /// Radius of the occlusion.
  float radius;

  /// Number of kernel samples.
  int32_t samples;

  /// Linear attenuation.
  float attenuation;

  /// Contrast of the occlusion.
  float contrast;

  /// Bias value to resolve depth precision issues.
  float depthBias;

  /// Bias value to prevent sampling close to tangent surface.
  float kernelBias;

  /// Sigma coefficient for blur filter.
  float blurSigma;

  /// Fall-off coefficient for detecting depth discontinuities in blur filter.
  float blurFallOff;

  /// Strength of the effect.
  float strength;
} AmbientOcclusionParameters;

/// Parameters that define how parallax mapping is performed.
typedef struct ParallaxMappingParameters
{
  /// Scale that defines how height value from parallax map translates into 3D depth.
  float scale;

  /// Minimum number of samples to read per pixel.
  int32_t samplesMin;

  /// Maximum number of samples to read per pixel.
  int32_t samplesMax;

  /// Occlusion strength applied from Occlusion Map (alpha-channel of Normal Map).
  float occlusion;
} ParallaxMappingParameters;

/// Light source parameters in 3D scene.
typedef struct SceneLight
{
  /// Ambient color.
  FloatColorRGB ambientColor;

  /// Range at which light attenuation starts (FLT_MAX means no attenuation should be applied).
  float attenuationStart;

  /// Albedo color.
  FloatColorRGB albedoColor;

  /// Range at which light attenuation ends. This must be equal to or higher than \c attenuationStart.
  float attenuationEnd;

  /// Specular color.
  FloatColorRGB specularColor;

  /// Exponent for specular light reflections.
  float specularExponent;

  /// Position of the light source.
  Vector position;

  /// Intensity of the light.
  float intensity;

  /// Direction of the light source (non-zero value indicates a spotlight, zero values means omni-light).
  Vector direction;

  /// Angle at which spotlight starts to fade in range of [0, PI).
  float angle;

  /// Angle after which spotlight is completely dark. This should be equal to or higher than \c angle.
  float angleCutoff;

  /// Index of the shadow caster associated with the light source.
  /// A value of -1 indicates light source does not cast shadows.
  int32_t shadowCaster;

  /// Bitmask that defines what objects are affected by this light.
  /// A value of zero means that light affects all objects.
  uint32_t bitmask;

  /// Reserved, must be set to zero.
  uint32_t reserved;

  /// Custom payload value.
  ObjectPayload payload;
} SceneLight;

/// Material that describes a particular object in 3D world.
typedef struct ObjectMaterial
{
  /// Technique that describes how light is reflected off the object's surface.
  TechniqueLighting technique;

  /// Ambient color that is always received by the object regardless the position of light.
  FloatColorRGB ambientColor;

  /// Strength of received shadows. A value of zero means no shadows will be received.
  float shadows;

  /// Albedo color, where alpha-channel is typically a Bloom Factor (glare from strong reflections).
  FloatColor albedoColor;

  /// Specular color, which is added depending on reflected vector from material's surface.
  FloatColorRGB specularColor;

  /// Specular Exponent that defines how short or wide specular reflection appears.
  float specularExponent;

  /// Emissive color, which is always added before any lights.
  FloatColorRGB emissiveColor;

  /// Strength of ambient occlusion. A value of zero means no occlusion will be received.
  float occlusion;

  /// Roughness of the object's surface that defines how light is reflected.
  Vector roughness;

  /// A bitmask that defines what lights affect this object.
  /// A value of zero means that this object is affected by all lights.
  uint32_t bitmask;

  /// Strength of Frosted Glass effect when rendering order-independent transparency.
  float frostedGlass;

  /// Custom payload value.
  ObjectPayload payload;
} ObjectMaterial;

/// Parameters that define the appearance of waves simulation.
typedef struct OceanWavesParameters
{
  /// Resolution of the simulation textures.
  int32_t resolution;

  /// General direction in which the waves propagate.
  PointF wind;

  /// Size of the generated waves.
  float waveSize;

  /// Choppiness of the generated waves.
  float choppiness;
} OceanWavesParameters;

/// Material that describes ocean water surface in a 3D simulation.
typedef struct OceanMaterial
{
  /// Ambient color.
  FloatColorRGB ambientColor;

  /// Fresnel Coefficient (reflectance at normal incidence).
  float fresnel;

  /// Ambient color that is always received by the ocean regardless the position of light.
  FloatColor albedoColor;

  /// Specular color, which is added depending on reflected vector from ocean's surface.
  FloatColorRGB specularColor;

  /// Specular color, which is added depending on reflected vector from ocean's surface.
  float specularExponent;

  /// Emissive color, which is always added before any lights.
  FloatColorRGB emissiveColor;

  /// Extinction of the ocean's surface, which determines its transparency.
  float extinction;

  /// Strength of a shadows when projected to the object's surface.
  /// A value of zero means shadows are not rendered and/or ignored.
  float shadows;

  /// A bitmask that defines what lights affect this object.
  /// A value of zero means that this object is affected by all lights.
  uint32_t bitmask;
} OceanMaterial;

/// Cumulative rendering attributes that affect how the scene is filtered.
typedef uint32_t TextureCabinetAttributes;

/// Rendering attributes that define what type of resources are used and how rendering is performed.
typedef uint32_t SceneAttributes;

/// Container for storing 3D scene lights.
typedef struct SceneLights_t SceneLights_t;

#ifndef __cplusplus
  /// Container for storing 3D scene lights.
  typedef SceneLights_t SceneLights;
#endif

/// Container for storing 3D object materials.
typedef struct ObjectMaterials_t ObjectMaterials_t;

#ifndef __cplusplus
  /// Container for storing 3D object materials.
  typedef ObjectMaterials_t ObjectMaterials;
#endif

/// A collection of drawable textures used to render the scene.
typedef struct TextureCabinet_t TextureCabinet_t;

#ifndef __cplusplus
  /// A collection of drawable textures used to render the scene.
  typedef TextureCabinet_t TextureCabinet;
#endif

/// A source that casts shadows that can be shared among multiple light sources.
typedef struct ShadowCaster_t ShadowCaster_t;

#ifndef __cplusplus
  /// A source that casts shadows that can be shared among multiple light sources.
  typedef ShadowCaster_t ShadowCaster;
#endif

/// Module that manages shadow maps produced by one or more shadow casters.
typedef struct ShadowCastingAtlas_t ShadowCastingAtlas_t;

#ifndef __cplusplus
  /// Module that manages shadow maps produced by one or more shadow casters.
  typedef ShadowCastingAtlas_t ShadowCastingAtlas;
#endif

/// 3D rendering scene.
typedef struct Scene_t Scene_t;

#ifndef __cplusplus
  /// 3D rendering scene.
  typedef Scene_t Scene;
#endif

/// 3D ocean semi-infinite wave field rendering module.
typedef struct OceanSimulation_t OceanSimulation_t;

#ifndef __cplusplus
  /// 3D ocean semi-infinite wave field rendering module.
  typedef OceanSimulation_t OceanSimulation;
#endif

// ObjectModel types.

/// Data type for storing unique object identification numbers.
typedef uintptr_t ObjectModelID;

/// Alignment for all three axes that determine the placement of mesh around its model.
typedef struct MeshAligns
{
  /// Alignment for X axis.
  MeshAlign x;

  /// Alignment for Y axis.
  MeshAlign y;

  /// Alignment for Z axis.
  MeshAlign z;

  /// Bias value used for volume size adjustment.
  float bias;

#ifdef __cplusplus
  /// Creates mesh alignments uninitialized.
  MeshAligns() = default;

  /// Creates new alignments with the given values.
  MeshAligns(MeshAlign x = MeshAlign::Origin, MeshAlign y = MeshAlign::Positive,
    MeshAlign z = MeshAlign::Origin, float bias = 0.1f) : x(x), y(y), z(z), bias(bias) {}
#endif
} MeshAligns;

/// Object model represented in a working 3D environment.
typedef struct ObjectModel_t ObjectModel_t;

#ifndef __cplusplus
  /// Object model represented in a working 3D environment.
  typedef ObjectModel_t ObjectModel;
#endif

/// Container and manager for working with multiple 3D scene objects.
typedef struct ObjectModels_t ObjectModels_t;

#ifndef __cplusplus
  /// Container and manager for working with multiple 3D scene objects.
  typedef ObjectModels_t ObjectModels;
#endif

/// Iterator for retrieving individual objects from an object model's container.
typedef struct ObjectModelsIterator_t ObjectModelsIterator_t;

#ifndef __cplusplus
  /// Container and manager for working with multiple 3D scene objects.
  typedef ObjectModelsIterator_t ObjectModelsIterator;
#endif

/// A container that represents a particular view that watches objects in the world.
typedef struct ObjectModelView_t ObjectModelView_t;

#ifndef __cplusplus
  /// A container that represents a particular view that watches objects in the world.
  typedef ObjectModelView_t ObjectModelView;
#endif

/// Comparison function for a pair of objects in a 3D scene.
typedef int32_t(*ObjectModelCompareFunc)(ObjectModel_t const* object1, ObjectModel_t const* object2,
  void* user);

// MeshVoxel types.

/// Voxel representation of a 3D mesh model.
typedef struct MeshVoxel_t MeshVoxel_t;

#ifndef __cplusplus
  /// Voxel representation of a 3D mesh model.
  typedef MeshVoxel_t MeshVoxel;
#endif

/// Mesh voxel rendering function.
typedef void(*MeshVoxelVisualizeFunc)(Vector const* position, Vector const* size, FloatColor const* color,
  void* user);

// SceneMeshMaterial types.

/// Shading parameters for scene mesh material.
typedef struct SceneMeshMaterialShading
{
  /// Ambient color.
  FloatColorRGB ambient;

  /// Bloom (glare) factor.
  float bloom;

  /// Diffuse color (alpha-channel denotes transparency).
  FloatColor diffuse;

  /// Specular color.
  FloatColorRGB specular;

  /// Specular exponent.
  float specularExponent;

  /// Emissive color.
  FloatColorRGB emissive;

  /// Lighting model (0 - Phong, 1 - Minnaert, 2 - Cook-Torrance, 3 - Oren-Nayar)
  int32_t lighting;

  /// Roughness values for non-Phong lighting models.
  Vector roughness;
} SceneMeshMaterialShading;

/// A range of indices in the mesh that a material applies to.
typedef struct SceneMeshMaterialRange
{
  /// Starting index.
  int32_t indexStart;

  /// Number of indices.
  int32_t indexCount;
} SceneMeshMaterialRange;

/// Material that describes how a portion of a scene mesh geometry should look like.
typedef struct SceneMeshMaterial_t SceneMeshMaterial_t;

#ifndef __cplusplus
  /// Material that describes how a portion of a scene mesh geometry should look like.
  typedef SceneMeshMaterial_t SceneMeshMaterial;
#endif

/// Container for scene mesh material that describe the appearance of scene mesh geometry.
typedef struct SceneMeshMaterials_t SceneMeshMaterials_t;

#ifndef __cplusplus
  /// Container for scene mesh material that describe the appearance of scene mesh geometry.
  typedef SceneMeshMaterials_t SceneMeshMaterials;
#endif

// SceneMeshLatches types.

/// A latch in 3D scene mesh, which describes a bone joint connection or a movement waypoint.
typedef struct SceneMeshLatch
{
  /// Name of the latch.
  char name[256];

  /// Position of the latch.
  Vector position;

  /// Type of the latch.
  uint16_t type;

  /// Group of the latch.
  uint16_t group;

  /// Orientation of the latch.
  Quaternion orientation;
} SceneMeshLatch;

/// A collection of marks in a 3D mesh to denote bone joint connections and movement waypoints.
typedef struct SceneMeshLatches_t SceneMeshLatches_t;

#ifndef __cplusplus
  /// A collection of marks in a 3D mesh to denote bone joint connections and movement waypoints.
  typedef SceneMeshLatches_t SceneMeshLatches;
#endif

// SceneMesh types.

/// High-level wrapper around a rendereable and pickable mesh in 3D scene.
typedef struct SceneMesh_t SceneMesh_t;

#ifndef __cplusplus
  /// High-level wrapper around a rendereable and pickable mesh in 3D scene.
  typedef SceneMesh_t SceneMesh;
#endif

/// Container for high-level wrappers of rendereable and pickable objects in 3D scene.
typedef struct SceneMeshes_t SceneMeshes_t;

#ifndef __cplusplus
  /// Container for high-level wrappers of rendereable and pickable objects in 3D scene.
  typedef SceneMeshes_t SceneMeshes;
#endif

// Application types and structures.

/// Structure that contains all the parameters necessary to create a new application and its window.
typedef struct ApplicationConfiguration
{
  /// Initial size of the application window.
  Point size;

  /// Initial state of application window.
  ApplicationWindowState state;

  /// Initial position of application window. If both X and Y are set to INT32_MAX, then a default position
  /// will  be used.
  Point position;

  /// Platform-specific fields that is required for startup.
  union
  {
    /// Fields specific to Windows platform.
    struct
    {
      /// Handle of application's instance.
      UntypedHandle handleInstance;

      /// Handle of application's "small" icon.
      UntypedHandle handleIconSmall;

      /// Handle of application's "big" icon.
      UntypedHandle handleIconBig;

      /// Name of application window class.
      char windowClassName[32];
    } win;

    /// Fields specific to Linux platform.
    struct
    {
      /// Type of rendering used with the application.
      uint8_t renderingType;

      /// Number of command-line arguments.
      int32_t parameterCount;

      /// List of command-line arguments.
      char** parameterStrings;
    } nx;
  } startup;
} ApplicationConfiguration;

/// Application helper module.
typedef struct Application_t Application_t;

#ifndef __cplusplus
  /// Application helper module.
  typedef Application_t Application;
#endif

/// Basic application event.
typedef void(*EventFunc)(Application_t* application, void* user);

/// Application creation event.
typedef LibraryBool(*BoolFunc)(Application_t* application, void* user);

/// Application mouse handling event.
typedef void(*MouseFunc)(Application_t* application, MouseEvent event, MouseButton button,
  Point const* position, void* user);

/// Application keyboard handling event.
typedef void(*KeyboardFunc)(Application_t* application, KeyEvent event, int32_t virtualKey, uint16_t keyCode,
  void* user);

/// Event function for application status change events.
typedef void(*StatusFunc)(Application* application, ApplicationEvent event, void* user);

/// Custom application message handling event.
typedef LibraryBool(*EventHookFunc)(Application_t* application, void const* event, void* user);

/// Events that are invoked by the application. Each of these fields is optional, so if a particular event
/// is set to NULL, it will not be invoked and default handler will be used.
typedef struct ApplicationEvents
{
  /// Event invoked during startup to load application resources. If this function returns \c false,
  /// application creation will fail.
  BoolFunc eventCreate;

  /// Event invoked during application shutdown to release the resources.
  EventFunc eventDestroy;

  /// Event invoked when application needs to render contents of the window.
  EventFunc eventRender;

  /// Event invoked when a mouse event has been registered.
  MouseFunc eventMouse;

  /// Event invoked when a key event has been registered.
  KeyboardFunc eventKey;

  /// Event invoked when an application status has changed.
  StatusFunc eventStatus;

  /// Event invoked every time the application is idle.
  BoolFunc eventIdle;

  /// Event invoked when application window is resized.
  EventFunc eventResize;

  /// Event hook invoked to process application events.
  EventHookFunc eventHook;
} ApplicationEvents;

// ActorCamera types and structures.

/// Camera position, rotation and distance constraints. If the difference between min and max constraint on
/// a particular axis is almost zero or less, then no constraint is applied.
typedef struct CameraConstraints
{
  /// Minimum position allowed for camera positioning. "w" component is a minimum distance constraint.
  Vector4 positionMin;

  /// Maximum position allowed for camera positioning. "w" component is a maximum distance constraint.
  Vector4 positionMax;

  /// Minimum camera rotation angles. "w" component is a minimum angle for Lenticular printing rotation.
  Vector4 rotationMin;

  /// Maximum camera rotation angles. "w" component is a maximum angle for Lenticular printing rotation.
  Vector4 rotationMax;
} CameraConstraints;

/// Camera module that can represent both first-person and third-person views for 3D world exploration and
/// object manipulation.
typedef struct ActorCamera_t ActorCamera_t;

#ifndef __cplusplus
  /// Camera module that can represent both first-person and third-person views for 3D world exploration and
  /// object manipulation.
  typedef ActorCamera_t ActorCamera;
#endif

// Timer types.

/// Multimedia timer that can accurately calculate latency, frame rate and provide time-based processing.
typedef struct Timer_t Timer_t;

#ifndef __cplusplus
  /// Multimedia timer that can accurately calculate latency, frame rate and provide time-based processing.
  typedef Timer_t Timer;
#endif

// Widget types.

/// A flexible structure for storing property data.
typedef union WidgetPropertyData
{
  /// Data represented as 32-bit signed integer.
  int32_t valueInteger;

  /// Data represented as 64-bit signed integer.
  int64_t valueInt64;

  /// Data represented as 32-bit floating-point.
  float valueFloat;

  /// Data represented as 64-bit floating-point.
  double valueReal;

  /// Data represented as 8-bit boolean.
  bool valueBool;

  /// Data represented as 2-component 32-bit floating-point vector.
  PointF valuePoint;

  /// Data represented as 3-component 32-bit floating-point vector.
  Vector valueVector;

  /// Data represented as a rectangle composed of four floating-point values.
  RectF valueRect;

  /// Data represented as margins containing four floating-point values.
  Margins valueMargins;

  /// Data represented as 32-bit unsigned integer color.
  Color valueColor;

  /// Data represented as two 32-bit unsigned integer colors.
  ColorPair valueColorPair;

  /// Data represented as four 32-bit unsigned integer colors.
  ColorRect valueColorRect;

  /// Data represented as 8-bit unsigned integer enumeration.
  uint8_t valueEnum;

  /// Data represented as 184-byte null-terminated string. The first byte is actually a string length;
  /// if this byte is set to 255, then the string does not fit and must be retrieved using other means.
  char valueString[184];

  /// Data represented as font parameters structure.
  FontParameters valueFont;
} WidgetPropertyData;

/// Information about a widget property.
typedef struct WidgetProperty
{
  /// Name of the property.
  char name[256];

  /// Data type of the property.
  WidgetPropertyType type;

  /// Behavior of the property.
  WidgetPropertyBehavior behavior;

  /// Additional attributes of the property.
  uint16_t attributes;

  /// Location of the property in the list of existing properties. This is an opaque value that loosely
  /// determines next property to be iterated. The actual value is temporary and valid only during continuous
  /// iteration. Any change to properties invalidates all previous iteration values.
  /// A value of zero indicates an invalid or "undefined" location.
  uint16_t location;

  /// Reserved bits, must be set to zero.
  uint16_t reserved;

  /// Contents of the property.
  WidgetPropertyData data;
} WidgetProperty;

/// A widget that represents a basic building block of user interface.
typedef struct Widget_t Widget_t;

#ifndef __cplusplus
  /// A widget that represents a basic building block of user interface.
  typedef Widget_t Widget;
#endif

/// Widget's external callback event type.
typedef LibraryBool(*WidgetExternalEvent)(struct Widget_t* widget, char const* event, void* user);

#ifdef __cplusplus
  } // namespace pxt
#endif