first commit

This commit is contained in:
2026-06-22 11:49:35 +02:00
commit d805f2ba86
619 changed files with 126873 additions and 0 deletions

125
include/engine/core/ace.h Normal file
View File

@ -0,0 +1,125 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __NACE__
#define __NACE__
#include "nstring/nstring.h"
#include "container/narray_list.h"
#include "container/nlist.h"
namespace GS {
namespace ACE {
class Manager;
static const int max_command_param = 3; /// Maximum number of parameters to a command.
#define AceCommandNop -1 ///< No operator (can be used to pause execution (ie: "Nop 1000;" will pause 1 sec)).
#define AceCommandExec -2 ///< Internal use.
#define AceCommandLoop -3 ///< Loop position.
#define AceCommandNext -4 ///< Reset PC back to the loop position (default: 0, reset script).
/*!
@short ACE base command.
@author Emmanuel Julien (ejulien@gsworks.fr)
*/
struct Command
{
int code; ///< Command code.
float duration, ///< Command duration in ms.
duration_left, ///< Command duration still left to execute in ms.
parm[max_command_param]; ///< Command parameter.
bool operator == (const Command &other)
{
if ((code != other.code) || (duration != other.duration))
return false;
for (int n = 0; n < max_command_param; ++n)
if (parm[n] != other.parm[n])
return false;
return true;
}
/// Mark a command as executed in the pipeline.
void SetDone()
{ duration_left = 0; }
};
/*!
@short ACE (Asynchronous Command Execution) unit.
@author Emmanuel Julien (ejulien@gsworks.fr)
*/
class Unit
{
friend class Manager;
protected:
bool is_done; // this flag is raised on the next update following the last command execution
List <Command> list;
List <Command> ::Item *pc, *loop_pc;
/// Execute a command.
virtual bool ExecCommand(Command *cmd, float dt);
public:
bool IsCommandListDone() const
{ return is_done; }
void DumpCommandList();
void ResetCommandList();
Unit();
virtual ~Unit() {}
};
/*!
@short ACE command definition.
*/
struct Define
{
String id;
int code;
int nparm;
};
/*!
@short ACE manager.
ACE is a mini script system that provides a way to automate
the execution of a series of actions on an object.
@author Emmanuel Julien (ejulien@gsworks.fr)
*/
class Manager
{
ArrayList <Define *> define_list; ///< List of defined command.
public:
/*!
@short Load a string command list in a unit.
@return Number of generated commands, -1 on error.
*/
int LoadACECommandList(const char *str, Unit *) const;
/// Define a new command in the manager.
bool DefineACECommand(const char *command, int code, int nparm, bool user_code = true);
/// Update a unit.
void UpdateACEUnit(Unit *, float dt);
Manager();
virtual ~Manager();
};
} // ACE
} // GS
#endif // __NACE__

View File

@ -0,0 +1,48 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __NCACHEDGRAPHICRESOURCEFACTORY__
#define __NCACHEDGRAPHICRESOURCEFACTORY__
#include "core/graphic_resource_factory.h"
#include "core/geometry.h"
#include "core/emitter.h"
#include "core/shader.h"
#include "picture/pict.h"
#include "metafile/nml_object.h"
namespace GS {
namespace Core {
/*
@short Cached graphic resource factory.
@author Emmanuel Julien (ejulien@gsworks.fr)
*/
struct CachedResourceFactory : public ResourceFactory
{
SharedList <Geometry *> geometries;
SharedList <Material *> materials;
SharedList <Shader *> shaders;
SharedList <ParticleModel *> particle_models;
SharedList <Picture *> pictures;
virtual Picture *LoadPicture(const char *);
virtual Geometry *LoadGeometry(const char *);
virtual Material *LoadMaterial(const char *);
virtual Shader *LoadShader(const char *);
virtual ParticleModel *LoadParticleModel(const char *);
virtual uint GetCachedResourceCount();
virtual uint PurgeCache();
};
} // Graphic
} // GS
#endif // __NCACHEDGRAPHICRESOURCEFACTORY__

View File

@ -0,0 +1,36 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __NCACHEDAUDIORESOURCEFACTORY__
#define __NCACHEDAUDIORESOURCEFACTORY__
#include "core/mixer_resource_factory.h"
#include "core/sound.h"
#include "container/nlist.h"
namespace GS {
namespace Audio {
/*
@short Cached audio resource factory.
@author Emmanuel Julien (ejulien@gsworks.fr)
*/
struct CachedResourceFactory : public ResourceFactory
{
SharedList <Sound *> sounds;
virtual Sound *LoadSound(const char *);
CachedResourceFactory(IMixer &m) : ResourceFactory(m) {}
};
} // Audio
} // GS
#endif // __NCACHEDAUDIORESOURCEFACTORY__

View File

@ -0,0 +1,46 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __NCACHEDRENDERERRESOURCEFACTORY__
#define __NCACHEDRENDERERRESOURCEFACTORY__
#include "core/renderer_resource_factory.h"
#include "container/nlist.h"
namespace GS {
namespace Render {
/*
@short Cached renderer resource factory.
@author Emmanuel Julien (ejulien@gsworks.fr)
*/
struct CachedRendererResourceFactory : public RendererResourceFactory
{
SharedList <Geometry *> geometries;
SharedList <Material *> materials;
SharedList <Texture *> textures;
SharedList <Shader *> shaders;
virtual Geometry *LoadGeometry(const char *, bool bypass_cache = false, Geometry * = 0);
virtual Material *LoadMaterial(const char *, bool bypass_cache = false, Material * = 0);
virtual Texture *LoadTexture(const char *, bool bypass_cache = false, Texture * = 0);
virtual Shader *LoadShader(const char *, bool bypass_cache = false, Shader * = 0);
virtual void ListCachedResources();
virtual uint GetCachedResourceCount();
virtual uint PurgeCache();
CachedRendererResourceFactory(Renderer &r) : RendererResourceFactory(r) {}
};
} // Render
} // GS
#endif // __NCACHEDRENDERERRESOURCEFACTORY__

View File

@ -0,0 +1,152 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __NCAMERA__
#define __NCAMERA__
#include "core/item.h"
#include "geometry/frustum.h"
#include "geometry/rect.h"
namespace GS {
namespace Core {
class Light;
/*!
@short Camera.
- World space:
Described by the world_matrix,
transform from object space to world space.<br>
- Camera space:
Described by the camera_matrix,
transform from world space to camera space.<br>
- Projection matrix:
Transform from a given space (usually camera space)
to a 2D orthonormal space.<br>
- View matrix:
Transform from the 2D orthonormal space
to the view (screen) space.<br>
This class is not managed, the user is responsible for freeing it.
For a managed implementation please see S3D::Scene::nMCamera.
@author Emmanuel Julien (ejulien@gsworks.fr)
*/
class Camera : public Item
{
public:
/*!
@name Aspect ratio system.
@note On a 16/9 display using a PC resolution the display is stretched
horizontally to fill the whole display area, in such case calling
using ASPECTRATIO_16_9 as the aspect ratio correction will shrink
the render to compensate for the distortion.
@{
*/
/// Compute the aspect ration based on the output dimensions.
#define AR_Auto (-1.f)
#define AR_Square (1.f)
#define AR_Television (1.33f)
#define AR_Pc AR_Television
#define AR_35mm (1.37f)
#define AR_Widescreen (1.78f)
#define AR_EuropeanTheatricalStandard (1.66f)
#define AR_AmericanTheatricalStandard (1.85f)
#define AR_AnamorphicWidescreen (2.35f)
float aspect_ratio; ///< Aspect ratio horizontal correction.
bool aspect_ratio_ref_yaxis; ///< Reference (fixed) axis for aspect ratio correction.
/// Compute the current aspect ratio correction coefficients.
Vector4 ComputeAspectRatioCorrection(const fRect &viewport, float global_ar = 1.f) const;
/// @}
/// Setup render object.
virtual void RenderSetup(ResourceFactories * = 0) {}
/// Convert from world coordinate to normalized screen coordinate.
bool WorldToScreen(const fRect &viewport, const Vector4 &in, Vector4 &out, bool normalize = true);
/// Convert from normalized screen coordinate to world.
Vector4 ScreenToWorld(const fRect &viewport, float x, float y, float z = 1, float ar = -1);
/// Compute camera projection matrix.
void ComputeProjectionMatrix(const fRect &viewport, Matrix4 &m) const;
/// Compute camera view frustum.
void ComputeFrustum(Frustum &, const fRect &viewport, float z_near = -1, float z_far = -1) const;
/// Adjust this camera so that its viewport matches the viewport of a given light.
void AlignTo(const Light &);
/// Compute world hierarchy matrix.
virtual void ComputeMatrix();
/// Get near clipping plane.
float GetNearClippingPlane() const { return z_near; }
/// Get far clipping plane.
float GetFarClippingPlane() const { return z_far; }
/// Set near clipping plane.
void SetNearClippingPlane(float z) { z_near = z; }
/// Set far clipping plane.
void SetFarClippingPlane(float z) { z_far = z; }
/// Set the camera zoom factor, relative to z = 1 meter.
void SetZoomFactor(float zf = Units::Mtr(1.9f));
/*!
@short Set the camera field of view.
@note FOV must be in the [Deg(0),Deg(180)[ range.
@see GetFov().
*/
void SetFov(float fov = Units::Deg(60));
/*!
@short Get camera fov.
@note This value is converted on the fly from the current zoom factor.
If you need it frequently and as this class only store fov as the
zoom factor you may want to cache the fov value in your application
to avoid possible numerical drift.
*/
float GetFov() const;
/// Set viewport (all values in range [0,1]).
void SetViewport(float origin_x, float origin_y, float width, float height);
Frustum frustum; ///< View frustum.
float z_near; ///< Z near clipping plane.
float z_far; ///< Z far clipping plane.
bool is_orthographic; ///< Is the camera using an orthographic projection.
float ortho_w; ///< Orthographic view width.
float ortho_h; ///< Orthographic view height.
float zoom_factor;
Matrix4 custom_projection;
bool is_occulus_camera;
float tan_up, tan_down, tan_left, tan_right;
/*!
@name Serialization.
@{
*/
bool FromMetaTag(NML::Tag &);
NML::Tag *AsMetaTag();
/// @}
Camera();
};
} // Core
} // GS
#endif //__NCAMERA__

View File

@ -0,0 +1,70 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __NCLOCK__
#define __NCLOCK__
#include "memory/nshared_ptr.h"
#include "container/smart_median_average.h"
namespace GS {
namespace Core {
/*!
@short Clock
@author Emmanuel Julien (ejulien@nworks.fr)
*/
class Clock : public SharedObject
{
bool pause;
int fixed_delta; ///< Fixed dt (ms).
int _gtick, gtick; ///< System's global tick counter.
int clock_scale; ///< System clock scale factor (x1000).
int dt_clock; ///< Delta frame.
int dt_error;
SmartMedianAverage <int> dt_clock_filter;
public:
void Reset();
void Update();
void Pause(bool = true);
/// Sync to current hardware clock (skipping unaccounted dt_clock).
void EatDeltaClock();
float Getf() const;
float GetDeltaf() const;
void SetScalef(float = 1.f);
float GetScalef() const;
/// Set fixed delta clock in seconds.
void SetFixedDeltaFramef(float = -1.0);
int GetDelta() const { return dt_clock; }
void SetScale(int k = 1000) { clock_scale = k; }
int GetScale() const { return clock_scale; }
int Get() const { return gtick; }
Clock();
};
typedef SharedPtr <Clock> sClock;
} // Core
} // GS
#endif // __NCLOCK__

View File

@ -0,0 +1,70 @@
/* -----------------------------------------------------------------------------
nEngine - GSFramework
Copyright 2001-2011 Emmanuel Julien. All Rights Reserved.
------------------------------------------------------------------------------*/
#ifndef __NPROFILER_TOOLS__
#define __NPROFILER_TOOLS__
#include "color/color.h"
#include "nstring/nstring.h"
/*!
@short Core profiler tools.
@author Emmanuel Julien (ejulien@nworks.fr)
*/
namespace GS {
namespace Render {
class Renderer;
class RasterFont;
}
namespace Core {
enum NumberFormat
{
Count,
MemorySize
};
template <class T> const Color &GetColorCode(const T &v, const T &warning, const T &alert)
{
if (v > alert)
return Color::Red;
if (v > warning)
return Color::Green;
return Color::White;
}
/// Format a value to string.
template <class T> String FormatNumber(const T &v, NumberFormat format = Count)
{
switch (format)
{
case Count:
if (v < 1000)
return String::Format("%d", (int)v);
else if (v < 1000000)
return String::Format("%.01fK", (float)v / 1000);
return String::Format("%.01fM", (float)v / 1000000);
case MemorySize:
if (v < 1000)
return String::Format("%dB", (int)v);
else if (v < 1000000)
return String::Format("%.01fKB", (float)v / 1000.f);
return String::Format("%.01fMB", (float)v / 1000000.f);
}
return String() << v;
}
/// Draw allocator profiler text.
void DrawAllocProfilerText(Render::Renderer &, Render::RasterFont *[2], float &x, float &y, float width = 0, float height = 0);
} // Core
} // GS
#endif // __NPROFILER_TOOLS__

View File

@ -0,0 +1,38 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __EMBEDDEDRESOURCEEXTRACTOR__
#define __EMBEDDEDRESOURCEEXTRACTOR__
#include "core/embedded_resource_handler_interface.h"
namespace GS {
namespace Core {
//
struct EmbeddedResourceExtractor : public IEmbeddedResourceHandler
{
bool extract_to_ram;
/*
@name Provide support for legacy embedded resources.
@{
*/
virtual bool ExtractEmbeddedMaterial(String &out, NML::Tag &, const char *context, int slot);
virtual bool ExtractEmbeddedShaderTree(String &out, NML::Tag &, const char *context);
/// @}
/// Warning: Do not use ram-based extraction in production code!
EmbeddedResourceExtractor(bool extract_to_ramdisk = false);
};
} // Core
} // GS
#endif // __EMBEDDEDRESOURCEEXTRACTOR__

View File

@ -0,0 +1,36 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __IEMBEDDEDRESOURCEHANDLER__
#define __IEMBEDDEDRESOURCEHANDLER__
#include "ntypes.h"
namespace GS {
class String;
namespace NML { class Tag; }
namespace Core {
//
struct IEmbeddedResourceHandler
{
virtual bool ExtractEmbeddedMaterial(String &nUnused(out), NML::Tag &, const char *nUnused(context), int nUnused(slot)) { return false; }
virtual bool ExtractEmbeddedShaderTree(String &nUnused(out), NML::Tag &, const char *nUnused(context)) { return false; }
virtual ~IEmbeddedResourceHandler() {}
static IEmbeddedResourceHandler *Get();
static void Set(IEmbeddedResourceHandler *);
};
} // Core
} // GS
#endif // __IEMBEDDEDRESOURCEHANDLER__

View File

@ -0,0 +1,224 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __NEMITTER__
#define __NEMITTER__
#include "core/item.h"
#include "core/renderable.h"
#include "geometry/curve.h"
#include "sort/sort.h"
namespace GS {
namespace Core {
/*!
@short Particle class.
@author Emmanuel Julien (ejulien@gsworks.fr)
*/
struct Particle
{
Time time;
Vector4 position,
velocity;
float size;
float angle;
Color color;
/*!
@name Parameter scaler.
@{
*/
float opacity_scale,
size_scale;
/// @}
/// Is the particle alive.
bool IsAlive() const { return time.toSec() < 0 ? false : true; }
Particle()
{ opacity_scale = 1; }
};
/*
@short Particle model.
Models the particle attributes over its lifetime.
@author Emmanuel Julien (ejulien@gsworks.fr)
*/
struct ParticleModel : public SharedObject
{
struct RenderData
{
Render::sMaterial material;
};
String name;
String material;
Time time_to_live; ///< Time to live.
float damping; ///< Particle velocity damping.
Vector4 gravity; ///< Particle gravity.
Curve angle_curve,
size_curve;
Curve red_curve,
green_curve,
blue_curve,
opacity_curve;
AutoPtr <RenderData> render_data;
/// Setup render data.
void RenderSetup(ResourceFactories * = 0);
/*!
@short Set template color.
This function does not clear the color and opacity curves.
It only set their default value member, curves with keys will animate
as usual.
*/
void SetColor(const Color &);
/// Add color curve point.
void AddColorPoint(const Time &t, const Color &);
/*!
@name Serialization.
@{
*/
bool FromMetaTag(NML::Tag &);
NML::Tag *AsMetaTag() const;
/// @}
ParticleModel();
};
typedef SharedPtr <ParticleModel> sParticleModel;
/*!
@short Emitter class.
Note: Emitters emit particle along the Z axis.
@author Emmanuel Julien (ejulien@gsworks.fr)
*/
class Emitter : public Item, public Renderable
{
public:
struct RenderData
{
sParticleModel particle_model;
};
enum Model
{
Model_Spray = 0
};
/*!
@name Emitter model.
@{
*/
protected:
Model model;
public:
/*!
@name Renderable interface.
@{
*/
/// Compute the renderable minmax.
virtual void ComputeRenderableMinMax(MinMax &mm) { ComputeMinMax(mm); }
/// Get the renderable primitive list for this renderable.
virtual uint GetRenderablePrimitiveList(const Camera &view, const Camera &default_view, Stack <Render::Primitive *> &list, Renderable::Context context = Renderable::Context_Default, bool cull = true);
/// @}
uint pool_size; ///< Particle pool size.
float birth_rate; ///< Rate in particle/second.
float birth_speed_min,
birth_speed_max; ///< Speed in m.s.
float spray_angle;
/*!
@name Model scale.
@{
*/
float birth_rate_scale,
birth_opacity_scale,
birth_speed_scale,
birth_size_scale;
/// @}
String particle_model;
/// Model particle.
void ModelParticle(Particle &, const Item &, const Time &emitter_time);
/// Get emitter model.
Model GetModel() const { return model; }
/// Set as spray emitter.
void SetSprayModel(float angle = Units::Deg(45.f));
/// @}
AutoPtr <RenderData> render_data;
protected:
Array <Particle> particle_pool;
uint alive_count;
bool is_seen;
Time time;
Time birth_time;
Array <Sort <float, uint>::Entry> sort_array;
public:
void RenderSetup(ResourceFactories * = 0);
bool Setup();
void Update(const Time &dt);
void Free();
void ComputeMinMax(MinMax &) const;
/// Sort emitter particles against a given view matrix.
void Sort(const Matrix4 &view_matrix);
/*!
@short Get alive particle count.
@note The emitter must have been sorted beforehand.
@see Sort().
*/
uint GetParticleCount() const { return alive_count; }
/*
@short Get alive particle.
@note Particles are returned back to front.
*/
Particle *GetParticle(uint n) const { return n < particle_pool.GetCount() ? &particle_pool[sort_array[alive_count - 1 - n].o] : 0; }
/*!
@name Serialization.
@{
*/
bool FromMetaTag(NML::Tag &);
NML::Tag *AsMetaTag() const;
/// @}
Emitter();
};
} // Core
} // GS
#endif // __NEMITTER__

View File

@ -0,0 +1,20 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __NENGINECORE__
#define __NENGINECORE__
namespace GS {
namespace Core {
static const char *Version = "1.5.0";
} // Core
} // GS
#endif // __NENGINECORE__

View File

@ -0,0 +1,257 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __NGEOMETRY__
#define __NGEOMETRY__
#include "core/tangent_frame.h"
#include "geometry/bounding_box.h"
#include "color/color.h"
#include "memory/nshared_ptr.h"
#include "memory/nauto_ptr.h"
#include "memory/bit_field.h"
#include "nstring/nstring.h"
namespace GS {
namespace Core {
using namespace NML;
//------------------------------------------------------------------------------
struct GeometrySkin
{
float w[__PV_BONE_LIMIT__];
ushort bone_index[__PV_BONE_LIMIT__];
};
struct Polygon
{
ushort vtx_count;
ushort material;
uint *binding;
};
struct VertexToPolygon
{
ushort pol_count;
Array <uint> pol_index;
};
struct PolygonVertex
{
uint pol_index;
uint vtx_index;
};
struct VertexToVertex
{
ushort vtx_count;
Array <PolygonVertex> vtx;
};
typedef Polygon * pPolygon;
//------------------------------------------------------------------------------
/*!
@short Geometry class.
@author Emmanuel Julien (ejulien@gsworks.fr)
*/
class Geometry : public SharedObject
{
public:
NPLACEMENT_NEW(Geometry)
/// Item flag.
enum
{
FlagHidden = (1 << 0),
FlagNullLodProxy = (1 << 1),
FlagNullShadowProxy = (1 << 2),
// Non-serialized.
FlagNoMaterialCache = (1 << 3)
};
private:
/// Low-level vertex properties comparison.
char VertexPropertiesCompare(uint, uint, uint, uint, uint);
/*!
@name Serialization
@{
*/
void ParseVertex(const Tag *);
void ParseAsciiVertex(const Tag *);
void ParseSkin(const Tag *);
void ParsePolygon(const Tag *);
void ParseAsciiPolygon(const Tag *);
void ParsePolygonNormal(const Tag *);
void ParseVertexNormal(const Tag *);
void ParseVertexTangent(const Tag *);
void ParseRGB(const Tag *);
void ParseAsciiRGB(const Tag *);
void ParseUV(const Tag *);
void ParseAsciiUV(const Tag *);
void ParseMaterials(const Tag *);
void ParseMisc(const Tag &);
/// @}
public:
String name;
BitField flag;
String copy_lock; ///< Used to prevent publishing.
/*!
@name Proxies.
@{
*/
String lod_proxy; ///< LOD proxy geometry.
float lod_distance; ///< LOD distance.
String shadow_proxy; ///< Shadow proxy geometry.
/// @}
/// Return the number of triangles in the mesh. Note: this does not perform any conversion.
uint GetTriangleCount() const
{
uint n, c = 0;
for (n = 0; n < pol.GetCount(); ++n)
if (pol[n].vtx_count >= 3)
c += pol[n].vtx_count - 2;
return c;
}
/*!
@short Flag vertices sharing the same properties as homogeneous.
All vertices attributes are checked and compared. If they all lie
under a given threshold then the vertex is reported as homogeneous.
This function is heavily used by the geometry stripper and triangle
list builder.
@param material_index Optionally restrict attribute comparison
to one material only.
(default: -1 to include all materials in
the geometry.)
*/
void FlagHomogeneousVertex(Array <bool> &flag, const Array <uint> &polygon_index, const Array <VertexToPolygon> &, int material_index = -1) const;
/*!
@name Topology section.
@{
*/
/// Compute the geometry min-max from current vertex set (AABB).
MinMax ComputeMinMax(const Matrix4 * = 0) const;
/// Compute geometry bones bounding volumes.
bool ComputeBoneBoundingVolumes(Array <MinMax> &) const;
Array <Vector4> vtx, vtx_normal;
Array <TangentFrame> vtx_tangent;
Array <Color> rgb;
Array <Vector2> uv[__UV_PER_GEOMETRY__];
/// Return the number of UV channels used by the geometry.
uint GetUVCount() const;
Array <Polygon> pol;
Array <uint> binding;
bool AllocateVertex(uint);
bool AllocatePolygon(uint);
/// Allocate polygon binding array.
bool AllocatePolygonBinding();
/// Compute polygon binding count.
uint ComputePolygonBindingCount() const;
/// @}
/*!
@name Skinning section.
@{
*/
/// Allocate bones array (not the skin weights array).
bool AllocateBone(uint);
/// Return the number of bones referenced by the geometry.
uint GetBoneCount() const;
Array <String> bone_name;
Array <Matrix4> bone_bind_matrix;
Array <GeometrySkin> skin; ///< Skin weights.
/// @}
Array <Vector4> pol_normal;
Array <TangentFrame> pol_tangent;
bool ComputePolygonNormal(bool force = false);
bool ComputePolygonTangent(uint uv_index = 0, bool force = false);
bool ComputeVertexNormal(float msa = -1.f, bool force = false);
bool ComputeVertexNormal(Array <Vector4> &, float msa = -1.f);
bool ComputeVertexTangent(bool reverse_t = false, bool reverse_b = false, bool force = false);
/*!
@name Geometry tools.
@{
*/
/// Compute polygon start index.
void ComputePolygonIndex(Array <uint> &) const;
/// Compute vertex to polygon table.
void ComputeVertexToPolygon(Array <VertexToPolygon> &) const;
/// Compute vertex to vertex table.
void ComputeVertexToVertex(Array <VertexToVertex> &, const Array <VertexToPolygon> * = 0) const;
/// @}
void SmoothRGB(uint pass_count, float max_smooth_angle);
void FreeRGB();
void FreeUV();
/*!
@name Material section.
@{
*/
struct MaterialSlot
{
String name;
bool use_cache;
MaterialSlot() : use_cache(true) {}
};
Array <MaterialSlot> material_table;
/// Merge duplicate materials in table.
uint MergeDuplicateMaterials();
/// @}
void Free();
/*!
@name Serialization.
@{
*/
bool FromMetaTag(const Tag &);
Tag *AsMetaTag() const;
/// @}
Geometry();
virtual ~Geometry();
};
/// Compute the minmax of a vertex array.
extern bool ComputeVertexArrayMinMax(const Array <Vector4> &, MinMax &, const Matrix4 * = 0);
typedef SharedPtr <Geometry> sGeometry;
typedef Geometry * pGeometry;
} // Core
} // GS
#endif // __NGEOMETRY__

View File

@ -0,0 +1,99 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __NGEOMETRYBIH__
#define __NGEOMETRYBIH__
#include "bih/bih.h"
#include "core/shader_tree.h"
#include "core/material.h"
#include "core/geometry.h"
#include "core/geometry_tree.h"
namespace GS {
namespace Core {
struct ResourceFactory;
/// BIH ray/triangle intersection acceleration structure.
struct GeometryBIHAccel
{
char cu, cv;
Array <float> k;
float d;
};
struct GeometryBIHMaterial
{
sMaterial material;
sShaderTree shader_tree;
};
/*
@short Geometry polygon bounding interval hierarchy.
Raytracing/intersection acceleration structure theoretically
performing within 70% of the SAH/KD-Tree performances.
@author Emmanuel Julien (ejulien@gsworks.fr)
*/
class GeometryBIH : public IGeometryTree, public BIH::Tree
{
Array <GeometryBIHMaterial> material_table; ///< Material table.
Array <uint> pol_index;
Array <GeometryBIHAccel> acc; ///< Raytracing lookup tables.
/// Trace leaf content.
void TraceLeaf(BIH::Node *leaf, float tmin, float tmax, BIH::Trace &trace, void *parm = 0);
/// Build raytracing lookup tables.
bool BuildLUT();
public:
/// Return the raytracing LUT structure.
const GeometryBIHAccel *GetRaytracingAccelerationStructure() const { return acc; }
/// Fast polygon test.
bool FastPolyTest(uint ip, Vector4 &s, Vector4 &d, float l = -1.f);
void RaytraceGeometry(GeometryTrace &trace, const Vector4 &s, const Vector4 &d, float l = -1.f);
bool BuildFromGeometry(ResourceFactory &, Geometry *);
void Free();
};
/*!
@short Geometry BIH tree.
@author Emmanuel Julien (ejulien@gsworks.fr)
*/
class GeometryBIHTree : public IGeometryTree
{
GeometryBIH bih;
public:
/*!
@name Interface core functions.
@{
*/
/// Raytrace the geometry tree.
void RaytraceGeometry(GeometryTrace &trace, const Vector4 &s, const Vector4 &d, float l = -1.f) { bih.RaytraceGeometry(trace, s, d, l); }
/// Build tree from a geometry.
bool BuildFromGeometry(ResourceFactory &gf, Geometry *g) { return bih.BuildFromGeometry(gf, g); }
/// Free all internal structures.
void Free() { bih.Free(); }
/// @}
~GeometryBIHTree()
{ Free(); }
};
} // Core
} // GS
#endif // __NGEOMETRYBIH__

View File

@ -0,0 +1,126 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __NGEOMETRYKDTREE__
#define __NGEOMETRYKDTREE__
#include "core/geometry_tree.h"
#include "container/narray.h"
#include "container/nlist.h"
namespace GS {
namespace Core {
class Geometry;
/*!
@short Geometry polygon KD-tree.
@author Thomas Simonnet (thomas@movida-mail.com)
*/
class GeometryKDTree : public IGeometryTree
{
private:
Array <sMaterial> material_table;
Array <uint> pol_index;
struct KDTreeNode
{
char m_KDTREE_NODE_TYPE_SPLIT;
int m_KDTREE_NODE_ID_ROPE[6];
float m_KDTREE_NODE_AABB[6];
float m_KDTREE_NODE_VALUE_SPLIT;
int m_KDTREE_NODE_ID;
int m_KDTREE_NODE_ID_CHILD_LEFT;
int m_KDTREE_NODE_ID_CHILD_RIGHT;
bool m_KDTREE_NODE_IS_LEAF;
int m_KDTREE_NODE_COUNT_POLY;
int* m_KDTREE_NODE_ID_VTX;
int* m_KDTREE_NODE_ID_POLY;
KDTreeNode();
~KDTreeNode(){delete []m_KDTREE_NODE_ID_POLY; delete []m_KDTREE_NODE_ID_VTX;};
};
/*#define KDTREE_NODE_TYPE_SPLIT 0
#define KDTREE_NODE_ID_ROPE 1
#define KDTREE_NODE_AABB 25
#define KDTREE_NODE_VALUE_SPLIT 49
#define KDTREE_NODE_ID 53
#define KDTREE_NODE_ID_CHILD_LEFT 57
#define KDTREE_NODE_ID_CHILD_RIGHT 61
#define KDTREE_NODE_IS_LEAF 65
#define KDTREE_NODE_COUNT_POLY 66
#define KDTREE_NODE_ID_POLY 70
*/
#define KDTREE_X_AXIS 0
#define KDTREE_Y_AXIS 1
#define KDTREE_Z_AXIS 2
#define KDTREE_SIDE_LEFT 0
#define KDTREE_SIDE_RIGHT 1
#define KDTREE_SIDE_BOTTOM 2
#define KDTREE_SIDE_TOP 3
#define KDTREE_SIDE_BACK 4
#define KDTREE_SIDE_FRONT 5
int m_count_bih;
float * m_TempFloatBih;
List <int> m_ArrayCountPoly;
List <Geometry*> m_PointerGeo;
KDTreeNode* m_NodeTree;
int m_SizeTree;
int* m_RealIdPoly;
float* m_Vtx;
Vector4* m_OptimizeEdgePoly;
protected:
int planeBoxOverlap(float normal[3], float vert[3], float maxbox[3]);
int triBoxOverlap(float boxcenter[3],float boxhalfsize[3],float Verts1[3],float Verts2[3],float Verts3[3]);
int GetKDtreeSideAABB(float* _AABB, Vector4 &_EntryPoint, int &_LastEntrySide);
bool IntersectTriangle(const Vector4 &s, const Vector4 &d, float* Vtx1, float* Vtx2, float* Vtx3, Vector4* _Edge1, Vector4* _Edge2, float &l_Dist, float &u, float &v, bool& _Backface);
bool AABBIntersectRay(float* _AABB, const Vector4 &o, const Vector4 &d, float &tmin, float &tmax);
void CreateRope(int &_CurrentNode, int *_RopeArray);
void IncreaseSizeNodeKdtreeBuffer(int _IncreaseSize);
void CreateNodeKdtree(int &_CurrentNode, int *_IdPoly, int *_IdVtx, int _CountPoly, float *_Vtx, int _CountVtx, int _CurrentDepth);
public:
/*!
@name KD-Tree specific functions.
@{
*/
/// Retrieve the index of the closest KD-tree node to a given location in world space.
int InsideKdTreeNode(const Vector4 &p, bool CheckInside=false);
/// @}
/*!
@name Interface core functions.
@{
*/
/// Raytrace the geometry tree.
virtual void RaytraceGeometry(GeometryTrace &trace, const Vector4 &s, const Vector4 &d, float l = -1.f);
/// Build tree from a geometry.
virtual bool BuildFromGeometry(ResourceFactory &gf, Geometry *geo);
/// Free all internal structures.
virtual void Free();
/// @}
GeometryKDTree();
~GeometryKDTree()
{ Free(); }
};
} // Core
} // GS
#endif // __NGEOMETRYKDTREE__

View File

@ -0,0 +1,120 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __NGEOREDUCER__
#define __NGEOREDUCER__
#include "math/vector.h"
namespace GS {
namespace Core {
class Geometry;
struct nLLEDGE
{
uint a, b;
nLLEDGE *p, *n;
};
struct nEENTRY
{
nLLEDGE *edge;
nEENTRY *n;
};
typedef nEENTRY * pnEENTRY;
class nEDGELIST
{
public:
pnEENTRY *lut;
nLLEDGE *root;
uint vtx_count, nedg;
void SetVertexCount(uint);
void Add(uint, uint);
void Remove(nLLEDGE *);
void RemapEdges(uint, uint);
nLLEDGE *GetEdge(uint, uint);
nEDGELIST ();
~nEDGELIST ();
};
class nLLTRI
{
public:
uint a, b, c;
ushort m;
Vector4 normal;
nLLTRI *p, *n;
char UseVertex(uint);
void ReplaceVertex(uint, uint);
};
struct nTENTRY
{
nLLTRI *tri;
nTENTRY *n;
};
typedef nTENTRY * pnTENTRY;
class nLTRILIST
{
public:
pnTENTRY *lut;
nLLTRI *root;
Geometry *sg;
void SetGeo(Geometry *);
nLLTRI *Add(uint, uint, uint);
void ReplaceVertex(uint, uint);
void AddTriToVertex(nLLTRI *, uint);
void RemoveTriFromVertex(nLLTRI *t, uint v);
void Remove(nLLTRI *);
void ComputeNormal(nLLTRI *);
uint ntri;
nLTRILIST ();
~nLTRILIST ();
};
struct nLVERTEX
{
char active, locked;
float cost;
uint tgtcollapse;
};
class GeometryReducer
{
public:
nEDGELIST elist;
nLTRILIST tlist;
nLVERTEX *vlist;
nLVERTEX *AddVertex(uint v);
void RemoveVertex(uint v);
void ComputeVertexCost(Geometry *, uint);
float ComputeEdgeCost(Geometry *, nLLEDGE *);
Geometry *Reduce(Geometry *, float k);
char IsBorder(uint v);
};
} // Core
} // GS
#endif // __NGEOREDUCER__

View File

@ -0,0 +1,91 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __NGEOMETRYTEMPLATE__
#define __NGEOMETRYTEMPLATE__
#include "core/geometry.h"
#include "container/nlist.h"
namespace GS {
namespace Core {
/*!
@short Geometry template class.
@author Thomas Simonnet (scorpheus)
@author Emmanuel Julien (ejulien@nworks.fr)
*/
class GeometryTemplate
{
/// Polygon template.
struct Polygon
{
List <Vector4> vertex;
List <Vector4> normal;
List <Color> color;
List <Vector2> uv[__UV_PER_GEOMETRY__];
ushort material;
};
/// Polygon vertex.
struct PolygonVertex
{
uint ipoly;
uint ivertex;
};
Vector4 GetVertex(const PolygonVertex &);
Vector4 GetNormal(const PolygonVertex &);
Vector2 GetUV(uint channel, const PolygonVertex &);
Color GetColor(const Color &);
float merge_threshold;
AutoPtr <Polygon> polygon;
AutoList <Polygon *> polygons;
List <String> materials;
public:
/*!
@name Polygon declaration.
@{
*/
void Clear();
void BeginPolygon();
void PushVertex(const Vector4 &);
void PushNormal(const Vector4 &);
void PushUV(uint channel, const Vector2 &);
void PushColor(const Color &);
void EndPolygon(ushort material_index);
/*!
@}
@name Material table declaration.
@{
*/
void ClearMaterials();
void PushMaterial(const char *uri);
/// @}
/// Set the vertex merge threshold.
void SetVertexMergeThreshold(float threshold)
{ merge_threshold = threshold; }
/// Instantiate the current template description.
Geometry *Instantiate(const char *name);
GeometryTemplate();
};
} // Core
} // GS
#endif // __NGEOMETRYTEMPLATE__

View File

@ -0,0 +1,60 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __GEOMETRYTOTRIANGLELIST__
#define __GEOMETRYTOTRIANGLELIST__
#include "ntypes.h"
#include "container/nlist.h"
namespace GS {
namespace Core {
class Geometry;
struct Trilist;
/*!
@short Geometry to triangle list conversion object.
Takes and convert the original polygonal representation of a geometry into a
list of triangle list.
Each triangle list contains the same buffers as a polygonal geometry
(vertex, normal, UV, etc...) in the same organization and an index buffer.
Care is taken not to duplicate homogeneous vertices (sharing the same
properties). Triangle lists are always split by material so there is never
more than one material per list.
@author Emmanuel Julien (ejulien@gsworks.fr)
*/
namespace GeometryToTriangleList {
/*!
@short Convert a polygonal geometry to a triangle list representation.
@note You can specify the maximum of triangles per triangle list to
this function, the function guarantees that this number is
not exceeded (this is used by some renderer when there is
a limit on the index data type size).
@note The limit is expressed in number of triangles.
So to limit a triangle list to 65536 index you should limit
the number of triangles to 21845 or 65536/3!
@note You can optionally call the triangle list optimization function
by passing a non zero positive value to the optimize_cache
parameter.
@see Optimize().
*/
bool Convert(const Geometry &, AutoList <Trilist *> &, uint max_tri_per_list = 16384, uint vtx_cache_size = 16);
} // GeometryToTriangleList
} // Core
} // GS
#endif // __GEOMETRYTOTRIANGLELIST__

View File

@ -0,0 +1,100 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __NGEOTREE__
#define __NGEOTREE__
#include "core/graphic_resource_factory.h"
#include "core/geometry.h"
#include "math/vector.h"
namespace GS {
namespace Core {
struct GeometryTraceBase
{
Geometry *g;
float i_t; ///< Distance to intersection from ray's origin.
bool backface; ///< Hit is on the back face of the polygon.
int ip; ///< Polygon index.
uint it; ///< Triangle index in polygon.
uint bi; ///< Polygon binding start index.
float u, v, w; ///< Barycentric coordinates.
Material *m;
ShaderTree *st;
};
// Raytrace result.
struct GeometryTrace : public GeometryTraceBase
{
Vector4 s; ///< Ray origin.
Vector4 d; ///< Ray direction.
bool want_closest;
bool has_i; ///< Do we have an intersection.
uint node_visited; ///< Number of nodes visited.
uint tri_test; ///< Number of triangle tested.
GeometryTrace(bool closest = true)
{
want_closest = closest;
has_i = false;
node_visited = 0;
tri_test = 0;
}
};
/*!
@short Geometry abstract tree.
@author Emmanuel Julien (ejulien@gsworks.fr)
*/
class IGeometryTree
{
protected:
sGeometry geometry;
public:
Geometry *GetGeometry() const { return geometry; }
/*!
@short Specify a fixed ray origin.
This function provides the tree implementation with an optimization
opportunity by specifying a fixed ray origin.
@note Pass NULL to remove hint.
*/
virtual void SetRayOriginHint(const Vector4 *) {}
/*!
@name Interface core functions.
@{
*/
/// Raytrace the geometry tree.
virtual void RaytraceGeometry(GeometryTrace &, const Vector4 &s, const Vector4 &d, float length = -1.f) = 0;
/// Build tree from a geometry.
virtual bool BuildFromGeometry(ResourceFactory &, Geometry *) = 0;
/// Free all internal structures.
virtual void Free() = 0;
/// @}
virtual ~IGeometryTree() {}
};
} // Core
} // GS
#endif // __NGEOTREE__

View File

@ -0,0 +1,57 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __NCORERESOURCEFACTORY__
#define __NCORERESOURCEFACTORY__
#include "ntypes.h"
#include "core/resource_factory_event_interface.h"
namespace GS {
class Picture;
typedef SharedPtr <Picture> sPicture;
namespace Core {
class Geometry;
class ShaderTree;
struct ParticleModel;
struct Material;
struct Shader;
/*
@short Core resource factory.
@author Emmanuel Julien (ejulien@gsworks.fr)
*/
struct ResourceFactory
{
sIResourceFactoryEvent event_handler;
virtual Picture *LoadPicture(const char *) = 0;
virtual Geometry *LoadGeometry(const char *) = 0;
virtual Material *LoadMaterial(const char *) = 0;
virtual Shader *LoadShader(const char *) = 0;
virtual ParticleModel *LoadParticleModel(const char *) = 0;
virtual uint GetCachedResourceCount() { return 0; }
virtual uint PurgeCache() { return 0; }
ResourceFactory() : event_handler(new IResourceFactoryEvent) {}
virtual ~ResourceFactory() {}
};
typedef SharedPtr <Geometry> sGeometry;
typedef SharedPtr <Material> sMaterial;
typedef SharedPtr <Shader> sShader;
typedef SharedPtr <ParticleModel> sParticleModel;
} // Core
} // GS
#endif // __NCORERESOURCEFACTORY__

View File

@ -0,0 +1,123 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __NISOSURFACE__
#define __NISOSURFACE__
#include "math/vector.h"
#include "thread/mutex.h"
namespace GS {
namespace Core {
class Geometry;
/*!
@short Isosurface.
@author Thomas Simonnet (scorpheus@hotmail.com)
*/
class Isosurface
{
private:
static const int EdgeArray[256];
static const int TriTable[256][16];
Vector4 m_Pos;
// grid definition
Vector4 m_NbGridCase;
float *m_Grid;
Vector4 m_GridSize;
float m_IsoValue;
// to know on which point of the grid we have to create a triangle
Vector4 * m_TabIndexValid;
int m_NbIndexValid;
// to precalculate
Vector4 m_CaseSizeDivNbCase;
struct STriangle
{
Vector4 m_Vertex[3]; // the 3 vertex of the triangle
int m_Num[3]; // number of the side who have each vertex
};
struct TVertex
{
float x, y, z; // Position
float nx, ny, nz; // Normal
float u, v; // UV coordinate
unsigned long Color; // Color
TVertex(){x=y=z=nx=ny=u=0; nz=v=1; Color =0xFF19E395;};
};
inline void CalcNormalX(float &_x, float &_y, float &_z, Vector4 &_Normal);
inline void CalcNormalY(float &_x, float &_y, float &_z, Vector4 &_Normal);
inline void CalcNormalZ(float &_x, float &_y, float &_z, Vector4 &_Normal);
// function permit to linear interpolate between vector
void interpolateVect(Vector4 &_Vect1, Vector4 &_Vect2, float &_Val1, float &_Val2, Vector4&_Vect);
// function permit to linear interpolate between val
float interpolateVal(float &_Val1, float &_Val2, float _Val_cible1, float _Val_cible2);
// Set the value of the vertex
void EvalPos(float &_x, float &_y, float &_z, Vector4 &_CasePosition);
// return the good float with the 3d parameter in the grid
int GridIndex(float &_x, float &_y, float &_z)const;
/// calcul the polygon for one case, and return the number of triangle for the polygon
int CalculPolygon(float &_x, float &_y, float &_z, STriangle* _TriangleList);
// draw the triangle in the cellule x,y, z
void RenderCell(uint &vtx_count, float &_x, float &_y, float &_z);
// compute the metaball array to fill the grid with ball
void ComputeMetaball(int nb_metaball, Vector4* pos_metaball, float* value_metaball);
Threading::Mutex m_Mutex;
public:
//max vertex to build the mesh
static uint m_MaxNbVertex;
// temp for build the mesh
static int m_MaxIdx;
int m_CountIdxBuffer;
static int* m_TempIdxBuffer ; // index buffer containing the geometry
// temp for build the mesh
static TVertex* m_TempVertexBuffer ; // Vertex buffer containing the geometry
/// Initialize the iso-surface field
bool Init(const Vector4 &_pos, const Vector4 &size, const Vector4 &step);
/// Get the iso-surface field size
void GetFieldSize(int &x, int &y, int &z);
/// Get the iso-surface field
void GetField(float *_Grid);
/// Triangularize the iso-surface
void Triangularize(Geometry* geometry, int nb_metaball, Vector4* pos_metaball, float* value_metaball);
Isosurface();
virtual ~Isosurface();
};
} // Core
} // GS
#endif // __NISOSURFACE__

177
include/engine/core/item.h Normal file
View File

@ -0,0 +1,177 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __NITEM__
#define __NITEM__
#include "math/matrix3.h"
#include "math/matrix4.h"
#include "math/quaternion.h"
#include "data/registry.h"
#include "memory/bit_field.h"
namespace GS {
class MinMax;
class Frustum;
namespace Core {
struct ResourceFactories;
class Item;
typedef List <Item *> ItemList;
/*!
@short Common properties to light/object and camera.
This class describe a location and orientation in space.
The position is described as a vector.
@see nVector.
Items can be parented to form a hierarchy where each child inherits its
parent transformation.
@see SetParent().
@author Emmanuel Julien (ejulien@gsworks.fr)
*/
class Item
{
public:
#define ItemFlagNone 0
#define ItemFlagHasTarget (1 << 0)
#define ItemFlagInvisible (1 << 1)
#define ItemFlagInheritPositionOnly (1 << 2)
#define ItemFlagLocalMatrixDirty (1 << 3)
#define ItemFlagWorldMatrixDirty (1 << 4)
#define ItemFlagInverseWorldMatrixDirty (1 << 5)
#define ItemFlagRotationMatrixDirty (1 << 6)
#define ItemFlagBoneHint (1 << 16)
private:
Math::rOrder rorder; ///< Euler rotation order.
Vector4 position, ///< Position.
rotation, ///< Orientation as 3 Euler angles.
scale; ///< Scale.
Matrix3 rotation_matrix;
protected:
Item *parent; ///< Parent item. The item will inherit all of its parent motion.
ItemList children;
Matrix4 local_matrix, ///< Local matrix.
prv_matrix, ///< Previous world matrix.
matrix, ///< World matrix.
imatrix; ///< Inverse world matrix.
Matrix4 pivot_matrix; ///< Offset matrix.
/// Compute world local matrix.
void ComputeLocalMatrix();
/// Compute world hierarchy matrix.
virtual void ComputeMatrix();
/// Compute world inverse matrix.
void ComputeInverseMatrix();
public:
NPLACEMENT_NEW(Item3d)
Registry registry;
virtual void SetParent(Item * = 0);
const ItemList &GetChildren() const { return children; }
Item *GetParent() const { return parent; }
void MarkTransformationDirty(bool children_only = false);
void MarkWorldTransformationDirty();
const Vector4 &GetPosition() const;
void SetPosition(const Vector4 &);
void SetRotation(const Vector4 &);
void SetRotation(const Quaternion &);
void SetRotation(const Matrix3 &);
const Vector4 &GetRotation() const;
void SetScale(const Vector4 &);
const Vector4 &GetScale() const;
void SetPivot(const Matrix4 &);
const Matrix4 &GetPivot() const;
Matrix4 GetMatrixNoPivot();
void SetMatrix(const Matrix4 &);
const Matrix4 &GetPreviousMatrix() const;
void SetPreviousMatrix(const Matrix4 &);
const Matrix4 &GetLocalMatrix();
const Matrix4 &GetMatrix();
const Matrix4 &GetMatrix() const { return matrix; }
const Matrix4 &GetInverseMatrix();
const Matrix4 &GetInverseMatrix() const { return imatrix; }
const Matrix3 &GetRotationMatrix();
const Matrix3 &GetRotationMatrix() const { return rotation_matrix; }
BitField item_flags;
Vector4 target; ///< Target position.
/// Is this item linked to a given item?
bool IsLinkedTo(Item *);
/// Set item position in world space (taking account of parent transformations).
void OffsetWorldPosition(const Vector4 &);
/// Transfer a 4x4 matrix to item position/scale and rotation components.
void SnapshotTransformation(const Matrix4 &, bool parent_space = false, bool only_matrix = false);
/*!
@short Set item target location.
@note When a target location exists the item align its local Z
axis (0,0,1} so that it always point towards the target
location.
*/
void SetTarget(const Vector4 * = 0);
void SetTarget(const Vector4 &v) { SetTarget(&v); }
Vector4 GetTarget() { return target; }
float opacity; ///< Item opacity.
void SetRotationOrder(Math::rOrder);
Math::rOrder GetRotationOrder() const { return rorder; }
/// Compute the item axis-aligned bounding box.
virtual void ComputeLocalMinMax(MinMax &) const;
void *mitem; ///< Managed item.
/// Setup item render data.
virtual void RenderSetup(ResourceFactories * = 0) = 0;
bool FromMetaTag(NML::Tag &);
NML::Tag *AsMetaTag() const;
Item();
virtual ~Item();
};
typedef Item * pItem;
} // Core
} // GS
#endif // __NITEM__

191
include/engine/core/light.h Normal file
View File

@ -0,0 +1,191 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __NLIGHT__
#define __NLIGHT__
#include "core/item.h"
#include "core/render_data.h"
#include "color/color.h"
#include "geometry/frustum.h"
#include "reflection/nenum_string.h"
#include "memory/nauto_ptr.h"
namespace GS {
namespace Core {
/*!
@short Light.
@author Emmanuel Julien (ejulien@gsworks.fr)
*/
class Light : public Item
{
public:
///
struct RenderData
{
Render::sTexture projection_texture;
struct ShadowRenderData
{
virtual ~ShadowRenderData() {}
};
/// Shadow data.
struct ShadowData
{
AutoPtr <ShadowRenderData> render_data;
float slice_distance;
Vector4 crop_region;
Matrix4 imatrix, pmatrix;
};
Array <ShadowData> shadow_data;
};
static Reflection::Property serializable[];
/// Light model.
enum Model
{
Model_None = 0,
Model_Point,
Model_Linear,
Model_Spot,
Model_Last
};
static Reflection::Enum::Dict model_dict[];
/// Light falloff.
enum Falloff
{
Falloff_Linear = 0, ///< Linear.
Falloff_InvDist, ///< Inverse distance.
Falloff_InvDist2 ///< Inverse squared distance.
};
static Reflection::Enum::Dict falloff_dict[];
/// Light shadow method.
enum Shadow
{
Shadow_None = 0,
Shadow_ProjectionMap,
Shadow_Map
};
static Reflection::Enum::Dict shadow_dict[];
Model model;
Frustum frustum;
/*!
@name Shadow section.
@{
*/
Shadow shadow;
bool shadow_cast_all;
float shadow_range,
shadow_bias,
shadow_distribution,
z_near;
/// @}
/*!
@name Volumetric section.
@{
*/
bool volumetric;
float volumetric_sample_step,
volumetric_range,
volumetric_thickness;
/// @}
/*!
@name Light section.
@{
*/
Falloff falloff;
float range,
volume_range, ///< Volume range (mainly used as an optimization hint).
clip_distance;
Color diffuse_color,
specular_color,
shadow_color;
float diffuse_intensity,
specular_intensity,
cone_angle,
edge_angle;
String projection_texture; ///< Projection texture.
/// @}
/// Set the spot cone and edge angles.
void SetSpotAngle(float cone = Units::Deg(40), float edge = Units::Deg(10))
{
cone_angle = cone;
edge_angle = edge;
}
/// Sample lighting contributed by this light to a location in space.
bool SampleColor(const Vector4 &p, const Vector4 &n, Color &diff, Color &spec, Vector4 *view = 0, float gloss = 0.8);
/*!
@short Sample energy this light contribute to a location in space.
This function can sample both the diffuse and specular lightning
contribution from a given light to a given position in space.
You can specify whether the specular should be computed using
accurate Phong model or using the halfway vector (faster/less
accurate).
You can ask that specular reflection be evaluated using the
Cook-Torrance model by calling the function with the parameter
'cooktorrance' set to true. The default specular reflection uses
the Phong model.
@note The default specular model used is the halfway vector one.
@note Sampling the specular contribution requires a view vector
and a glossiness value.
@return True if the light contribute to the surface.
*/
bool SampleEnergy(const Vector4 &p,const Vector4 &n, float *diff = 0, float *spec = 0, Vector4 *view = 0, float gloss = 0.8, bool halfway = false, bool cooktorrance = false);
virtual void ComputeMatrix();
void ComputeProjectionMatrix(Matrix4 &m_) const;
void ComputeFrustrum(Frustum &f, float z_near = -1, float z_far = -1) const;
float GetNearClippingPlane() const { return z_near; }
float GetFarClippingPlane() const { return volume_range; }
void SetNearClippingPlane(float z) { z_near = z; }
void SetFarClippingPlane(float z) { volume_range = z; }
void RenderSetup(ResourceFactories * = 0);
AutoPtr <RenderData> render_data;
void SetDefaults();
bool FromMetaTag(NML::Tag &);
NML::Tag *AsMetaTag();
Light();
};
typedef Light * pLight;
} // Core
} // GS
#endif // __NLIGHT__

View File

@ -0,0 +1,184 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __NMATERIAL__
#define __NMATERIAL__
#include "core/material_channel.h"
#include "core/physic_material.h"
#include "math/matrix4.h"
#include "color/color.h"
#include "memory/nshared_ptr.h"
#include "memory/nauto_ptr.h"
#include "nstring/nstring.h"
namespace GS {
namespace Core {
/// Basic material definition.
struct BasicMaterial {
Color diffuse; ///< Diffuse color.
Color specular; ///< Specular color.
Color self; ///< Self color.
Color ambient; ///< Ambient color.
float glossiness; ///< Glossiness.
float opacity; ///< Opacity (eg. 1 - transparency or alpha).
float reflection; ///< Reflection [0;1]
float irefraction; ///< Index of refraction.
float athreshold; ///< Alpha threshold [0;1].
float depth_bias; ///< Depth bias.
uint renderword; ///< Render word.
uint blendop; ///< Blending operator.
};
/*!
@short Material.
A material describe the rendering properties of a surface.
It usually embeds several textures which can have a very different use
depending on whether they are used by a fixed function hardware renderer or
a programmable renderer or even the raytracer.
@note A material can have up to nTextureStageLimit texture levels.
@author Emmanuel Julien (ejulien@gsworks.fr)
*/
struct Material : public BasicMaterial, public PhysicMaterial, public SharedObject {
NPLACEMENT_NEW(Material)
/*!
@short Maximum texture stage count.
@note 1 is the lowest acceptable value as C++ does not allow 0 sized
array declaration. (Default: 6)
*/
static const int max_texture_stage = 6;
/// Material render word (bit mask).
enum RenderWord {
Render_None = 0,
Render_Unlit = (1 << 0),
Render_Smooth = (1 << 1),
Render_NormalTangent = (1 << 2),
Render_NoFog = (1 << 3),
Render_DoubleSided = (1 << 4),
Render_Wire = (1 << 5),
Render_VertexColor = (1 << 6),
Render_ParralaxDisp = (1 << 7),
Render_Toon = (1 << 8),
Render_NoZWrite = (1 << 9),
Render_NoZTest = (1 << 10),
Render_AlphaTest = (1 << 11),
Render_AlphaSoftZ = (1 << 12), ///< Soft particle.
Render_AlphaInShadow = (1 << 13), ///< Render alpha/opacity in shadow maps.
Render_UseFramebuffer = (1 << 14),
Render_Skinned = (1 << 15)
};
/// Blending operator.
enum BlendOperator {
Blend_None = 0,
Blend_Alpha,
Blend_Add
};
/// Filtering type (exclusive).
enum FilterType {
Filter_None = 0,
Filter_Point = 1,
Filter_Linear = 2,
Filter_Default = Filter_Point
};
enum UVMode {
UV_UV = 0, ///< Geometry standard UV buffer.
UV_LSN, ///< Geometry local space transformed normal component.
UV_FrontMap, ///< Front mapping.
UV_SphericalEnvironment ///< Spherical Environment mapping.
};
enum Operator {
Operator_Default = 0, ///< Default operator for a given renderer (usually a function of channel member).
Operator_Multiply, ///< Multiply stage.
Operator_Add ///< Add stage.
};
/*!
@short Texture stage.
A texture stage describes a texture layer in a material.
It links a texture object together with the material layer specific
attributes such as UV wrapping, texture sampling method (point, linear,
etc...). A texture stage is also associated with the channel it modify
(diffuse, color, specular, etc... see StageChannel). It is the
renderer's responsibility to render a given material as accurately as
possible and to provide acceptable fall back in the case a material is
too complex to be rendered.
@author Emmanuel Julien (ejulien@gsworks.fr)
*/
struct TextureStage {
MaterialChannel channel; ///< Texture channel.
String t; ///< Shared texture object.
uchar uv_index; ///< UV map index in geometry UV list.
UVMode uv_mode; ///< UV mode.
Matrix4 uv_matrix; ///< UV matrix.
Operator op; ///< Stage combine operator.
/// Reset the texture stage.
void Reset();
TextureStage() { Reset(); }
};
String name;
String shader;
uint texstage_count;
Array<TextureStage> texstage;
/// Return the texture stage for a given channel (if any).
TextureStage *GetChannelStage(MaterialChannel) const;
/*!
@short Create a new texture stage.
@note If a stage is already assigned to the material channel
it will be returned and no new stage will be allocated.
*/
TextureStage *NewStage(MaterialChannel, const char *uri = 0, UVMode = UV_UV, uchar uv_index = 0);
void Reset();
/*!
@name Serialization.
@{
*/
bool FromMetaTag(NML::Tag &);
NML::Tag *AsMetaTag() const;
/// @}
Material();
};
typedef SharedPtr<Material> sMaterial;
typedef List<Material *> MaterialList;
} // Core
} // GS
#endif // __NMATERIAL__

View File

@ -0,0 +1,38 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __NChannel__
#define __NChannel__
namespace GS {
namespace Core {
enum MaterialChannel
{
Channel_None = 0, ///< No channel.
Channel_Diffuse, ///< Diffuse channel.
Channel_Decal, ///< Decal channel.
Channel_Opacity, ///< Opacity channel.
Channel_Specular, ///< Specular channel.
Channel_Glossiness, ///< Glossiness channel.
Channel_Normal, ///< Normal channel (tangent/world).
Channel_Reflection, ///< Reflection channel.
Channel_SelfIllum, ///< Self-illumination channel.
Channel_Light, ///< Lighting channel.
Channel_BlendRGB, ///< Red blend channel.
Channel_Last
};
const char *MaterialChannelName(MaterialChannel);
MaterialChannel MaterialChannelFromName(const char *);
} // Core
} // GS
#endif // __NChannel__

View File

@ -0,0 +1,31 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __NMATERIALTOSHADERTREE__
#define __NMATERIALTOSHADERTREE__
#include "core/material.h"
namespace GS {
namespace Core {
class ShaderTree;
struct ShaderBlock;
namespace MaterialToShaderTree {
/// Convert a material texture stage to a shader tree block.
ShaderBlock *MaterialTextureStageToShaderBlock(const Material &m, const Material::TextureStage *ts, ShaderBlock *nb = 0);
/// Convert a material fixed-function definition to a shader tree.
bool Convert(const Material &, ShaderTree &);
} // MaterialToShaderTree
} // Core
} // GS
#endif // __NMATERIALTOSHADERTREE__

View File

@ -0,0 +1,93 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __NMIXER__
#define __NMIXER__
#include "core/mixer_data.h"
#include "memory/nauto_ptr.h"
namespace GS {
namespace Audio {
/*!
@short Mixer interface.
@author Emmanuel Julien (ejulien@gsworks.fr)
*/
struct IMixer
{
enum State
{
Invalid = 0,
Stopped,
Playing,
Paused
};
enum Loop
{
None = 0,
Repeat
};
/*!
@name Interface.
The API any concrete mixer must implement.
@{
*/
virtual bool Open() = 0;
virtual void Close() = 0;
virtual void SuspendWorkerThread() = 0;
virtual void ResumeWorkerThread() = 0;
virtual void SetMasterVolume(float = 1.0) = 0;
virtual float GetMasterVolume() = 0;
/// Play a sound, does not wait for the worker thread return code.
virtual bool StartFast(int, FutureData *) = 0;
/// Play a sound, returns the channel on which the stream was started.
virtual int Start(int, FutureData *) = 0;
/// Start a stream, does not wait for the worker thread return code.
virtual bool StreamFast(int, const char *) = 0;
/// Start a stream, returns the channel on which the stream was started.
virtual int Stream(int, const char *) = 0;
virtual void Stop(int) = 0;
virtual void Pause(int) = 0;
virtual void Resume(int) = 0;
virtual int LockChannel() = 0;
virtual void UnlockChannel(int) = 0;
virtual void UnlockAllChannels() = 0;
virtual float GetChannelPitch(int) = 0;
virtual float GetChannelVolume(int) = 0;
virtual float GetChannelPanning(int) = 0;
virtual Loop GetChannelLoopMode(int) = 0;
virtual int GetChannelLoopPosition(int) = 0;
virtual void SetChannelPitch(int, float) = 0;
virtual void SetChannelVolume(int, float) = 0;
virtual void SetChannelPanning(int, float) = 0;
virtual void SetChannelLoopMode(int, Loop = None) = 0;
virtual void SetChannelLoopPosition(int, int ms) = 0;
virtual State GetState(int) = 0;
virtual FutureData *LoadSound(const char *) = 0;
virtual void UnloadSound(FutureData *) = 0;
/// @}
virtual ~IMixer() {}
};
} // Audio
} // GS
#endif // __NMIXER__

View File

@ -0,0 +1,36 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __NAUDIODATA__
#define __NAUDIODATA__
#include "async/future.h"
#include "alloc/ialloc.h"
#include "time/ntime.h"
namespace GS {
namespace Audio {
//
struct Data : public SharedObject
{
NPLACEMENT_NEW(Mixer)
Time duration;
virtual ~Data() {}
};
typedef SharedPtr <Data> sData;
typedef ASync::Future <sData> FutureData;
} // Audio
} // GS
#endif // __NAUDIODATA__

View File

@ -0,0 +1,42 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __NAUDIORESOURCEFACTORY__
#define __NAUDIORESOURCEFACTORY__
#include "core/resource_factory_event_interface.h"
#include "memory/nauto_ptr.h"
namespace GS {
namespace Audio {
struct IMixer;
struct Sound;
/*
@short Mixer resource factory.
@author Emmanuel Julien (ejulien@gsworks.fr)
*/
struct ResourceFactory
{
AutoPtr <IResourceFactoryEvent> event_handler;
IMixer &mixer;
virtual Sound *LoadSound(const char *) = 0;
ResourceFactory(IMixer &m) : event_handler(new IResourceFactoryEvent), mixer(m) {}
virtual ~ResourceFactory() {}
};
typedef SharedPtr <Sound> sSound;
} // Audio
} // GS
#endif // __NAUDIORESOURCEFACTORY__

View File

@ -0,0 +1,248 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __NMIXER_THREAD_CONTROLLER__
#define __NMIXER_THREAD_CONTROLLER__
#include "core/mixer.h"
#include "audio/sample_interface.h"
#include "nstring/nstring.h"
#include "thread/mutex.h"
namespace GS {
namespace Audio {
//
struct MixerVariant : public SharedObject
{
union
{
int i_value;
float f_value;
};
AutoPtr <FutureData> future_data;
MixerVariant() : i_value(0) {}
MixerVariant(int v) : i_value(v) {}
MixerVariant(float v) : f_value(v) {}
MixerVariant(FutureData *f) : future_data(f) {}
};
typedef SharedPtr <MixerVariant> sMixerVariant;
//
struct MixerCommand
{
enum Code
{ Nop = 0, LoadSound, UnloadSound, Start, Stream, GetState, Pause, Stop, Resume, Lock, Unlock, Close,
SetMaster, SetVolume, SetPitch, SetPanning, SetLoopMode, SetLoopPosition,
GetMaster, GetVolume, GetPitch, GetPanning, GetLoopMode, GetLoopPosition };
Code code;
int channel;
String uri;
union
{
bool b_value;
float f_value;
int i_value;
};
sData data;
ASync::Future <MixerVariant *> *result;
MixerCommand() {}
MixerCommand(Code c) : code(c) {}
MixerCommand(Code c, float v) : code(c), f_value(v) {}
MixerCommand(Code c, const char *name) : code(c), uri(name) {}
MixerCommand(Code c, Data *_data) : code(c), data(_data) {}
MixerCommand(Code c, int n) : code(c), channel(n) {}
MixerCommand(Code c, int n, Data *d) : code(c), channel(n), data(d) {}
MixerCommand(Code c, int n, bool v) : code(c), channel(n), b_value(v) {}
MixerCommand(Code c, int n, float v) : code(c), channel(n), f_value(v) {}
MixerCommand(Code c, int n, int v) : code(c), channel(n), i_value(v) {}
MixerCommand(Code c, int n, const char *name) : code(c), channel(n), uri(name) {}
};
/*!
@short Threaded mixer controller.
@author Emmanuel Julien (ejulien@gsworks.fr)
*/
template <class _Thread> class ThreadedMixer : public IMixer
{
AutoPtr <_Thread> thread;
bool PutCommand(MixerCommand *cmd, MixerVariant **result = 0)
{
if (thread.IsNull() || !thread->device)
return false;
ASync::Future <MixerVariant *> future_result;
forever
{
Threading::MutexLock lock(&thread->cmdbuffer_mutex);
if (thread->cmdbuffer.GetFree() > 0)
if (MixerCommand **put = &thread->cmdbuffer.CurrentPut())
{
*put = cmd;
cmd->result = result ? &future_result : NULL; // Future is to be Set() by the worker thread.
thread->cmdbuffer.Produce();
thread->cmdbuffer_event.Trigger();
break;
}
}
if (result)
*result = future_result.Get();
return true;
}
MixerVariant *PutCommandAndWaitResult(MixerCommand *cmd)
{
MixerVariant *result;
return PutCommand(cmd, &result) ? result : 0;
}
public:
virtual bool Open()
{
if (thread.IsValid())
return true;
thread = new _Thread;
return thread->Start();
}
virtual void Close()
{
PutCommand(new MixerCommand(MixerCommand::Close));
if (thread.IsValid())
thread->Join();
thread = 0;
}
virtual void SuspendWorkerThread()
{ thread->SuspendMixer(); }
virtual void ResumeWorkerThread()
{ thread->ResumeMixer(); }
virtual void SetMasterVolume(float volume = 1.0)
{ PutCommand(new MixerCommand(MixerCommand::SetMaster, volume)); }
virtual float GetMasterVolume()
{
AutoPtr <MixerVariant> v(PutCommandAndWaitResult(new MixerCommand(MixerCommand::GetMaster)));
return v.IsValid() ? v->f_value : 1;
}
virtual bool StartFast(int channel, FutureData *data)
{ return data ? PutCommand(new MixerCommand(MixerCommand::Start, channel, data->Get())) : false; }
virtual int Start(int channel, FutureData *data)
{
AutoPtr <MixerVariant> v(data ? PutCommandAndWaitResult(new MixerCommand(MixerCommand::Start, channel, data->Get())) : 0);
return v.IsValid() ? v->i_value : -1;
}
virtual bool StreamFast(int channel, const char *uri)
{ return PutCommand(new MixerCommand(MixerCommand::Stream, channel, uri)); }
virtual int Stream(int channel, const char *uri)
{
AutoPtr <MixerVariant> v(PutCommandAndWaitResult(new MixerCommand(MixerCommand::Stream, channel, uri)));
return v.IsValid() ? v->i_value : -1;
}
virtual void Stop(int channel)
{ PutCommand(new MixerCommand(MixerCommand::Stop, channel)); }
virtual void Pause(int channel)
{ PutCommand(new MixerCommand(MixerCommand::Pause, channel)); }
virtual void Resume(int channel)
{ PutCommand(new MixerCommand(MixerCommand::Resume, channel)); }
virtual int LockChannel()
{
AutoPtr <MixerVariant> v(PutCommandAndWaitResult(new MixerCommand(MixerCommand::Lock)));
return v.IsValid() ? v->i_value : -1;
}
virtual void UnlockChannel(int channel)
{ PutCommand(new MixerCommand(MixerCommand::Unlock, channel)); }
virtual void UnlockAllChannels()
{
for (int n = 0; n < 64; ++n)
PutCommand(new MixerCommand(MixerCommand::Unlock, n));
}
virtual float GetChannelPitch(int channel)
{
AutoPtr <MixerVariant> v(PutCommandAndWaitResult(new MixerCommand(MixerCommand::GetPitch, channel)));
return v.IsValid() ? v->f_value : 1;
}
virtual float GetChannelVolume(int channel)
{
AutoPtr <MixerVariant> v(PutCommandAndWaitResult(new MixerCommand(MixerCommand::GetVolume, channel)));
return v.IsValid() ? v->f_value : 1;
}
virtual float GetChannelPanning(int channel)
{ return -1; }
virtual Loop GetChannelLoopMode(int channel)
{
AutoPtr <MixerVariant> v(PutCommandAndWaitResult(new MixerCommand(MixerCommand::GetLoopMode, channel)));
return v.IsValid() ? (v->i_value == AL_TRUE ? Repeat : None) : None;
}
virtual int GetChannelLoopPosition(int channel)
{ return 0; }
virtual void SetChannelPitch(int channel, float pitch)
{ PutCommand(new MixerCommand(MixerCommand::SetPitch, channel, pitch)); }
virtual void SetChannelVolume(int channel, float volume)
{ PutCommand(new MixerCommand(MixerCommand::SetVolume, channel, volume)); }
virtual void SetChannelPanning(int channel, float panning)
{ PutCommand(new MixerCommand(MixerCommand::SetPanning, channel, panning)); }
virtual void SetChannelLoopMode(int channel, Loop loop = None)
{ PutCommand(new MixerCommand(MixerCommand::SetLoopMode, channel, loop == IMixer::Repeat ? AL_TRUE : AL_FALSE)); }
virtual void SetChannelLoopPosition(int, int ms)
{}
virtual State GetState(int channel)
{
AutoPtr <MixerVariant> v(PutCommandAndWaitResult(new MixerCommand(MixerCommand::GetState, channel)));
if (v.IsValid())
switch (v->i_value)
{
case AL_INITIAL:
case AL_STOPPED: return Stopped;
case AL_PAUSED: return Paused;
case AL_PLAYING: return Playing;
}
return Invalid;
}
virtual FutureData *LoadSound(const char *uri)
{
AutoPtr <MixerVariant> v(uri ? PutCommandAndWaitResult(new MixerCommand(MixerCommand::LoadSound, uri)) : 0);
return v.IsValid() ? v->future_data.Detach() : 0;
}
virtual void UnloadSound(FutureData *data)
{
AutoPtr <MixerVariant> v(data ? PutCommandAndWaitResult(new MixerCommand(MixerCommand::UnloadSound, data->Get())) : 0);
}
~ThreadedMixer()
{ Close(); }
};
} // Audio
} // GS
#endif // __NMIXER_THREAD_CONTROLLER__

View File

@ -0,0 +1,68 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
------------------------------------------------------------------------------*/
#ifndef __NNULLMIXER__
#define __NNULLMIXER__
#include "core/mixer.h"
namespace GS {
namespace Audio {
/*!
@short Null mixer.
@author Emmanuel Julien (ejulien@gsworks.fr)
*/
struct NullMixer : public IMixer
{
bool Open() { return true; }
void Close() {}
void SuspendWorkerThread() {}
void ResumeWorkerThread() {}
void SetMasterVolume(float = 1.0) {}
float GetMasterVolume() { return 1; }
bool StartFast(int, FutureData *) { return false; }
int Start(int, FutureData *) { return 0; }
bool StreamFast(int, const char *) { return false; }
int Stream(int, const char *) { return 0; }
void Stop(int) {}
void Pause(int) {}
void Resume(int) {}
int LockChannel() { return 0; }
void UnlockChannel(int) {}
void UnlockAllChannels() {}
float GetChannelPitch(int) { return 1; }
float GetChannelVolume(int) { return 1; }
float GetChannelPanning(int) { return 0; }
Loop GetChannelLoopMode(int) { return None; }
int GetChannelLoopPosition(int) { return 0; }
void SetChannelPitch(int, float) {}
void SetChannelVolume(int, float) {}
void SetChannelPanning(int, float) {}
void SetChannelLoopMode(int, Loop = None) {}
void SetChannelLoopPosition(int, int ms) {}
State GetState(int) { return Invalid; }
FutureData *LoadSound(const char *) { return 0; }
void UnloadSound(FutureData *) {}
~NullMixer() {}
};
} // Audio
} // GS
#endif // __NNULLMIXER__

View File

@ -0,0 +1,119 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __NNULLRENDERER__
#define __NNULLRENDERER__
#include "core/renderer.h"
namespace GS {
namespace Render {
/*!
@short Null renderer class.
@author Emmanuel Julien (ejulien@gsworks.fr)
*/
struct NullRenderer : public Renderer
{
/// Returns the renderer's name as a C string.
const char *GetName() const { return "Null Renderer."; }
/// Returns a C string describing the renderer.
const char *GetDescription() const { return "A null renderer that render nothing."; }
/// Returns a C string containing the renderer version number.
const char *GetVersion() const { return "0.0"; }
virtual Geometry *NewGeometry(const char *name = 0) { return 0; }
virtual Material *NewMaterial(const char *name = 0) { return 0; }
virtual Texture *NewTexture(const char *name = 0) { return 0; }
virtual Shader *NewShader(const char *name = 0) { return 0; }
bool BeginDrawList() { return true; }
void EndDrawList() {}
/// Open video.
bool Open(uint width, uint height, char nUnused(bpp) = 32, VideoMode = VideoWindowed, const void * nUnused(sys_handle) = 0)
{
dimensions.Set(width, height);
return true;
}
/// Free all renderer resources.
void Free() {}
/// Close video.
void Close() {}
/// Explicitly resize video output.
bool ResizeVideo(uint width, uint height)
{
dimensions.Set(width, height);
return true;
}
/// Switch to/from fullscreen.
void SetFullscreen(bool = true) {}
/// Refresh display output.
void Refresh() {}
/// Render the display queue.
void RenderList() {}
/// Request that the frame be displayed to output.
void ShowFrame() {}
/// Return a pointer to the current subsystem window output.
void *GetCurrentSystemWindowHandle() const { return 0; }
/// Setup an extra window to use as renderer output.
Window *NewOutputWindow(const void *) { return 0; }
/// Set the output window. Pass NULL to setup the primary window (ie. the renderer initial window).
void SetOutputWindow(Window * = 0) {}
/// Free a rendering window.
void FreeOutputWindow(Window *) {}
/// Clear the render target
void Clear(float, float, float, float = 1.f, float = 1.f, ClearFunction = ClearAll) {}
/// Grab the frame buffer to a texture.
void GrabDisplay(Texture *) {}
/// Grab the frame buffer to a picture.
void GrabDisplay(Picture &) {}
/// Set a texture as render target.
void SetRenderTarget(Texture *) {}
/// Display a 3d line.
void DrawLine(uint nUnused(count), const Vector4 *, const Color * = 0, Core::Material::BlendOperator = Core::Material::Blend_None, Core::Material::RenderWord = Core::Material::Render_None, Shader * = 0) {}
/// Draw a triangle to frame buffer.
void DrawTriangle(uint nUnused(count), const Vector4 *, const ushort *idx = 0, const Color * = 0, const Vector2 * = 0, const Texture * = 0, Core::Material::BlendOperator = Core::Material::Blend_None, Core::Material::RenderWord = Core::Material::Render_None, Shader * = 0) {}
/// Draw sprite.
void DrawSprite(uint nUnused(count), const Vector4 *, const Color * = 0, const float *size = 0, const Texture * = 0, float nUnused(global_size) = 1.f, Core::Material::BlendOperator = Core::Material::Blend_None, Core::Material::RenderWord = Core::Material::Render_None, Shader * = 0) {}
/// Output string to screen.
void Write(const RasterFont &, const char *, float &nUnused(x), float &nUnused(y), const WriterConfig &, float nUnused(scale) = 1, const Color * = 0, WriterAlignment = AlignLeft, bool mirrored=false) {}
/// Set the view matrix.
void SetViewMatrix(const Matrix4 &, const Matrix4 * = 0) {}
/// Set the projection matrix.
void SetProjectionMatrix(const Matrix4 &) {}
/// Set the world matrix.
void SetWorldMatrix(const Matrix4 &, const Matrix4 * = 0) {}
/// Set viewport.
void SetViewport(const fRect &) {}
/// Get viewport.
fRect GetViewport() const { return fRect(0.f, 0.f, (float)dimensions.x, (float)dimensions.y); }
/// Clear the user clipping plane.
void ClearClippingPlane() {}
/// Set the user clipping plane.
void SetClippingPlane(const Vector4 &nUnused(p), const Vector4 &nUnused(n)) {}
/// Set clipping rect.
void SetClippingRect(const fRect *) {}
/// Get clipping rect.
fRect GetClippingRect() const { return fRect(-1, -1, -1, -1); }
virtual ~NullRenderer() { Close(); }
};
} // Render
} // GS
#endif // __NNULLRENDERER__

View File

@ -0,0 +1,100 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __NOBJECT__
#define __NOBJECT__
#include "core/renderable.h"
#include "core/skin.h"
#include "core/item.h"
namespace GS {
namespace Core {
/*!
@short Object class.
This class simply links a geometry with an item and provide some wrapper
functions to render them.
@author Emmanuel Julien (ejulien@gsworks.fr)
*/
class Object : public Item, public Renderable
{
protected:
AutoPtr <Skin> skin;
public:
struct RenderData
{ Render::sGeometry geometry; };
static float lod_bias;
/*!
@name Renderable interface.
@{
*/
/// Compute the renderable minmax.
virtual void ComputeRenderableMinMax(MinMax &);
/// Get the renderable primitive list for this renderable.
virtual uint GetRenderablePrimitiveList(const Camera &view, const Camera &default_view, Stack <Render::Primitive *> &, Renderable::Context = Renderable::Context_Default, bool cull = true);
/// Setup item render data.
virtual void RenderSetup(ResourceFactories * = 0);
/// @}
bool cache_geometry; ///< Whether the object should reuse cached geometry or create new instances.
/// Compute object world axis-aligned bounding box.
void ComputeLocalMinMax(MinMax &) const;
/// Return the object skin.
Skin *GetSkin() const { return skin; }
/// Return the binding bone matrix.
bool GetBindMatrix(uint, Matrix4 &) const;
/// Update skin matrices.
void UpdateSkin();
/// Has skin.
inline bool HasSkin() const
{ return skin.IsValid() && skin->bones.GetCount(); }
inline uint GetBoneCount() const
{ return skin.IsValid() ? skin->bones.GetCount() : 0; }
inline Item *GetBone(uint n) const
{ return skin.IsValid() ? skin->bones[n] : 0; }
/// Allocate skin binding structures.
virtual bool AllocateSkin(uint bone_count);
/// Free skin binding structures.
virtual void FreeSkin();
/*!
@short Bind a bone to this item's skin.
@note You can specify the binding matrix for this bone. If you do
not the current bone item matrix will be used.
*/
virtual bool BindBone(uint n, Item *bone);
String geometry;
AutoPtr <RenderData> render_data;
bool FromMetaTag(NML::Tag &);
NML::Tag *AsMetaTag() const;
Object();
};
} // Core
} // GS
#endif // __NOBJECT__

View File

@ -0,0 +1,74 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __OCTREE_RENDERABLE__
#define __OCTREE_RENDERABLE__
#include "core/renderable.h"
#include "container/narray_list.h"
namespace GS {
namespace Core {
/*
@short Octree for static renderable.
@author Emmanuel Julien (ejulien@nworks.fr)
*/
class OctreeCullingSystem : public Renderable
{
public:
struct CachedNode
{
Renderable *renderable;
MinMax minmax;
CachedNode() : renderable(0) {}
};
struct Node
{
Array <CachedNode *> cached_node;
MinMax minmax;
AutoPtr <Node> child[2];
};
private:
bool dirty;
Array <CachedNode> nodes;
AutoPtr <Node> root;
ArrayList <Renderable *> renderable_list;
/// Perform list insertion into the octree.
Node *InsertList(List <CachedNode *> &list);
void GetNodeRenderablePrimitive(Node *, const Camera &view, const Camera &default_view, Stack <Render::Primitive *> &, Context);
void CullNodeRenderablePrimitive(Node *, const Camera &view, const Camera &default_view, Stack <Render::Primitive *> &, Context);
public:
void AddRenderable(Renderable *);
void DeleteRenderable(Renderable *);
bool Update();
/// Compute renderable min-max.
virtual void ComputeRenderableMinMax(MinMax &);
/// Get primitive list.
virtual uint GetRenderablePrimitiveList(const Camera &view, const Camera &default_view, Stack <Render::Primitive *> &list, Context context = Context_Default, bool cull = true);
OctreeCullingSystem() : dirty(true) {}
};
} // Core
} // GS
#endif // __OCTREE_RENDERABLE__

View File

@ -0,0 +1,155 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __nPathKdtree__
#define __nPathKdtree__
#include "core/geometry_tree.h"
#include "container/narray.h"
#include "container/narray_list.h"
#include "memory/nshared_ptr.h"
namespace GS {
namespace Render { class Renderer; }
struct nMSegment : public SharedObject
{
Vector4 a,b;
float a_t, b_t;
MinMax bounding_box;
MinMax GetBoundingBox()
{
Vector4 min;
Vector4 max;
if(a.x > b.x)
{
min.x = b.x;
max.x = a.x;
}
else
{
min.x = a.x;
max.x = b.x;
}
if(a.y > b.y)
{
min.y = b.y;
max.y = a.y;
}
else
{
min.y = a.y;
max.y = b.y;
}
if(a.z > b.z)
{
min.z = b.z;
max.z = a.z;
}
else
{
min.z = a.z;
max.z = b.z;
}
bounding_box = MinMax(min, max);
return bounding_box;
}
};
/*!
@short Geometry polygon KD-tree.
@author Thomas Simonnet (thomas@movida-mail.com)
*/
class PathKdtree
{
private:
struct KDTreeNode
{
char m_KDTREE_NODE_TYPE_SPLIT;
int m_KDTREE_NODE_ID_ROPE[6];
float m_KDTREE_NODE_AABB[6];
float m_KDTREE_NODE_VALUE_SPLIT;
int m_KDTREE_NODE_ID;
int m_KDTREE_NODE_ID_CHILD_LEFT;
int m_KDTREE_NODE_ID_CHILD_RIGHT;
bool m_KDTREE_NODE_IS_LEAF;
int m_KDTREE_NODE_COUNT_SEGMENT;
int* m_KDTREE_NODE_ID_SEGMENT;
KDTreeNode();
~KDTreeNode(){delete []m_KDTREE_NODE_ID_SEGMENT;};
};
#define KDTREE_X_AXIS 0
#define KDTREE_Y_AXIS 1
#define KDTREE_Z_AXIS 2
#define KDTREE_SIDE_LEFT 0
#define KDTREE_SIDE_RIGHT 1
#define KDTREE_SIDE_BOTTOM 2
#define KDTREE_SIDE_TOP 3
#define KDTREE_SIDE_BACK 4
#define KDTREE_SIDE_FRONT 5
int m_count_bih;
float * m_TempFloatBih;
KDTreeNode* m_NodeTree;
int m_SizeTree;
protected:
void DrawKdtreeNode(Render::Renderer &render, int _CurrentNode, Matrix4& m);
void IncreaseSizeNodeKdtreeBuffer(int _IncreaseSize);
void CreateNodeKdtree(int &_CurrentNode, int *_IdSegment, int _CountSegment, int _CurrentDepth, bool _ForceCreateLeaf=false);
public:
SharedArrayList<nMSegment*> segment_list;
void draw_scene_debug(Render::Renderer &render, Matrix4& m);
/*!
@name KD-Tree specific functions.
@{
*/
/// Retrieve the index of the closest KD-tree node to a given location in world space.
int InsideKdTreeNode(const Vector4 &p, bool CheckInside=false);
bool InsideKdTree(const Vector4 &p);
/// @}
/*!
@name Interface core functions.
@{
*/
/// Raytrace the geometry tree.
void NearestQuadtreeTreeNode(Vector4 p, SharedArrayList<nMSegment*> &list_segment);
void BuildQuadtree();
/// add object to the quadtree.
virtual bool AddSegment(nMSegment* segment);
virtual bool AddSegment(SharedArrayList<nMSegment*> segment_list);
/// Free all internal structures.
virtual void Free();
/// @}
PathKdtree();
~PathKdtree()
{ Free(); }
};
} // GS
#endif // __nPathKdtree__

View File

@ -0,0 +1,66 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
------------------------------------------------------------------------------*/
#ifndef __NPHYSIC_MATERIAL__
#define __NPHYSIC_MATERIAL__
namespace GS {
namespace NML { class Tag; }
namespace Core {
/*!
@short Physic material.
@author Emmanuel Julien (ejulien@gsworks.fr)
*/
struct PhysicMaterial
{
/*!
@name General physic properties.
@{
*/
float mass; ///< Mass.
float dynamic_friction; ///< Dynamic friction.
float static_friction; ///< Static friction.
float restitution; ///< Restitution (inelastic/elastic).
bool anisotropic_friction; ///< Anisotropic friction.
float v_dynamic_friction; ///< Lateral dynamic friction.
float v_static_friction; ///< Lateral static friction.
/*!
@short Set material friction.
@note The static friction is a force opposing external forces
acting on a resting body. The dynamic friction is a force
opposing the motion of a moving body.
@see SetAnisotropicFriction().
*/
void SetFriction(float dync = 0.5f, float sttc = 0.75f)
{ dynamic_friction = dync; static_friction = sttc; }
/// @}
/*!
@name Soft body properties.
@{
*/
float sb_damping; ///< Damping.
float sb_stiffness; ///< Stiffness.
float sb_torsion; ///< Torsion.
/// @}
bool FromMetaTag(NML::Tag &);
NML::Tag *AsMetaTag() const;
PhysicMaterial();
virtual ~PhysicMaterial(){}
};
} // Core
} // GS
#endif // __NPHYSIC_MATERIAL__

View File

@ -0,0 +1,94 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __NRASTERFONT__
#define __NRASTERFONT__
#include "core/render_data.h"
#include "container/nlist.h"
namespace GS {
namespace Render {
struct ResourceFactory;
/*!
@short Raster font.
Raster font that can be used by the Write() method of the renderer.
A raster font is of fixed size and stored in one or several texture
pages.
@author Emmanuel Julien (ejulien@gsworks.fr)
*/
class RasterFont
{
public:
/// Raster font glyph.
struct Glyph
{
bool available;
float u, v;
float w, h;
float offx, offy;
float step;
uint page;
void Reset()
{
available = false;
u = v = 0;
w = h = 0;
offx = offy = 0;
step = 0;
page = 0;
}
Glyph() { Reset(); }
};
private:
SharedList <Texture *> pages;
Glyph glyph[256]; ///< Character LUT.
float baseline;
float height;
public:
String name;
float GetHeight(bool normalized = true) const;
float GetBaseline(bool normalized = true) const;
/// Return the texture corresponding to a given font page.
Texture *GetPage(uint) const;
/// Return information structure for a given glyph.
const Glyph *GetGlyphInfos(uchar) const;
// Return the rect of a single-line string (stops at the first carriage return).
Vector2 ComputeLineRect(const char *s, bool normalized = true) const;
/// Return the rect a multi-line string.
Vector2 ComputeStringRect(const char *s, bool normalized = true) const;
/*!
@short Load a raster font.
@param nml The font meta file description.
@param base Font page texture base name.
*/
bool Load(ResourceFactory &, const char *nml, const char *base);
void Unload();
};
} // Render
} // GS
#endif // __NRASTERFONT__

View File

@ -0,0 +1,205 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __NRENDERDATA__
#define __NRENDERDATA__
#include "core/material.h"
#include "core/texture_parm.h"
#include "geometry/bounding_box.h"
#include "memory/bit_field.h"
namespace GS {
class Picture;
namespace Core {
class Geometry;
struct Material;
struct Shader;
}
namespace Render {
class Renderer;
struct ResourceFactory;
//------------------------------------------------------------------------------
struct Material;
typedef SharedPtr <Material> sMaterial;
struct Geometry;
typedef SharedPtr <Geometry> sGeometry;
struct Texture;
typedef SharedPtr <Texture> sTexture;
struct Shader;
typedef SharedPtr <Shader> sShader;
//------------------------------------------------------------------------------
/*!
@short The renderer base data container.
This is the base structure holding all of a renderer's specific data for
an entity to be setup. This structure is to be derived for each functional
renderer implementation.
@see nRenderGeometry, nRenderMaterial, nRenderTexture, nLight.
*/
struct Data : public SharedObject
{
NPLACEMENT_NEW(Renderer)
String name;
/// Load from cooked resource.
virtual bool LoadCooked(const char *uri)
{ return false; }
virtual bool ShouldReloadOnDependencyChange(const char *n) const
{ return name == n; }
Data(const char *_name = 0) : name(_name) {}
};
//------------------------------------------------------------------------------
struct Geometry : public Data
{
Array <sMaterial> material_table;
BitField flag;
Vector4 hotspot;
MinMax minmax;
/// Change a material in the material table.
virtual bool SetMaterial(uint nUnused(index), Material *) { return false; }
/// Create from geometry.
virtual bool Create(ResourceFactory &, const Core::Geometry &) = 0;
sGeometry lod_proxy;
float lod_distance;
sGeometry shadow_proxy;
Array <Matrix4> bone_bind_matrix;
Array <MinMax> bone_minmax;
Geometry(const char *_name = 0) : Data(_name) {}
};
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
struct MaterialShader : public Data
{
virtual bool SetUserUniformValue(const char *name, const Vector4 &) = 0;
virtual bool SetUserUniformValue(const char *name, Texture *) = 0;
};
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
struct Material : public Core::BasicMaterial, public Data
{
sTexture texture_table[Core::Material::max_texture_stage];
/// Get the material shader.
virtual MaterialShader *GetShader() const { return 0; }
/// Create from material.
virtual bool Create(ResourceFactory &, const Core::Material &) = 0;
/// Clone this material (create an independent copy).
virtual Material *Clone() const { return NULL; }
Material(const char *_name = 0) : Data(_name) {}
};
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
struct Texture : public Data
{
enum Format
{
FormatRGBA8 = 0,
FormatBGRA8,
FormatRGBA16,
FormatRGBAF,
FormatDepth,
FormatDepthF,
FormatDepthOculus,
FormatInvalid
};
enum AA
{
NoAA = 0,
MSAA2x,
MSAA4x,
MSAA8x,
MSAA16x,
AALast
};
enum Usage
{
IsRenderTarget = (1 << 0), ///< used as a render-target
IsShaderResource = (1 << 1), ///< used as a shader resource
UsageDefault = IsShaderResource
};
TextureParm parm;
Format format;
AA aa;
bool is_rtt;
/// Configure texture as a shadow map.
virtual void ConfigureAsShadowMap() = 0;
bool Create(const Picture &, Usage = UsageDefault);
/// Create from raw picture data.
virtual bool Create(const char *data, int width, int height, Format = FormatRGBA8, AA = NoAA, Usage = UsageDefault) = 0;
virtual void Free() = 0;
virtual uint GetWidth() const = 0;
virtual uint GetHeight() const = 0;
/// Blit CPU data to texture.
virtual void Blit(const char *data, uint w, uint h, uint x = 0, uint y = 0, Format = Texture::FormatRGBA8) = 0;
/// Resize texture, does not preserve content.
virtual void Resize(uint w, uint h) = 0;
virtual void SetAnisotropy(TextureParm::Anisotropy) = 0;
virtual void SetFiltering(TextureParm::Filtering) = 0;
virtual void SetWrapping(TextureParm::Wrap u, TextureParm::Wrap v) = 0;
Texture(const char *_name = 0) : Data(_name)
{
format = FormatInvalid;
aa = NoAA;
is_rtt = false;
}
};
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
struct Shader : public Data
{
/// Create from shader.
virtual bool Create(ResourceFactory &, const Core::Shader &) = 0;
Shader(const char *_name = 0) : Data(_name) {}
};
//------------------------------------------------------------------------------
} // Render
} // GS
#endif // __NRENDERDATA__

View File

@ -0,0 +1,53 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
------------------------------------------------------------------------------*/
#ifndef __NRENDERPRIMITIVE__
#define __NRENDERPRIMITIVE__
#include "core/render_data.h"
namespace GS {
namespace Core
{
class Item;
class Emitter;
struct Patch;
}
namespace Render {
/// Render primitive.
struct Primitive
{
enum Type
{
Type_Geometry = 0,
Type_Emitter,
Type_TerrainPatch
};
Type type;
const Core::Item *item;
sGeometry geometry;
union
{
Core::Emitter *emitter;
Core::Patch *patch;
};
Primitive(Geometry *g, const Core::Item *i, float) : type(Type_Geometry), item(i), geometry(g), emitter(0) {}
Primitive(Core::Patch *p, const Core::Item *i, float) : type(Type_TerrainPatch), item(i), patch(p) {}
Primitive(Core::Emitter *e, const Core::Item *i, float) : type(Type_Emitter), item(i), emitter(e) {}
};
} // Render
} // GS
#endif // __NRENDERPRIMITIVE__

View File

@ -0,0 +1,45 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __NRENDER_RESOURCE_FACTORY__
#define __NRENDER_RESOURCE_FACTORY__
#include "core/render_data.h"
#include "core/resource_factory_event_interface.h"
namespace GS {
namespace Render {
struct ResourceFactory
{
sIResourceFactoryEvent event_handler;
virtual Geometry *NewGeometry() = 0;
virtual Material *NewMaterial() = 0;
virtual Texture *NewTexture() = 0;
virtual Shader *NewShader() = 0;
virtual Geometry *LoadGeometry(const char *, bool bypass_cache = false, Geometry * = 0) = 0;
virtual Material *LoadMaterial(const char *, bool bypass_cache = false, Material * = 0) = 0;
virtual Texture *LoadTexture(const char *, bool bypass_cache = false, Texture * = 0) = 0;
virtual Shader *LoadShader(const char *, bool bypass_cache = false, Shader * = 0) = 0;
virtual void ListCachedResources() {}
virtual uint GetCachedResourceCount() { return 0; }
virtual uint PurgeCache() { return 0; }
ResourceFactory() : event_handler(new IResourceFactoryEvent) {}
virtual ~ResourceFactory() {}
};
} // Render
} // GS
#endif // __NRENDER_RESOURCE_FACTORY__

View File

@ -0,0 +1,50 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
------------------------------------------------------------------------------*/
#ifndef __NRENDERABLE__
#define __NRENDERABLE__
#include "core/render_data.h"
#include "core/render_primitive.h"
#include "container/nstack.h"
namespace GS {
class MinMax;
namespace Core {
class Camera;
/*!
@short Renderer renderable item.
@author Emmanuel Julien (ejulien@nworks.fr)
*/
struct Renderable
{
enum Context
{
Context_Default = 0,
Context_Shadow,
Context_Occlusion
};
/// Is this renderable enabled.
virtual inline bool IsRenderable() const { return true; }
/// Compute the renderable minmax.
virtual void ComputeRenderableMinMax(MinMax &) = 0;
/// Get the renderable primitive list, returns the number of primitive that were considered for addition to the final list.
virtual uint GetRenderablePrimitiveList(const Camera &view, const Camera &default_view, Stack <Render::Primitive *> &, Context = Context_Default, bool cull = true) = 0;
virtual ~Renderable() {}
};
} // Core
} // GS
#endif // __NRENDERABLE__

View File

@ -0,0 +1,402 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __NBASERENDERER__
#define __NBASERENDERER__
#include "core/renderable.h"
#include "core/material.h"
#include "timing/benchmark.h"
#include "data/registry.h"
#include "geometry/frustum.h"
#include "geometry/rect.h"
#include "plugin/plugin_manager.h"
#include "async/job_perf.h"
namespace GS {
namespace Render {
class RasterFont;
struct IEnvironment;
/// Video mode settings.
enum VideoMode
{
VideoWindowed = 0,
VideoFullscreen,
VideoWindowedQuiet, ///< Open windowed output but do not automatically show the window.
VideoRaw,
VideoGenericPAL, ///< Used by console systems.
VideoGenericNTSC
};
///
struct Window
{
/// Get handle.
virtual void *GetHandle() const = 0;
/// Get render window size.
virtual void GetSize(uint &w, uint &h) = 0;
virtual ~Window() {}
};
/*!
@short Renderer base class.
This the base that has to be derived to add support for a new renderer.
For example implementations see NullRenderer or GPURenderer.
nNull_Renderer can be used as a starting point in implementing a
new renderer.
This class also implements all functions required to maintain the minimum
concept of viewport used by the engine.
@see S3D::Scene::SetSceneInterface().
@author Emmanuel Julien (ejulien@gsworks.fr)
*/
class Renderer : public RegistryListener
{
public:
NPLACEMENT_NEW(Renderer)
/// Return the plugin class.
static const char *GetPluginClass() { return "Renderer"; }
/*!
@short Return the plugin version.
@note This version number must be increased whenever a modification
is made to the base interface in order to prevent incompatible
plugin from being loaded.
*/
static uint GetPluginVersion() { return 1; }
/*!
@name Resource factory.
@{
*/
virtual Geometry *NewGeometry(const char *name = 0) = 0;
virtual Material *NewMaterial(const char *name = 0) = 0;
virtual Texture *NewTexture(const char *name = 0) = 0;
virtual Shader *NewShader(const char *name = 0) = 0;
/// @}
/// Clear function
enum ClearFunction
{
ClearColor = (1 << 0),
ClearDepth = (1 << 1),
ClearAll = ~0
};
/*!
@short Geometry updater control word.
@see UpdateGeometry().
*/
enum GeoUpdate
{
GEOUPDATE_NONE = 0,
GEOUPDATE_IDX,
GEOUPDATE_VTX,
GEOUPDATE_VNRM,
GEOUPDATE_PNRM,
GEOUPDATE_SOFTVTX,
GEOUPDATE_RGB
};
/// Renderer statistics.
struct Statistics
{
String adapter,
vendor;
uint queue_pass, ///< Number of queue pass rendered.
light_processed, ///< Number of light processed.
renderable_processed, ///< Number of renderable processed.
renderable_drawn, ///< Number of renderable drawn.
list_drawn, ///< Number of display list drawn.
triangle_drawn, ///< Number of triangles drawn.
texture_memory, ///< Texture memory in use.
geometry_memory; ///< Geometry memory in use.
ASync::JobPerf bench_prepare_light;
Benchmark bench_post_process,
bench_render;
/// Reset statistics.
void Reset()
{
queue_pass = 0;
light_processed = 0;
renderable_processed = 0;
renderable_drawn = 0;
list_drawn = 0;
triangle_drawn = 0;
bench_post_process.Reset();
bench_prepare_light.Reset();
bench_render.Reset();
}
Statistics()
{
texture_memory = 0;
geometry_memory = 0;
Reset();
}
};
/// Reload managed resources on context change.
virtual void OnContextChanged(ResourceFactory *) {}
/// Get current adapter ideal triangle batch size.
virtual uint GetTriangleIdealBatchSize() const { return 16384; }
/*!
@name Renderer registry.
@{
*/
Registry registry;
virtual RegistryRValue ProcessMessage(RegistryMessage, const Registry *, const void *parm) { return RegistryReturn_Ok; }
/*!
@}
@name Renderer queue system.
@{
*/
List <Core::Renderable *> renderable_list;
/// Delete the renderable list.
void DeleteRenderableList();
/// Push a renderable to the renderable list.
void PushRenderable(Core::Renderable *);
/*!
@short Build a renderable primitive list.
A separate lod view can be provided to ensure selection of the
correct geometry lod when rendering derived views such as shadow
maps.
*/
uint BuildRenderablePrimitiveList(const Core::Camera &view, const Core::Camera &lod_view, Stack <Primitive *> &, Core::Renderable::Context = Core::Renderable::Context_Default) const;
/// @}
protected:
String error; ///< Last error description.
/// Request lights to the manager and setup lighting.
void RequestAndSetupLighting(Vector4 &pos);
// Renderer state.
bool fullscreen; ///< Windowed or fullscreen?
float output_aspect_ratio; ///< Output aspect ratio override (default: -1 for no override)
float global_aspect_ratio; ///< Global aspect ratio.
Core::Camera *view_item; ///< Current view item.
Registry *view_registry; ///< Current view registry.
Frustum frustum; ///< Current frustum.
sTexture output_texture; ///< Frame buffer output texture.
List <Window *> windows;
Window *output_window;
Window *default_window;
public:
tVector2 <uint> dimensions; ///< Output dimensions.
tVector2 <uint> ideal_render_system_vr_resolution;
tVector2 <uint> saved_ideal_render_system_vr_resolution;
float ipd;
bool use_fix_camera;
Window* GetOutputWindow(){ return output_window; }
// Renderer statistics.
Statistics stats;
/// Set output texture.
virtual void SetOutputTexture(Texture *texture) { output_texture = texture; }
/// Get output dimensions.
tVector2 <uint> GetOutputDimensions() const;
/// Return the output aspect ratio.
float GetOutputAspectRatio() const;
/// Set the output aspect ratio override (0 to disable), returns the previous aspect ratio.
float SetOutputAspectRatio(float k = 0) { float v = output_aspect_ratio; output_aspect_ratio = k; return v; }
/// Get renderer global aspect ratio.
float GetGlobalAspectRatio() const { return global_aspect_ratio; }
/// Set renderer global aspect ratio, returns the previous aspect ratio.
float SetGlobalAspectRatio(float k = 1.f) { float v = global_aspect_ratio; global_aspect_ratio = k; return v; }
/// Is the renderer fullscreen.
bool isFullscreen() const { return fullscreen; }
virtual void ResetStatistics() { stats.Reset(); }
/// Display on-screen statistics.
virtual void DrawProfilerText(RasterFont *[2], float &x, float &y);
/// Return the current camera.
Core::Camera *GetCamera() const;
/// Set the current viewing item.
void SetCamera(Core::Camera *);
/// Apply view.
virtual void ApplyCamera();
/// Set view registry.
void SetViewRegistry(Registry *);
/*!
@short Interface used by the renderer to query environment.
@see SetEnvironmentInterface().
*/
IEnvironment *environment_interface;
/// Set the scene interface.
void SetEnvironmentInterface(IEnvironment *itf) { environment_interface = itf; }
/*!
@name Renderer core.
These are the functions to be reimplemented by a capable renderer.
@{
*/
/// Start a new frame.
virtual bool BeginDrawList() = 0;
/// End current frame, draw to back-buffer.
virtual void EndDrawList() = 0;
/// Returns the renderer's name as a C string.
virtual const char *GetName() const = 0;
/// Returns a C string describing the renderer.
virtual const char *GetDescription() const = 0;
/// Returns a C string containing the renderer version number.
virtual const char *GetVersion() const = 0;
/// Returns a C string containing the last error description.
virtual const char *GetError() const { return error; }
/// Open video.
virtual bool Open(uint width, uint height, char bpp = 32, VideoMode = VideoWindowed, const void *sys_handle = 0) = 0;
/// Free all renderer resources.
virtual void Free() {}
/// Close video.
virtual void Close() {}
/// Setup core resources.
virtual bool SetupCoreResources(bool support_3d = true) { return true; }
/// Explicitly resize video output.
virtual bool ResizeVideo(uint width, uint height) = 0;
/// Switch to/from fullscreen.
virtual void SetFullscreen(bool = true) = 0;
/// Refresh display output.
virtual void Refresh() = 0;
/// Return a pointer to the current subsystem window output.
virtual void *GetCurrentSystemWindowHandle() const = 0;
/// Setup an extra window to use as renderer output.
virtual Window *NewOutputWindow(const void *) = 0;
/// Set the output window.
virtual void SetOutputWindow(Window * = 0) = 0;
/// Free a rendering window.
virtual void FreeOutputWindow(Window *) = 0;
/// Render the display queue.
virtual void RenderList() = 0;
/// Request that the frame be displayed to current output window.
virtual void ShowFrame() = 0;
/// Clear the render target.
virtual void Clear(float r, float g, float b, float a = 1.f, float z = 1.f, ClearFunction = ClearAll) = 0;
/// Grab the frame buffer to a texture.
virtual void GrabDisplay(Texture *) = 0;
/// Grab the frame buffer to a picture.
virtual void GrabDisplay(Picture &) = 0;
virtual void RenderFrame() {};
/// Set a texture as render target.
virtual void SetRenderTarget(Texture *) = 0;
/// Draw line.
virtual void DrawLine(uint count, const Vector4 *, const Color * = 0, Core::Material::BlendOperator = Core::Material::Blend_None, Core::Material::RenderWord = Core::Material::Render_None, Shader * = 0) = 0;
/// Draw triangle.
virtual void DrawTriangle(uint count, const Vector4 *, const ushort *idx = 0, const Color * = 0, const Vector2 * = 0, const Texture * = 0, Core::Material::BlendOperator = Core::Material::Blend_None, Core::Material::RenderWord = Core::Material::Render_None, Shader * = 0) = 0;
/// Draw sprite.
virtual void DrawSprite(uint count, const Vector4 *, const Color * = 0, const float *size = 0, const Texture * = 0, float global_size = 1.f, Core::Material::BlendOperator = Core::Material::Blend_None, Core::Material::RenderWord = Core::Material::Render_None, Shader * = 0) = 0;
//
struct WriterConfig
{
bool correct_ar; ///< Enforce aspect ratio.
bool normalized; ///< Normalized/absolute coordinates.
WriterConfig(bool normd = true, bool ar = true) : normalized(normd), correct_ar(ar) {}
};
enum WriterAlignment
{
AlignLeft = 0,
AlignMiddle,
AlignRight
};
/// Output string to screen.
virtual void Write(const RasterFont &, const char *, float &x, float &y, const WriterConfig &, float s = 1, const Color * = 0, WriterAlignment = AlignLeft, bool mirrored = false) = 0;
/// Set the view matrix.
virtual void SetViewMatrix(const Matrix4 &, const Matrix4 *inverse = 0) = 0;
/// Set the projection matrix.
virtual void SetProjectionMatrix(const Matrix4 &) = 0;
/// Set the world matrix.
virtual void SetWorldMatrix(const Matrix4 &, const Matrix4 *inverse = 0) = 0;
/// Clear the user clipping plane.
virtual void ClearClippingPlane() = 0;
/// Set the user clipping plane.
virtual void SetClippingPlane(const Vector4 &p, const Vector4 &n) = 0;
/// Set clipping rect.
virtual void SetClippingRect(const fRect *) = 0;
/// Get clipping rect.
virtual fRect GetClippingRect() const = 0;
/// Set viewport.
virtual void SetViewport(const fRect &) = 0;
/// Get viewport.
virtual fRect GetViewport() const = 0;
/// @}
bool FromMetaTag(NML::Tag &);
NML::Tag *AsMetaTag();
Renderer();
virtual ~Renderer();
};
typedef PluginManager <Renderer> RendererPluginManager;
} // Render
} // GS
#endif // __NBASERENDERER__

View File

@ -0,0 +1,72 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __NRENDERERENVINTERFACE__
#define __NRENDERERENVINTERFACE__
#include "core/render_data.h"
#include "color/color.h"
#include "container/nlist.h"
namespace GS {
struct Vector4;
class Frustum;
namespace Core {
class Camera;
class Light;
}
namespace Render {
/*
@short Renderer environment interface.
Used by the renderer to communicate events and query environment informations.
*/
struct IEnvironment
{
/// Get environment clock.
virtual float GetClock() const { return 0; }
/// Get environment time of day.
virtual float GetTimeOfDay() const { return 0.f; }
/// Get user sky box shader.
virtual Shader *GetSkyboxShader() const { return 0; }
/// Get sky box texture layers.
virtual bool GetSkyboxLayers(sTexture [2]) const { return false; }
/// Get clear color.
virtual Color GetClearColor() const { return Color::Black; }
/// Get ambient color.
virtual Color GetAmbientColor() const { return Color::Black; }
/// Get environment probe.
virtual void GetEnvironmentProbe(sTexture &/*radiance*/, sTexture &/*irradiance*/) const {}
/// Get current camera.
virtual Core::Camera *GetCurrentCamera() const { return 0; }
/// Get all lights in frustum.
virtual void GetLightsInFrustum(const Vector4 &/*world_pos*/, const Frustum &/*frustum*/, List <Core::Light *> &/*list*/, uint /*limit*/ = 0) const = 0;
/// Get closest lights.
virtual void GetClosestLights(const Vector4 &/*world_pos*/, List <Core::Light *> &/*list*/, uint /*limit*/ = 0) const = 0;
/// Get fog enabled.
virtual bool IsFogEnabled() const { return false; }
/// Get fog configuration.
virtual bool GetFogConfiguration(Color &color, float &fog_near, float &fog_far) const { return false; }
/// Render user/debug primitive hook.
virtual void OnRenderUser(Renderer *) const {}
virtual ~IEnvironment() {}
};
} // Render
} // GS
#endif // __NRENDERERENVINTERFACE__

View File

@ -0,0 +1,40 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __NRENDERER_RESOURCE_FACTORY__
#define __NRENDERER_RESOURCE_FACTORY__
#include "core/render_resource_factory.h"
namespace GS {
namespace Render {
class Renderer;
//
struct RendererResourceFactory : public ResourceFactory
{
Renderer &renderer;
virtual Geometry *NewGeometry();
virtual Material *NewMaterial();
virtual Texture *NewTexture();
virtual Shader *NewShader();
virtual Geometry *LoadGeometry(const char *, bool bypass_cache = false, Geometry * = 0);
virtual Material *LoadMaterial(const char *, bool bypass_cache = false, Material * = 0);
virtual Texture *LoadTexture(const char *, bool bypass_cache = false, Texture * = 0);
virtual Shader *LoadShader(const char *, bool bypass_cache = false, Shader * = 0);
RendererResourceFactory(Renderer &r) : renderer(r) {}
};
} // Render
} // GS
#endif // __NRENDERER_RESOURCE_FACTORY__

View File

@ -0,0 +1,66 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __NRENDERER_TOOLBOX__
#define __NRENDERER_TOOLBOX__
#include "core/renderer.h"
namespace GS {
namespace RendererToolbox {
using Core::Material;
using Render::Renderer;
/// Wrapper to display a cross in 3D.
void DrawCross(Renderer &, const Vector4 &, float size = Units::Mtr(1), const Color * = 0, Material::BlendOperator = Material::Blend_None);
/// Wrapper to display an axis aligned square in 3D.
void DrawSquare(Renderer &, const Vector4 &, float size = Units::Mtr(1), Material::BlendOperator = Material::Blend_None);
/// Wrapper to display an OOBB using the line function of a derived renderer.
void DrawOBB(Renderer &, const OBB &, const Color * = 0, Material::BlendOperator = Material::Blend_None);
/// Wrapper to display an OOBB using the triangle function of a derived renderer.
void DrawFilledOBB(Renderer &, const OBB &, const Color *, Material::BlendOperator = Material::Blend_None, Material::RenderWord = Material::Render_None);
/// Wrapper to display an AABB in 3D.
void DrawAABB(Renderer &, const MinMax &, const Color * = 0, Material::BlendOperator = Material::Blend_None);
/// Wrapper to display a cube in 3D.
void DrawCube(Renderer &, const Vector4 &, float size = Units::Mtr(1), const Color * = 0, Material::BlendOperator = Material::Blend_None);
/// Wrapper to display a sphere in 3D.
void DrawSphere(Renderer &, const Vector4 &, float radius = Units::Mtr(1), const Color * = 0, Material::BlendOperator = Material::Blend_None);
/// Wrapper to display a ball in 3D.
void DrawBall(Renderer &, const nMatrix4 &, float radius = Units::Mtr(1), Color * = 0, Material::BlendOperator = Material::Blend_None);
/// Wrapper to display a circle in 3D.
void DrawCircle(Renderer &, const Vector4 &, float radius = Units::Mtr(1), const Matrix3 * = 0, const Color * = 0, Material::BlendOperator = Material::Blend_None);
/// Wrapper to display a cylinder in 3D.
void DrawCylinder(Renderer &, const Vector4 &, float radius = Units::Mtr(1), float length = Units::Mtr(1), const Matrix3 * = 0, const Color * = 0, Material::BlendOperator = Material::Blend_None);
/// Wrapper to display a capsule in 3D.
void DrawCapsule(Renderer &, const Vector4 &, float radius = Units::Mtr(1.f), float length = Units::Mtr(1), const Matrix3 * = 0, const Color * = 0, Material::BlendOperator = Material::Blend_None);
/// Wrapper to display a cone in 3D.
void DrawCone(Renderer &, const Vector4 &, float radius = Units::Mtr(1.f), float length = Units::Mtr(1), const Matrix3 * = 0, const Color * = 0, Material::BlendOperator = Material::Blend_None);
/// Wrapper to line 3D.
void Line3D(Renderer &, const Vector4 &, const Vector4 &, const Color * = 0, Material::BlendOperator = Material::Blend_None, Material::RenderWord = Material::Render_None);
/// Draw triangle.
void Triangle3D(Renderer &, const Vector4 [3], const Color [3] = 0, const Vector2 [3] = 0, const Render::Texture * = 0, Material::BlendOperator = Material::Blend_None, Material::RenderWord = Material::Render_None);
/// Return nearest but highest power of two from a given value.
template <class T> T GetPow2(T v, bool no_shrink = false)
{
T h = 1;
if (no_shrink)
while (h < v)
h *= 2;
else
while ((h + h / 2) < v)
h *= 2;
return h;
}
} // RendererToolbox
} // GS
#endif // __NRENDERER_TOOLBOX__

View File

@ -0,0 +1,32 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __NRESOURCEFACTORIES__
#define __NRESOURCEFACTORIES__
#include "core/graphic_resource_factory.h"
#include "core/render_resource_factory.h"
#include "core/mixer_resource_factory.h"
namespace GS {
namespace Core {
struct ResourceFactories : public SharedObject
{
AutoPtr <ResourceFactory> graphic;
AutoPtr <Render::ResourceFactory> render;
AutoPtr <Audio::ResourceFactory> audio;
};
typedef SharedPtr <ResourceFactories> sResourceFactories;
} // Core
} // GS
#endif // __NRESOURCEFACTORIES__

View File

@ -0,0 +1,29 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __RESOURCEFACTORYEVENTINTERFACE__
#define __RESOURCEFACTORYEVENTINTERFACE__
#include "memory/nshared_ptr.h"
namespace GS {
//
struct IResourceFactoryEvent : public SharedObject
{
virtual void OpenLoad() {}
virtual void LoadProgress(const char *, float = -1) {}
virtual void EndLoad() {}
};
typedef SharedPtr <IResourceFactoryEvent> sIResourceFactoryEvent;
} // GS
#endif // __RESOURCEFACTORYEVENTINTERFACE__

View File

@ -0,0 +1,27 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __RESOURCE_GEOMETRY_GENERATOR__
#define __RESOURCE_GEOMETRY_GENERATOR__
namespace GS {
namespace Core {
class Geometry;
namespace GeometryGenerator {
/// Is a geometry name referring to a generated resource.
bool IsGenerated(const char *);
/// Generate a geometry.
bool Generate(const char *, Geometry &);
} // GeometryGenerator
} // Core
} // GS
#endif // __RESOURCE_GEOMETRY_GENERATOR__

View File

@ -0,0 +1,79 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __NRENDERERSHADER__
#define __NRENDERERSHADER__
#include "core/shader_input.h"
#include "container/nlist.h"
#include "memory/nshared_ptr.h"
namespace GS {
namespace Core {
// Shader varying.
struct ShaderVarying
{
String type, name;
};
/*!
@short Shader base class.
@author Emmanuel Julien (ejulien@gsworks.fr)
*/
struct Shader : public SharedObject
{
String name;
String vertex_decl, vertex,
pixel_decl, pixel,
geometry_decl, geometry;
AutoList <ShaderInput *> input_list;
AutoList <ShaderVarying *> varying_list;
/// Clone this shader to a new object.
bool Clone(Shader &clone) const;
/// Declare a varying.
ShaderVarying *DeclareVarying(const char *name, const char *type);
/// Declare an input.
ShaderInput *DeclareInput(const char *name, ShaderInput::DataType data_type, ShaderInput::Semantic semantic, ShaderInput::Type parm_type, ShaderInput::Scope parm_scope, uint array_size = 1);
/// Get a shader input from its semantic.
ShaderInput *GetInput(ShaderInput::Semantic semantic) const;
/// Set a define.
void Define(const char *, ShaderInput::Scope define_scope);
/// Declare inputs from a meta tag.
void ParseInputTag(NML::Tag *);
/// Declare varyings from a meta tag.
void ParseVaryingTag(NML::Tag *);
/// Add an ISL section to this shader.
bool AddISLSection(const char *uri);
void Clear();
/*!
@name Serialization.
@{
*/
bool FromMetaTag(NML::Tag &);
NML::Tag *AsMetaTag() const;
/// @}
Shader(const char *name = 0, const char *vertex = 0, const char *fragment = 0, const char *geometry = 0);
};
} // Core
} // GS
#endif // __NRENDERERSHADER__

View File

@ -0,0 +1,859 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __NSHADER_BLOCK__
#define __NSHADER_BLOCK__
#include "core/shader.h"
#include "color/color.h"
#include "math/matrix3.h"
#include "math/matrix4.h"
#include "nstring/nstring.h"
namespace GS {
namespace NML { class Tag; }
namespace Core {
struct ShaderBlockPin;
struct ShaderBlock;
typedef ShaderBlock * pShaderBlock;
/*!
@short Block shader value.
Used by the raytracer software implementation of the shader blocks.
*/
struct ShaderBlockValue
{
enum BlockValueType
{
BlockValueNone = 0,
BlockValueVector,
BlockValueMatrix3,
BlockValueMatrix4,
BlockValueTexture
};
BlockValueType type;
// Can't union those and most of all we don't want runtime allocations here...
Vector4 v;
Matrix3 m3;
Matrix4 m4;
String t;
void Set(const float &_f)
{ v.x = _f; type = BlockValueVector; }
void Set(const Vector4 &_v)
{ v = _v; type = BlockValueVector; }
void Set(const Matrix3 &_m)
{ m3 = _m; type = BlockValueMatrix3; }
void Set(const Matrix4 &_m)
{ m4 = _m; type = BlockValueMatrix4; }
void Set(const char *_t)
{ t = _t; type = BlockValueTexture; }
ShaderBlockValue() : type(BlockValueNone) {}
};
/*!
@short Base render block.
A render block is a component of a render map. It represents an input, an
operator to the render map.
@author Emmanuel Julien (ejulien@gsworks.fr)
*/
struct ShaderBlock
{
enum BlockType
{
TypeNone = 0,
// Input blocks.
TypeGeometryVertex,
TypeGeometryNormal,
TypeGeometryUV,
TypeGeometrySkinning,
TypeGeometryVertexColor,
TypeGeometryTangentFrame,
TypeRenderBuffer,
TypeTexture,
TypeTextureSampler,
TypeConstant,
TypeColor,
TypeMaterialParam,
TypeMaterialTexture,
TypeScreenUV,
TypeViewVector,
TypeViewport,
// Matrix blocks.
TypeNormalViewMatrix,
TypeNormalMatrix,
TypeModelViewMatrix,
TypeModelMatrix,
// Operator blocks.
TypeMix,
TypeAdd,
TypeMul,
TypeSub,
TypeDiv,
TypeDot,
TypeCross,
TypeClamp,
TypeNormalize,
TypeSwizzle,
TypeBuild,
TypeSin,
TypeCos,
TypePow,
TypeAbs,
// Packing operators.
TypeUnpackColorToVector,
TypePackVectorToColor,
// Engine parameters.
TypeClock,
TypeInvalid
};
/// Verbose block type.
static const char *BlockTypeToString(BlockType type)
{
switch (type)
{
case TypeNone: return "None";
case TypeGeometryVertex: return "Geometry Vertex";
case TypeGeometryNormal: return "Geometry Normal";
case TypeGeometryUV: return "Geometry UV";
case TypeGeometrySkinning: return "Geometry Skinning";
case TypeGeometryVertexColor: return "Geometry RGB";
case TypeGeometryTangentFrame: return "Geometry Tangent Frame";
case TypeRenderBuffer: return "Render Buffer";
case TypeTexture: return "Texture";
case TypeTextureSampler: return "Texture Sampler";
case TypeConstant: return "Constant";
case TypeColor: return "Color";
case TypeMaterialParam: return "Material Parameter";
case TypeMaterialTexture: return "Material Texture";
case TypeScreenUV: return "Screen UV";
case TypeViewVector: return "View Vector";
case TypeViewport: return "Viewport";
case TypeNormalViewMatrix: return "Normal View Matrix";
case TypeNormalMatrix: return "Normal Matrix "; ///< ! The additional space is NEEDED! (Normal matrix is the name of a legacy version of this node)
case TypeModelViewMatrix: return "Model View Matrix";
case TypeModelMatrix: return "Model Matrix";
case TypeMix: return "Mix";
case TypeAdd: return "Add";
case TypeMul: return "Multiply";
case TypeSub: return "Subtract";
case TypeDiv: return "Divide";
case TypeDot: return "Dot";
case TypeCross: return "Cross";
case TypeClamp: return "Clamp";
case TypeNormalize: return "Normalize";
case TypeSwizzle: return "Swizzle";
case TypeBuild: return "Build";
case TypeSin: return "Sinus";
case TypeCos: return "Cosinus";
case TypePow: return "Pow";
case TypeAbs: return "Abs";
case TypeUnpackColorToVector: return "Unpack color to vector";
case TypePackVectorToColor: return "Pack vector to color";
case TypeClock: return "Clock";
case TypeInvalid: break;
}
return "Invalid";
}
Vector2 pos;
BlockType type;
/*
@name Block input/output.
@{
*/
/// Get input count.
virtual uint GetInputCount() const = 0;
/// Get input block.
virtual ShaderBlock *GetInput(uint n) const = 0;
/// Set input.
virtual bool SetInput(uint n, ShaderBlock *in) = 0;
/// Get input pin.
virtual const ShaderBlockPin *GetInputPin(uint n) const = 0;
/// Get block output pin.
virtual const ShaderBlockPin *GetOutputPin() const = 0;
/// Evaluate block output type.
virtual int GetOutputType() const = 0;
/// @}
/// Get block label.
virtual String GetLabel() const = 0;
/// Get block id.
virtual String GetId() const = 0;
/// Is this block equivalent to another block.
bool IsEquivalent(const ShaderBlock *input_block) const;
/// Gather all of this block children.
void GatherChildren(List <ShaderBlock *> &children);
/// Import block map from metatag.
static Array <pShaderBlock> *BlockMapFromMetaTag(NML::Tag &);
/// Import branch from metatag.
static ShaderBlock *BranchFromMetaTag(NML::Tag &, Array <pShaderBlock> *block_map = 0);
static NML::Tag *BlockMapAsMetaTag(const List <ShaderBlock *> &block_map);
NML::Tag *BranchAsMetaTag(List <ShaderBlock *> &block_map);
NML::Tag *ParamAsMetaTag() const;
ShaderBlock() : type(TypeNone) {}
virtual ~ShaderBlock() {}
};
//------------------------------------------------------------------------------
#define __SpecializeBlock(__LABEL__, __INPUT_COUNT__)\
static ShaderBlockPin input_pin[__INPUT_COUNT__];\
static ShaderBlockPin output_pin;\
\
ShaderBlock *input[__INPUT_COUNT__];\
\
String GetLabel() const\
{ return __LABEL__; }\
uint GetInputCount() const\
{ return __INPUT_COUNT__; }\
bool SetInput(uint n, ShaderBlock *block)\
{\
if (n >= __INPUT_COUNT__)\
return false;\
if (block && !(input_pin[n].compatibility & block->GetOutputType()))\
return false;\
input[n] = block;\
return true;\
}\
ShaderBlock *GetInput(uint n) const\
{ return (n < __INPUT_COUNT__) ? input[n] : 0; }\
const ShaderBlockPin *GetInputPin(uint n) const\
{ return (n < __INPUT_COUNT__) ? &input_pin[n] : 0; }\
const ShaderBlockPin *GetOutputPin() const\
{ return &output_pin; }\
int GetOutputType() const;
#define __SpecializeBlockNoInput(__LABEL__)\
static ShaderBlockPin output_pin;\
\
String GetLabel() const\
{ return __LABEL__; }\
uint GetInputCount() const\
{ return 0; }\
bool SetInput(uint /*n*/, ShaderBlock */*block*/)\
{ return false; }\
ShaderBlock *GetInput(uint /*n*/) const\
{ return 0; }\
const ShaderBlockPin *GetInputPin(uint /*n*/) const\
{ return 0; }\
const ShaderBlockPin *GetOutputPin() const\
{ return &output_pin; }\
int GetOutputType() const;
//------------------------------------------------------------------------------
/*
@short Render block pin description.
@author Emmanuel Julien (ejulien@gsworks.fr)
*/
struct ShaderBlockPin
{
const char *name,
*desc;
int compatibility; ///< Pin connection compatibility
};
struct SinusShaderBlock : public ShaderBlock
{
__SpecializeBlock("Sinus", 1)
String GetId() const
{ return "Sin"; }
SinusShaderBlock(ShaderBlock *block = 0)
{
type = TypeSin;
input[0] = block;
}
};
struct CosinusShaderBlock : public ShaderBlock
{
__SpecializeBlock("Cosinus", 1)
String GetId() const
{ return "Cos"; }
CosinusShaderBlock(ShaderBlock *block = 0)
{
type = TypeCos;
input[0] = block;
}
};
struct PowShaderBlock : public ShaderBlock
{
__SpecializeBlock("Pow", 2)
String GetId() const
{ return "Pow"; }
PowShaderBlock(ShaderBlock *v = 0, ShaderBlock *p = 0)
{
type = TypePow;
input[0] = v;
input[1] = p;
}
};
struct AbsShaderBlock : public ShaderBlock
{
__SpecializeBlock("Abs", 1)
String GetId() const
{ return "Abs"; }
AbsShaderBlock(ShaderBlock *v = 0)
{
type = TypeAbs;
input[0] = v;
}
};
struct ClockShaderBlock : public ShaderBlock
{
__SpecializeBlockNoInput("Clock")
String GetId() const
{ return "Clock"; }
ClockShaderBlock()
{ type = TypeClock; }
};
struct ScreenUVShaderBlock : public ShaderBlock
{
__SpecializeBlockNoInput("Screen UV")
String GetId() const
{ return "ScreenUV"; }
ScreenUVShaderBlock()
{ type = TypeScreenUV; }
};
struct ViewVectorShaderBlock : public ShaderBlock
{
__SpecializeBlockNoInput("View Vector")
String GetId() const
{ return "ViewV"; }
ViewVectorShaderBlock()
{ type = TypeViewVector; }
};
struct ViewportShaderBlock : public ShaderBlock
{
__SpecializeBlockNoInput("Viewport")
String GetId() const
{ return "Viewport"; }
ViewportShaderBlock()
{ type = TypeViewport; }
};
struct NormalViewMatrixShaderBlock : public ShaderBlock
{
__SpecializeBlockNoInput("Normal View Matrix")
String GetId() const
{ return "NormalViewMatrix"; }
NormalViewMatrixShaderBlock()
{ type = TypeNormalViewMatrix; }
};
struct NormalMatrixShaderBlock : public ShaderBlock
{
__SpecializeBlockNoInput("Normal Matrix ")
String GetId() const
{ return "NormalMatrix"; }
NormalMatrixShaderBlock()
{ type = TypeNormalMatrix; }
};
struct ModelViewMatrixShaderBlock : public ShaderBlock
{
__SpecializeBlockNoInput("Model View Matrix ")
String GetId() const
{ return "ModelViewMatrix"; }
ModelViewMatrixShaderBlock()
{ type = TypeModelViewMatrix; }
};
struct ModelMatrixShaderBlock : public ShaderBlock
{
__SpecializeBlockNoInput("Model Matrix")
String GetId() const
{ return "ModelMatrix"; }
ModelMatrixShaderBlock()
{ type = TypeModelMatrix; }
};
struct UnpackColorToVectorShaderBlock : public ShaderBlock
{
__SpecializeBlock("Unpack Color", 1)
String GetId() const
{ return "UnpackColor"; }
UnpackColorToVectorShaderBlock(ShaderBlock *block = 0)
{
type = TypeUnpackColorToVector;
input[0] = block;
}
};
struct PackVectorToColorShaderBlock : public ShaderBlock
{
__SpecializeBlock("Pack Vector", 1)
String GetId() const
{ return "PackVector"; }
PackVectorToColorShaderBlock(ShaderBlock *block = 0)
{
type = TypePackVectorToColor;
input[0] = block;
}
};
struct MixOperatorShaderBlock : public ShaderBlock
{
__SpecializeBlock("Mix", 3)
String GetId() const
{ return "Mix"; }
MixOperatorShaderBlock(ShaderBlock *a = 0, ShaderBlock *b = 0, ShaderBlock *k = 0)
{
type = TypeMix;
input[0] = a; input[1] = b; input[2] = k;
}
};
struct AddOperatorShaderBlock : public ShaderBlock
{
__SpecializeBlock("Add", 2)
String GetId() const
{ return "Add"; }
AddOperatorShaderBlock(ShaderBlock *a = 0, ShaderBlock *b = 0)
{
type = TypeAdd;
input[0] = a; input[1] = b;
}
};
struct MulOperatorShaderBlock : public ShaderBlock
{
__SpecializeBlock("Mul", 2)
String GetId() const
{ return "Mul"; }
MulOperatorShaderBlock(ShaderBlock *a = 0, ShaderBlock *b = 0)
{
type = TypeMul;
input[0] = a; input[1] = b;
}
};
struct SubOperatorShaderBlock : public ShaderBlock
{
__SpecializeBlock("Sub", 2)
String GetId() const
{ return "Sub"; }
SubOperatorShaderBlock(ShaderBlock *a = 0, ShaderBlock *b = 0)
{
type = TypeSub;
input[0] = a; input[1] = b;
}
};
struct DivOperatorShaderBlock : public ShaderBlock
{
__SpecializeBlock("Div", 2)
String GetId() const
{ return "Div"; }
DivOperatorShaderBlock(ShaderBlock *a = 0, ShaderBlock *b = 0)
{
type = TypeDiv;
input[0] = a; input[1] = b;
}
};
struct DotOperatorShaderBlock : public ShaderBlock
{
__SpecializeBlock("Dot", 2)
String GetId() const
{ return "Dot"; }
DotOperatorShaderBlock(ShaderBlock *a = 0, ShaderBlock *b = 0)
{
type = TypeDot;
input[0] = a; input[1] = b;
}
};
struct CrossOperatorShaderBlock : public ShaderBlock
{
__SpecializeBlock("Cross", 2)
String GetId() const
{ return "Cross"; }
CrossOperatorShaderBlock(ShaderBlock *a = 0, ShaderBlock *b = 0)
{
type = TypeCross;
input[0] = a; input[1] = b;
}
};
struct NormalizeOperatorShaderBlock : public ShaderBlock
{
__SpecializeBlock("Normalize", 1)
String GetId() const
{ return "Norm"; }
NormalizeOperatorShaderBlock(ShaderBlock *a = 0)
{
type = TypeNormalize;
input[0] = a;
}
};
struct ClampShaderBlock : public ShaderBlock
{
__SpecializeBlock("Clamp", 3)
String GetId() const
{ return "Clamp"; }
ClampShaderBlock(ShaderBlock *v = 0, ShaderBlock *a = 0, ShaderBlock *b = 0)
{
type = TypeClamp;
input[0] = v; input[1] = a; input[2] = b;
}
};
struct SwizzleShaderBlock : public ShaderBlock
{
enum Swizzle
{
SwizzleNone = 0,
SwizzleX,
SwizzleY,
SwizzleZ,
SwizzleW
};
__SpecializeBlock("Swizzle", 1)
String GetId() const
{ return String::Format("Swizzle%d%d%d%d", swizzle[0], swizzle[1], swizzle[2], swizzle[3]); }
Swizzle swizzle[4];
SwizzleShaderBlock(ShaderBlock *block = 0, Swizzle x = SwizzleNone, Swizzle y = SwizzleNone, Swizzle z = SwizzleNone, Swizzle w = SwizzleNone)
{
type = TypeSwizzle;
swizzle[0] = x; swizzle[1] = y; swizzle[2] = z; swizzle[3] = w;
input[0] = block;
}
};
struct BuildShaderBlock : public ShaderBlock
{
enum Build
{
BuildZero = 0,
BuildOne,
BuildX,
BuildY,
BuildZ,
BuildW
};
__SpecializeBlock("Build", 4)
Build build[4];
String GetId() const
{ return String::Format("Build%d%d%d%d", build[0], build[1], build[2], build[3]); }
BuildShaderBlock(ShaderBlock *a = 0, Build x = BuildX, ShaderBlock *b = 0, Build y = BuildY, ShaderBlock *c = 0, Build z = BuildZ, ShaderBlock *d = 0, Build w = BuildW)
{
type = TypeBuild;
build[0] = x; build[1] = y; build[2] = z; build[3] = w;
input[0] = a; input[1] = b; input[2] = c; input[3] = d;
}
};
struct GeometryUVShaderBlock : public ShaderBlock
{
__SpecializeBlockNoInput("UV Stream")
int channel;
String GetId() const
{ return String::Format("UV%d", channel); }
GeometryUVShaderBlock(int uv_channel = 0)
{
type = TypeGeometryUV;
channel = uv_channel;
}
};
struct GeometryVertexShaderBlock : public ShaderBlock
{
__SpecializeBlockNoInput("Vertex Stream")
String GetId() const
{ return String("Vertex"); }
GeometryVertexShaderBlock()
{ type = TypeGeometryVertex; }
};
struct GeometryNormalShaderBlock : public ShaderBlock
{
__SpecializeBlockNoInput("Normal Stream")
bool smooth;
String GetId() const
{ return String(smooth ? "NormalSmooth" : "Normal"); }
GeometryNormalShaderBlock()
{
type = TypeGeometryNormal;
smooth = true;
}
};
struct GeometrySkinningShaderBlock : public ShaderBlock
{
__SpecializeBlockNoInput("Skinning Matrix")
String GetId() const
{ return String("SkinMtx"); }
GeometrySkinningShaderBlock()
{ type = TypeGeometrySkinning; }
};
struct GeometryVertexColorShaderBlock : public ShaderBlock
{
__SpecializeBlockNoInput("Vertex Color Stream")
String GetId() const
{ return String("VertexColor"); }
GeometryVertexColorShaderBlock()
{ type = TypeGeometryVertexColor; }
};
struct GeometryTangentFrameShaderBlock : public ShaderBlock
{
__SpecializeBlockNoInput("Tangent Frame")
String GetId() const
{ return String("TangentMtx"); }
GeometryTangentFrameShaderBlock()
{ type = TypeGeometryTangentFrame; }
};
struct RenderBufferShaderBlock : public ShaderBlock
{
__SpecializeBlockNoInput("Render Buffer")
enum RenderBuffer
{
Depth = 0
};
RenderBuffer buffer;
String GetId() const
{ return String("RenderBuffer"); }
RenderBufferShaderBlock(RenderBuffer _buffer = Depth)
{
type = TypeRenderBuffer;
buffer = _buffer;
}
};
struct TextureShaderBlock : public ShaderBlock
{
__SpecializeBlockNoInput("Texture")
enum TextureType
{
Texture2D = 0,
Texture3D,
TextureCube
};
TextureType texture_type;
String texture;
String GetId() const;
TextureShaderBlock(const char *name = 0)
{
type = TypeTexture;
texture = name;
texture_type = Texture2D;
}
};
struct TextureSamplerShaderBlock : public ShaderBlock
{
__SpecializeBlock("Texture Sampler", 2)
enum SamplerType
{
Sampler2D = 0,
Sampler3D,
SamplerCube
};
SamplerType sampler_type;
String GetId() const
{ return String::Format("TexSampler%d", (int)sampler_type); }
TextureSamplerShaderBlock(ShaderBlock *texture = 0, ShaderBlock *uv = 0)
{
type = TypeTextureSampler;
sampler_type = Sampler2D;
input[0] = texture;
input[1] = uv;
}
};
struct MaterialParamShaderBlock : public ShaderBlock
{
__SpecializeBlockNoInput("Material Parameter")
enum MaterialParam
{
MaterialDiffuse = 0,
MaterialSpecular,
MaterialSelf,
MaterialAmbient,
MaterialGlossiness,
MaterialOpacity,
MaterialReflection
};
MaterialParam param;
String GetId() const;
MaterialParamShaderBlock(MaterialParam p = MaterialDiffuse)
{
type = TypeMaterialParam;
param = p;
}
};
struct MaterialTextureShaderBlock : public ShaderBlock
{
__SpecializeBlockNoInput("Material Texture")
enum TextureType
{
Texture2D = 0,
Texture3D,
TextureCube
};
TextureType texture_type;
int slot;
String GetId() const;
MaterialTextureShaderBlock(int n = 0)
{
type = TypeMaterialTexture;
texture_type = Texture2D;
slot = n;
}
};
struct ColorShaderBlock : public ShaderBlock
{
__SpecializeBlockNoInput("Color")
Color color;
String GetId() const
{ return "Color"; }
ColorShaderBlock(float r = 1, float g = 1, float b = 1, float a = 1)
{
type = TypeColor;
color.Set(r, g, b, a);
}
};
struct ConstantShaderBlock : public ShaderBlock
{
__SpecializeBlockNoInput("Constant")
float constant[4];
ShaderInput::DataType constant_type;
String GetId() const;
ConstantShaderBlock()
{
type = TypeConstant; constant_type = ShaderInput::NoData;
constant[0] = constant[1] = constant[2] = constant[3] = 0;
}
ConstantShaderBlock(float v)
{
type = TypeConstant; constant_type = ShaderInput::Float;
constant[0] = v; constant[1] = constant[2] = constant[3] = 0;
}
ConstantShaderBlock(float u, float v)
{
type = TypeConstant; constant_type = ShaderInput::Vector2;
constant[0] = u; constant[1] = v; constant[2] = constant[3] = 0;
}
ConstantShaderBlock(float x, float y, float z)
{
type = TypeConstant; constant_type = ShaderInput::Vector3;
constant[0] = x; constant[1] = y; constant[2] = z; constant[3] = 0;
}
ConstantShaderBlock(float x, float y, float z, float w)
{
type = TypeConstant; constant_type = ShaderInput::Vector4;
constant[0] = x; constant[1] = y; constant[2] = z; constant[3] = w;
}
};
} // Core
} // GS
#endif // __NSHADER_BLOCK__

View File

@ -0,0 +1,225 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __NSHADERINPUT__
#define __NSHADERINPUT__
#include "math/vector.h"
#include "nstring/nstring.h"
namespace GS {
namespace Core {
/// Shader input.
struct ShaderInput
{
enum Type
{
None = 0,
Uniform, ///< User programmed shader variable.
Attribute ///< User bound shader input stream.
};
enum Semantic // do not reorder!
{
// Data attributes.
Position = 0,
Normal,
UV0,
UV1,
UV2,
VertexColor,
Tangent,
Bitangent,
BoneIndex,
BoneWeight,
// Data uniforms.
Constant,
Texture2D,
Texture3D,
TextureCube,
Clock,
TimeOfDay, ///< Environment time of day (eg. skybox)
ViewVector,
ViewPosition,
Viewport,
ZNear,
ZFar,
ZoomFactor,
FxScale,
InverseBufferSize,
InverseViewportSize,
DisplayBufferRatio,
ViewportRatio,
ViewDepthOffset,
AmbientColor,
FogColor,
FogNear,
FogFar,
FogInverseRange,
DepthBuffer,
FrameBuffer,
GBuffer0,
GBuffer1,
GBuffer2,
GBuffer3,
NoiseMap,
NormalMatrix,
NormalViewMatrix,
ModelMatrix,
ViewMatrix,
ProjectionMatrix,
ModelViewMatrix,
ModelViewProjectionMatrix,
InverseViewProjectionMatrix,
InverseViewProjectionMatrixAtOrigin, // precision hack
PreviousModelViewMatrix,
PreviousModelViewProjectionMatrix,
MaterialOpacity,
MaterialDiffuse,
MaterialSpecular,
MaterialSelf,
MaterialAmbient,
MaterialGlossiness,
MaterialReflection,
MaterialAlphaThreshold,
MaterialDepthBias,
MaterialTexture0,
MaterialTexture1,
MaterialTexture2,
MaterialTexture3,
MaterialTexture4,
MaterialTexture5,
MaterialTexture6,
MaterialTexture7,
LightRange,
LightSpotEdge,
LightSpotCone,
LightShadowBias,
LightDiffuseColor,
LightSpecularColor,
LightShadowColor,
LightViewPosition,
LightViewDirection,
LightShadowMatrix0,
LightShadowMatrix1,
LightShadowMatrix2,
LightShadowMatrix3,
LightShadowMatrix4,
LightShadowMatrix5,
InverseShadowMapSize,
LightShadowMap0,
LightShadowMap1,
LightShadowMap2,
LightShadowMap3,
LightShadowMap4,
LightShadowMap5,
LightPSSMSliceDistance0,
LightPSSMSliceDistance1,
LightPSSMSliceDistance2,
LightPSSMSliceDistance3,
ViewToLightMatrix,
LightProjectionMap,
BoneMatrix,
PreviousBoneMatrix,
LastSemantic
};
enum Category
{
CategoryVertexStream = 0, // keep as category 0
CategoryConstant,
CategoryTexture,
CategorySkin,
CategoryRenderer,
CategoryMaterialOpacity,
CategoryMaterial,
CategoryTransform,
CategoryPreviousTransform,
CategoryLight,
CategoryLast
};
static const char *GetCategoryName(Category);
enum Precision
{
NoP = 0,
LowP,
MediumP,
HighP
};
enum DataType // do not reorder!
{
NoData = (1 << 0),
Int = (1 << 1),
Float = (1 << 2),
Vector2 = (1 << 3),
Vector3 = (1 << 4),
Vector4 = (1 << 5),
Matrix3 = (1 << 6),
Matrix4 = (1 << 7),
DataTexture2D = (1 << 8),
DataTexture3D = (1 << 9),
DataTextureCube = (1 << 10),
DataTextureShadow = (1 << 11)
};
struct SemanticDesc
{
const char *name;
Category category;
DataType data_type;
Precision precision;
};
static SemanticDesc semantic_desc[LastSemantic + 1];
bool ConsumesTextureUnit() const;
enum Scope
{
Vertex = (1 << 0),
Pixel = (1 << 1),
Geometry = (1 << 2)
};
String name;
int scope;
Type type;
Semantic semantic;
uint array_size;
String parm_t;
GS::Vector4 parm_v; ///< 16B vector
ShaderInput::DataType data_type;
ShaderInput();
};
} //Core
} // GS
#endif // __NSHADERINPUT__

View File

@ -0,0 +1,36 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
------------------------------------------------------------------------------*/
#ifndef __NISL_TO_GLSL__
#define __NISL_TO_GLSL__
#include "core/shader_input.h"
namespace GS {
namespace Core {
struct Shader;
namespace ISLtoGLSL {
enum GLSLVariant
{
OGL, ///< OpenGL 2.1 (GLSL 100)
OGL32, ///< OpenGL 3.2 (GLSL 130)
EGL20 ///< EGL 2.0
};
/// Get a type name.
bool GetType(ShaderInput::DataType, String &);
/// Convert an ISL shader to a GLSL shader.
bool Translate(const Shader &, String &glsl_vertex, String &glsl_fragment, GLSLVariant = OGL);
} // ISLtoGLSL
} // Core
} // GS
#endif // __NISL_TO_GLSL__

View File

@ -0,0 +1,31 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
------------------------------------------------------------------------------*/
#ifndef __NISL_TO_HLSL__
#define __NISL_TO_HLSL__
#include "core/shader_input.h"
namespace GS {
namespace Core {
struct Shader;
namespace ISLtoHLSL {
String GetCategoryCBufferName(ShaderInput::Category);
/// Get a type name.
bool GetType(ShaderInput::DataType, String &);
/// Translate an ISL shader to a HLSL shader.
bool Translate(const Shader &, String &hlsl_vertex, String &hlsl_fragment);
} // ISLtoHLSL
} // Core
} // GS
#endif // __NISL_TO_HLSL__

View File

@ -0,0 +1,74 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __NSHADER_TREE__
#define __NSHADER_TREE__
#include "math/vector.h"
#include "container/nlist.h"
#include "memory/nshared_ptr.h"
#include "nstring/nstring.h"
namespace GS {
namespace Core {
struct ShaderBlock;
/*
@short Shader tree.
@author Emmanuel Julien (ejulien@gsworks.fr)
*/
class ShaderTree : public SharedObject
{
protected:
/// Extract block from the map.
void GatherBlockList(List <ShaderBlock *> &block_list, ShaderBlock *root = 0);
public:
enum ShaderSinkType
{
SinkVertex = 0,
SinkNormal,
SinkDiffuse,
SinkModulate,
SinkSpecular,
SinkGlossiness,
SinkConstant,
SinkOpacity,
SinkReflection,
SinkInvalid
};
String name;
Vector2 pos;
ShaderBlock *sink[SinkInvalid];
/// Return a sink compatibility.
int GetSinkCompatibility(ShaderSinkType) const;
/// Free map and all blocks.
void Free();
bool FromMetaTag(NML::Tag &);
NML::Tag *AsMetaTag() const;
ShaderTree();
~ShaderTree();
};
typedef SharedPtr <ShaderTree> sShaderTree;
} // Core
} // GS
#endif // __NSHADER_TREE__

View File

@ -0,0 +1,158 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __SHADER_TREE_COMPILER__
#define __SHADER_TREE_COMPILER__
#include "core/shader.h"
#include "core/shader_block.h"
namespace GS {
namespace Core {
/// Compiled shader block.
struct CShaderBlock
{
String variable;
const ShaderBlock *block;
ShaderInput::DataType output;
CShaderBlock(const ShaderBlock *render_block) : block(render_block), output(ShaderInput::NoData)
{
block = render_block;
output = ShaderInput::NoData;
}
};
/*!
@short Shader tree compiler.
Compile a shader tree to a shader.
@author Emmanuel Julien (ejulien@gsworks.fr)
*/
class ShaderTreeCompiler
{
/*!
@name Specialized interface.
@{
*/
protected:
virtual CShaderBlock *CompileConstantShaderBlock(const ConstantShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel) = 0;
virtual CShaderBlock *CompileColorShaderBlock(const ColorShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel) = 0;
virtual CShaderBlock *CompileMaterialParamShaderBlock(const MaterialParamShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel) = 0;
virtual CShaderBlock *CompileMaterialTextureShaderBlock(const MaterialTextureShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel) = 0;
virtual CShaderBlock *CompileGeometryVertexShaderBlock(const GeometryVertexShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel) = 0;
virtual CShaderBlock *CompileGeometryUVShaderBlock(const GeometryUVShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel) = 0;
virtual CShaderBlock *CompileGeometryNormalShaderBlock(const GeometryNormalShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel) = 0;
virtual CShaderBlock *CompileGeometrySkinningShaderBlock(const GeometrySkinningShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel) = 0;
virtual CShaderBlock *CompileGeometryVertexColorShaderBlock(const GeometryVertexColorShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel) = 0;
virtual CShaderBlock *CompileGeometryTangentFrameShaderBlock(const GeometryTangentFrameShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel) = 0;
virtual CShaderBlock *CompileRenderBufferShaderBlock(const RenderBufferShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel) = 0;
virtual CShaderBlock *CompileTextureShaderBlock(const TextureShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel) = 0;
virtual CShaderBlock *CompileTextureSamplerShaderBlock(const TextureSamplerShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel) = 0;
virtual CShaderBlock *CompileMixShaderBlock(const MixOperatorShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel) = 0;
virtual CShaderBlock *CompileAddShaderBlock(const AddOperatorShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel) = 0;
virtual CShaderBlock *CompileSubShaderBlock(const SubOperatorShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel) = 0;
virtual CShaderBlock *CompileMulShaderBlock(const MulOperatorShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel) = 0;
virtual CShaderBlock *CompileDivShaderBlock(const DivOperatorShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel) = 0;
virtual CShaderBlock *CompileDotShaderBlock(const DotOperatorShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel) = 0;
virtual CShaderBlock *CompileCrossShaderBlock(const CrossOperatorShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel) = 0;
virtual CShaderBlock *CompileClampShaderBlock(const ClampShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel) = 0;
virtual CShaderBlock *CompileNormalizeBlock(const NormalizeOperatorShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel) = 0;
virtual CShaderBlock *CompileSwizzleShaderBlock(const SwizzleShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel) = 0;
virtual CShaderBlock *CompileBuildShaderBlock(const BuildShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel) = 0;
virtual CShaderBlock *CompileCosinusShaderBlock(const CosinusShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel) = 0;
virtual CShaderBlock *CompileSinusShaderBlock(const SinusShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel) = 0;
virtual CShaderBlock *CompilePowShaderBlock(const PowShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel) = 0;
virtual CShaderBlock *CompileAbsShaderBlock(const AbsShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel) = 0;
virtual CShaderBlock *CompileUnpackColorToVector(const UnpackColorToVectorShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel) = 0;
virtual CShaderBlock *CompilePackVectorToColor(const PackVectorToColorShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel) = 0;
virtual CShaderBlock *CompileClockShaderBlock(const ClockShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel) = 0;
virtual CShaderBlock *CompileScreenUVShaderBlock(const ScreenUVShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel) = 0;
virtual CShaderBlock *CompileViewVectorShaderBlock(const ViewVectorShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel) = 0;
virtual CShaderBlock *CompileViewportShaderBlock(const ViewportShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel) = 0;
virtual CShaderBlock *CompileNormalViewMatrixShaderBlock(const NormalViewMatrixShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel) = 0;
virtual CShaderBlock *CompileNormalMatrixShaderBlock(const NormalMatrixShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel) = 0;
virtual CShaderBlock *CompileModelViewMatrixShaderBlock(const ModelViewMatrixShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel) = 0;
virtual CShaderBlock *CompileModelMatrixShaderBlock(const ModelMatrixShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel) = 0;
/// @}
protected:
String id;
uint variable_count,
texture_count;
Shader *shader;
AutoList <ShaderBlock *> temporary_block_list;
AutoList <CShaderBlock *> compiled_tree_block;
bool GetNewVariable(String &constant, const char *prefix = 0);
CShaderBlock *GetNewCompiledBlock(const ShaderBlock *);
String vertex_declaration,
vertex_source,
pixel_declaration,
pixel_source;
public:
/// Get current shader id.
const String &GetId() const { return id; }
/// Restart compiler. Derived implementations should call the base class first.
void RestartCompiler(Shader *);
/// Compile a shader block.
CShaderBlock *CompileShaderBlock(const ShaderBlock *, const char *prefix = 0, ShaderInput::Scope = ShaderInput::Pixel);
/// Compile a temporary block. Compiler takes ownership of the block.
CShaderBlock *CompileTemporary(ShaderBlock *, const char *prefix = 0, ShaderInput::Scope = ShaderInput::Pixel);
/// Add a custom prefix to the shader name.
void AddPrefix(const char *);
/// Add code to the vertex shader declaration.
void AddVertexDeclaration(const char *d) { vertex_declaration += d; }
/// Add code to the vertex shader.
void AddVertexShader(const char *d) { vertex_source += d; }
/// Add code to the fragment shader declaration.
void AddPixelDeclaration(const char *d) { pixel_declaration += d; }
/// Add code to the fragment shader.
void AddPixelShader(const char *d) { pixel_source += d; }
/// Get vertex program.
const String &GetVertexSource() const { return vertex_source; }
/// Get fragment program.
const String &GetPixelSource() const { return pixel_source; }
/// Complete a compilation, retrieve the shader.
virtual Shader *Finish() = 0;
/// Free all compiler stats.
void Free();
ShaderTreeCompiler();
virtual ~ShaderTreeCompiler();
};
} //Core
} // GS
#endif // __SHADER_TREE_COMPILER__

View File

@ -0,0 +1,83 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __ISL_SHADER_TREE_COMPILER__
#define __ISL_SHADER_TREE_COMPILER__
#include "core/shader_tree_compiler.h"
namespace GS {
namespace Core {
/*!
@short ISL Shader tree compiler.
@author Emmanuel Julien (ejulien@nworks.fr)
*/
class ISLShaderTreeCompiler : public ShaderTreeCompiler
{
protected:
virtual CShaderBlock *CompileConstantShaderBlock(const ConstantShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel);
virtual CShaderBlock *CompileColorShaderBlock(const ColorShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel);
virtual CShaderBlock *CompileMaterialParamShaderBlock(const MaterialParamShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel);
virtual CShaderBlock *CompileMaterialTextureShaderBlock(const MaterialTextureShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel);
virtual CShaderBlock *CompileGeometryVertexShaderBlock(const GeometryVertexShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel);
virtual CShaderBlock *CompileGeometryUVShaderBlock(const GeometryUVShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel);
virtual CShaderBlock *CompileGeometryNormalShaderBlock(const GeometryNormalShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel);
virtual CShaderBlock *CompileGeometrySkinningShaderBlock(const GeometrySkinningShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel);
virtual CShaderBlock *CompileGeometryVertexColorShaderBlock(const GeometryVertexColorShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel);
virtual CShaderBlock *CompileGeometryTangentFrameShaderBlock(const GeometryTangentFrameShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel);
virtual CShaderBlock *CompileRenderBufferShaderBlock(const RenderBufferShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel);
virtual CShaderBlock *CompileTextureShaderBlock(const TextureShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel);
virtual CShaderBlock *CompileTextureSamplerShaderBlock(const TextureSamplerShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel);
virtual CShaderBlock *CompileMixShaderBlock(const MixOperatorShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel);
virtual CShaderBlock *CompileAddShaderBlock(const AddOperatorShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel);
virtual CShaderBlock *CompileSubShaderBlock(const SubOperatorShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel);
virtual CShaderBlock *CompileMulShaderBlock(const MulOperatorShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel);
virtual CShaderBlock *CompileDivShaderBlock(const DivOperatorShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel);
virtual CShaderBlock *CompileDotShaderBlock(const DotOperatorShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel);
virtual CShaderBlock *CompileCrossShaderBlock(const CrossOperatorShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel);
virtual CShaderBlock *CompileClampShaderBlock(const ClampShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel);
virtual CShaderBlock *CompileNormalizeBlock(const NormalizeOperatorShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel);
virtual CShaderBlock *CompileSwizzleShaderBlock(const SwizzleShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel);
virtual CShaderBlock *CompileBuildShaderBlock(const BuildShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel);
virtual CShaderBlock *CompileCosinusShaderBlock(const CosinusShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel);
virtual CShaderBlock *CompileSinusShaderBlock(const SinusShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel);
virtual CShaderBlock *CompilePowShaderBlock(const PowShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel);
virtual CShaderBlock *CompileAbsShaderBlock(const AbsShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel);
virtual CShaderBlock *CompileUnpackColorToVector(const UnpackColorToVectorShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel);
virtual CShaderBlock *CompilePackVectorToColor(const PackVectorToColorShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel);
virtual CShaderBlock *CompileClockShaderBlock(const ClockShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel);
virtual CShaderBlock *CompileScreenUVShaderBlock(const ScreenUVShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel);
virtual CShaderBlock *CompileViewVectorShaderBlock(const ViewVectorShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel);
virtual CShaderBlock *CompileViewportShaderBlock(const ViewportShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel);
virtual CShaderBlock *CompileNormalViewMatrixShaderBlock(const NormalViewMatrixShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel);
virtual CShaderBlock *CompileNormalMatrixShaderBlock(const NormalMatrixShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel);
virtual CShaderBlock *CompileModelViewMatrixShaderBlock(const ModelViewMatrixShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel);
virtual CShaderBlock *CompileModelMatrixShaderBlock(const ModelMatrixShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel);
public:
bool GetTypeDeclaration(ShaderInput::DataType, String &declaration);
virtual Shader *Finish();
};
} // Core
} // GS
#endif // __ISL_SHADER_TREE_COMPILER__

View File

@ -0,0 +1,109 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __TINYC_SHADER_TREE_COMPILER__
#define __TINYC_SHADER_TREE_COMPILER__
#include "core/shader_tree_compiler.h"
namespace GS {
namespace Core {
struct ResourceFactory;
struct Material;
/*!
@short TinyC Shader tree compiler.
@author Scorpheus (Scorpheus@hotmail.com)
*/
class TinyCShaderTreeCompiler : public ShaderTreeCompiler
{
/*!
@name Specialized interface.
@{
*/
protected:
virtual CShaderBlock *CompileConstantShaderBlock(const ConstantShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel);
virtual CShaderBlock *CompileColorShaderBlock(const ColorShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel);
virtual CShaderBlock *CompileMaterialParamShaderBlock(const MaterialParamShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel);
virtual CShaderBlock *CompileMaterialTextureShaderBlock(const MaterialTextureShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel);
virtual CShaderBlock *CompileGeometryVertexShaderBlock(const GeometryVertexShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel);
virtual CShaderBlock *CompileGeometryUVShaderBlock(const GeometryUVShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel);
virtual CShaderBlock *CompileGeometryNormalShaderBlock(const GeometryNormalShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel);
virtual CShaderBlock *CompileGeometrySkinningShaderBlock(const GeometrySkinningShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel);
virtual CShaderBlock *CompileGeometryVertexColorShaderBlock(const GeometryVertexColorShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel);
virtual CShaderBlock *CompileGeometryTangentFrameShaderBlock(const GeometryTangentFrameShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel);
virtual CShaderBlock *CompileRenderBufferShaderBlock(const RenderBufferShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel);
virtual CShaderBlock *CompileTextureShaderBlock(const TextureShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel);
virtual CShaderBlock *CompileTextureSamplerShaderBlock(const TextureSamplerShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel);
virtual CShaderBlock *CompileMixShaderBlock(const MixOperatorShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel);
virtual CShaderBlock *CompileAddShaderBlock(const AddOperatorShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel);
virtual CShaderBlock *CompileSubShaderBlock(const SubOperatorShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel);
virtual CShaderBlock *CompileMulShaderBlock(const MulOperatorShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel);
virtual CShaderBlock *CompileDivShaderBlock(const DivOperatorShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel);
virtual CShaderBlock *CompileDotShaderBlock(const DotOperatorShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel);
virtual CShaderBlock *CompileCrossShaderBlock(const CrossOperatorShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel);
virtual CShaderBlock *CompileClampShaderBlock(const ClampShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel);
virtual CShaderBlock *CompileNormalizeBlock(const NormalizeOperatorShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel);
virtual CShaderBlock *CompileSwizzleShaderBlock(const SwizzleShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel);
virtual CShaderBlock *CompileBuildShaderBlock(const BuildShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel);
virtual CShaderBlock *CompileCosinusShaderBlock(const CosinusShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel);
virtual CShaderBlock *CompileSinusShaderBlock(const SinusShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel);
virtual CShaderBlock *CompilePowShaderBlock(const PowShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel);
virtual CShaderBlock *CompileAbsShaderBlock(const AbsShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel);
virtual CShaderBlock *CompileUnpackColorToVector(const UnpackColorToVectorShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel);
virtual CShaderBlock *CompilePackVectorToColor(const PackVectorToColorShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel);
virtual CShaderBlock *CompileClockShaderBlock(const ClockShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel);
virtual CShaderBlock *CompileScreenUVShaderBlock(const ScreenUVShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel);
virtual CShaderBlock *CompileViewVectorShaderBlock(const ViewVectorShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel);
virtual CShaderBlock *CompileViewportShaderBlock(const ViewportShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel);
virtual CShaderBlock *CompileNormalViewMatrixShaderBlock(const NormalViewMatrixShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel);
virtual CShaderBlock *CompileNormalMatrixShaderBlock(const NormalMatrixShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel);
virtual CShaderBlock *CompileModelViewMatrixShaderBlock(const ModelViewMatrixShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel);
virtual CShaderBlock *CompileModelMatrixShaderBlock(const ModelMatrixShaderBlock *, ShaderInput::Scope = ShaderInput::Pixel);
/// @}
public:
ResourceFactory &graphic_factory;
/// Get code to the fragment shader declaration.
String GetFragmentDeclaration() { return pixel_declaration; }
/// Get code to the fragment shader.
String GetFragmentShader() { return pixel_source; }
/// Declare a varying.
virtual bool DeclareVarying(const char *name, ShaderInput::DataType data_type) {return true;};
/// Helper.
bool GetTypeDeclaration(ShaderInput::DataType, String &declaration);
void SetShaderInputs( const Material &m);
/// Complete a compilation, retrieve the shader.
virtual Shader *Finish();
TinyCShaderTreeCompiler(ResourceFactory &gf) : graphic_factory(gf) {}
};
} // Core
} // GS
#endif // __TINYC_SHADER_TREE_COMPILER__

View File

@ -0,0 +1,23 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __SHADERTREECONVERTSTATICTEXTUREBLOCKTODYNAMIC__
#define __SHADERTREECONVERTSTATICTEXTUREBLOCKTODYNAMIC__
namespace GS {
namespace Core {
struct Material;
class ShaderTree;
// Convert all static shader texture blocks to dynamic ones.
void ConvertStaticToDynamicTextureBlocks(ShaderTree &, const Material &);
} // Core
} // GS
#endif // __SHADERTREECONVERTSTATICTEXTUREBLOCKTODYNAMIC__

View File

@ -0,0 +1,23 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __NSHADERTREETOSHADER__
#define __NSHADERTREETOSHADER__
namespace GS {
namespace Core {
struct Shader;
class ShaderTree;
// Convert a shader tree to an ISL shader.
bool ConvertShaderTreeToShader(const ShaderTree &, Shader &);
} // Core
} // GS
#endif // __NSHADERTREETOSHADER__

View File

@ -0,0 +1,45 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __SIMPLE_LIST_RENDERABLE__
#define __SIMPLE_LIST_RENDERABLE__
#include "core/renderable.h"
#include "container/narray_list.h"
namespace GS {
namespace Core {
/*
@short Simple list renderable.
@author Emmanuel Julien (ejulien@nworks.fr)
*/
class SimpleCullingSystem : public Renderable
{
protected:
ArrayList <Renderable *> renderable_list;
public:
/// Add a renderable to the provider.
void AddRenderable(Renderable *);
/// Delete a renderable from the provider.
void DeleteRenderable(Renderable *);
/// Compute renderable min-max.
virtual void ComputeRenderableMinMax(MinMax &);
/// Get primitive list.
virtual uint GetRenderablePrimitiveList(const Camera &view, const Camera &default_view, Stack <Render::Primitive *> &, Context = Context_Default, bool cull = true);
};
} // Core
} // GS
#endif // __SIMPLE_LIST_RENDERABLE__

View File

@ -0,0 +1,36 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __NSKIN__
#define __NSKIN__
#include "math/matrix4.h"
#include "geometry/bounding_box.h"
#include "container/narray.h"
namespace GS {
struct OBB;
namespace Core {
class Item;
struct Skin
{
Array <Item *> bones;
Array <Matrix4> bones_mtx, previous_bones_mtx;
Array <MinMax> bones_minmax;
/// Compute bone skin minmax.
bool ComputeBoneBoundingVolume(uint n, OBB &) const;
};
} // Core
} // GS
#endif // __NSKIN__

View File

@ -0,0 +1,42 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __NSOUND__
#define __NSOUND__
#include "core/mixer_data.h"
#include "nstring/nstring.h"
#include "memory/nauto_ptr.h"
#include "time/ntime.h"
namespace GS {
namespace Audio {
struct IMixer;
/*!
@short Mixer sound object.
@author Emmanuel Julien (ejulien@gsworks.fr)
*/
struct Sound : public SharedObject
{
NPLACEMENT_NEW(Sound)
IMixer &mixer;
String name;
AutoPtr <FutureData> mixer_data;
Sound(IMixer &m) : mixer(m) {}
~Sound();
};
} // Audio
} // GS
#endif // __NSOUND__

View File

@ -0,0 +1,24 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __NTANGENTFRAME__
#define __NTANGENTFRAME__
#include "math/vector.h"
namespace GS {
struct TangentFrame
{
Vector4 T, B;
};
} // GS
#endif // __NTANGENTFRAME__

View File

@ -0,0 +1,208 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __NTERRAIN__
#define __NTERRAIN__
#include "core/renderable.h"
#include "core/item.h"
#include "core/material.h"
#include "geometry/rect.h"
namespace GS {
namespace Core {
class Terrain;
class Geometry;
struct Patch
{
Terrain *terrain;
int u, v, w, h;
int decimation;
MinMax minmax;
iRect GetRect() const { return iRect(u, v, u + w, v + h); }
AutoPtr <Patch> children[4];
Patch() : terrain(0) {}
};
/*
@short Terrain.
@author Emmanuel Julien (ejulien@gsworks.fr)
*/
class Terrain : public Item, public Renderable
{
public:
struct Attrib
{
char nx, ny, nz;
};
struct Layer
{
bool enabled;
String diffuse, specular, normal, self;
float angle, tiling;
Layer()
{
enabled = true;
angle = 0.f;
tiling = 1.f;
}
};
protected:
float width, depth;
Array <float> heightmap;
Array <Attrib> attribmap;
int heightmap_w, heightmap_h;
float unit;
AutoPtr <Patch> root_node;
uint node_count;
void UpdatePatchMinMax(Patch *node) const;
/// Cull terrain primitive and push to the render queue.
void CullRenderablePrimitiveList(const Camera &view, const Camera &default_view, Stack <Render::Primitive *> &, Context, Patch *);
/// Helper function to create a geometry object for a given terrain patch.
Geometry *CreateNodeGeometry(const Patch *);
/// Build the terrain quad-tree for a specific terrain part.
Patch *BuildTerrainStaticQuadtree(int u, int v, int w, int h, int decimation, int depth);
/// Update a quadtree patch.
void UpdateQuadtreePatch(Patch *patch, iRect &update_rect);
/// Layer to tag.
NML::Tag *LayerAsMetaTag(int index);
public:
Layer layer[4];
/// Terrain render data.
struct RenderData
{
struct Layer
{
Render::sTexture diffuse, specular, normal, self;
};
Layer layer[4];
Render::sTexture blendmap;
Render::sMaterial material;
};
///
struct TraceResult
{
bool has_hit;
Vector4 w_i; ///< Intersection in world space.
Vector2 uv;
};
String material;
String heightmap_path,
blendmap_path,
shader_path;
AutoPtr <RenderData> render_data;
/// Compute the renderable bounding box.
virtual void ComputeRenderableMinMax(MinMax &);
/// Get the renderable primitive list.
virtual uint GetRenderablePrimitiveList(const Camera &view, const Camera &default_view, Stack <Render::Primitive *> &, Context = Context_Default, bool cull = true);
bool Raytrace(const Vector4 &s, const Vector4 &d, TraceResult &, float len = -1.f);
/*!
@short Apply several blur passes to the heightmap.
@note The normals are not blurred, so you might want to recompute
them when done.
*/
void ApplyBlur(int pass_count = 1);
/// Compute normals from the heightmap.
void ComputeNormals(int u = 0, int v = 0, int w = 0, int h = 0);
float GetWidth() const { return width; }
float GetDepth() const { return depth; }
/*!
@short Return the terrain normal for a given sample.
@note For performance critical code you might want to use the
attribute map directly.
*/
Vector4 GetNormalAt(int u, int v) const;
Attrib *GetAttributesMap() const { return attribmap; }
Attrib *GetAttributesMapAt(int u, int v) const;
float *GetHeightmap() const { return heightmap; }
int GetHeightmapWidth() const { return heightmap_w; }
int GetHeightmapHeight() const { return heightmap_h; }
int GetHeightmapPitch() const { return heightmap_w + 1; }
float GetUnit() const { return unit; }
bool LocalToTexture(const Vector4 &, float w, float h, float &u, float &v) const;
bool LocalToHeightmap(const Vector4 &p, float &u, float &v) const;
/// Sample height in heightmap space.
float SampleHeight(float u, float v) const;
/// Sample height in local space.
float SampleHeight(const Vector4 &) const;
/// Update a terrain quadtree zone.
void UpdateQuadtree(int u = 0, int v = 0, int w = 0, int h = 0);
Patch *BuildQuadtree();
void RenderSetup(ResourceFactories * = 0);
/// Set heightmap from file.
bool FromPicture(const char *, int blur_pass_count = 0);
/*!
@name Height map I/O.
@{
*/
bool LoadHeightmap(const char *);
bool SaveHeightmap(const char *);
/// @}
/*!
@short Allocate terrain.
@note This function does not allocate terrain patches.
*/
bool Allocate(uint w_res, uint h_res, float unit);
void Free();
bool FromMetaTag(NML::Tag &);
NML::Tag *AsMetaTag();
Terrain();
virtual ~Terrain();
};
} // Core
} // GS
#endif // __NTERRAIN__

View File

@ -0,0 +1,26 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __TERRAIN_SHADER_GENERATOR__
#include "core/terrain.h"
namespace GS {
namespace Core {
struct Shader;
namespace TerrainShaderGenerator {
bool GenerateShader(Shader &shader, const char *t_blend, const Terrain::Layer layers[4]);
} // TerrainShaderGenerator
} // Core
} // GS
#endif // __TERRAIN_SHADER_GENERATOR__

View File

@ -0,0 +1,120 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __NTEXTUREPARM__
#define __NTEXTUREPARM__
#include "reflection/c_refl.h"
#include "reflection/nenum_string.h"
#include "nstring/nstring.h"
namespace GS {
class Picture;
namespace NML { class Tag; }
namespace Render {
struct Texture;
//
struct TextureParm
{
/// Get texture parameter file name from texture name.
static String GetParmFileName(const char *);
static Reflection::Property serializable[];
enum Filtering
{
FilterDefault = 0,
FilterNearest,
FilterBilinear,
FilterTrilinear,
FilterLast
};
static Reflection::Enum::Dict filtering_dict[];
enum Anisotropy
{
AnisotropyDefault = 0,
AnisotropyNone,
Anisotropy2x,
Anisotropy4x,
Anisotropy8x,
Anisotropy16x,
AnisotropyLast
};
static Reflection::Enum::Dict anisotropic_dict[];
enum Wrap
{
WrapDefault = 0,
WrapRepeat,
WrapClamp,
WrapLast
};
static Reflection::Enum::Dict wrap_dict[];
enum Swizzle
{
SwizzleRGBA = 0, // identity
SwizzleBGRA,
SwizzleARGB,
SwizzleABGR,
SwizzleXYZ, // identity
SwizzleXZY,
SwizzleYXZ,
SwizzleYZX,
SwizzleZXY,
SwizzleZYX,
SwizzleLast
};
static Reflection::Enum::Dict swizzle_dict[];
static const char *GetSwizzleFlags(Swizzle);
Wrap wrap_u, wrap_v;
Filtering filtering;
Anisotropy anisotropy;
float lod_bias;
Swizzle swizzle;
bool invert[4];
bool flip[2];
void Apply(Picture &) const;
void Apply(Texture &) const;
bool FromMetaTag(NML::Tag &);
NML::Tag *AsMetaTag() const;
TextureParm()
{
wrap_u = wrap_v = WrapDefault;
filtering = FilterDefault;
anisotropy = AnisotropyDefault;
lod_bias = 0.f;
swizzle = SwizzleRGBA;
for (uchar n = 0; n < 4; ++n)
invert[n] = false;
flip[0] = flip[1] = false;
}
};
} // Render
} // GS
#endif // __NTEXTUREPARM__

View File

@ -0,0 +1,25 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __TOOLMODE__
#define __TOOLMODE__
namespace GS {
enum ToolMode
{
NoTool = 0,
ToolEdit, ///< Tool edition mode, scripts are ignored.
ToolPreview, ///< Tool scene preview mode, full evaluations.
ToolProjectPreview ///< Tool project preview mode, full evaluations.
};
} // GS
#endif // __TOOLMODE__

View File

@ -0,0 +1,69 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __NGEOTRILIST__
#define __NGEOTRILIST__
#include "core/tangent_frame.h"
#include "color/color.h"
#include "container/nlist.h"
#include "container/narray.h"
namespace GS {
namespace Core {
/*!
@short Geometry triangle list.
@author Emmanuel Julien (ejulien@gsworks.fr)
*/
struct Trilist
{
struct Skin
{
float w[__PV_BONE_LIMIT__];
uchar bone_index[__PV_BONE_LIMIT__]; ///< Internal maximum of 256 bones per triangle list (indexed via the Trilist::bone_map array).
};
Array <Vector4> vtx;
Array <uint> idx; ///< Triangle index array.
Array <Skin> skin; ///< Vertex skinning information.
Array <ushort> bone; ///< Map referencing items in Item::bone (usually resolved from the Geometry::bone_id array at skin binding time).
Array <Vector4> nrm;
Array <TangentFrame> tangent;
Array <Vector2> uv[__UV_PER_GEOMETRY__];
Array <Color> rgb;
uint mat; ///< Material index.
/// Return the number of triangle in the list.
inline uint GetTriangleCount() const { return idx.GetCount() / 3; }
/*!
@short Optimize a given triangle list array.
The optimizer reorder the triangle list index in order to maximize cache hits.
You can specify the target architecture vertex cache size.
@note This function can be called several times if needed. The
modifications will however not be applied to the renderer
internals. For this you will need to explicitly recreate
the renderer's representation.
*/
static void Optimize(const List <Trilist *> &list, int vtx_cache_size = 16);
Trilist() : mat(0) {}
};
typedef Trilist * pTrilist;
} // Core
} // GS
#endif // __NGEOTRILIST__

View File

@ -0,0 +1,48 @@
/* -----------------------------------------------------------------------------
GSFramework
Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */
#ifndef __NTRIGGER__
#define __NTRIGGER__
#include "core/item.h"
namespace GS {
namespace Core {
/*!
@short Trigger class.
@author Emmanuel Julien (ejulien@gsworks.fr)
*/
struct Trigger : public Item
{
struct ItemInTrigger
{
bool inside; ///< Item is inside trigger.
Item *item;
ItemInTrigger(Item *i) : item(i), inside(true) {}
};
List <ItemInTrigger *> items_in_trigger;
void ReadyItemList();
void PurgeItemList();
virtual void MarkItem(Item *);
virtual void DropItem(Item *);
bool IsInside(const Vector4 &);
void RenderSetup(ResourceFactories * = 0) {}
~Trigger();
};
} // Core
} // GS
#endif // __NTRIGGER__