diff --git a/README.md b/README.md new file mode 100755 index 0000000..dd11fa3 --- /dev/null +++ b/README.md @@ -0,0 +1,35 @@ +ofxArtool5 +===================================== + +OpenFrameworks addon wrapping the functionalities of ArtoolKit 5. +At the moment it provides : + +- Marker based AR +- NFT based AR + +Licence +------- +Artoolkit is [LGPLv3](https://github.com/artoolkit/artoolkit5/blob/master/LICENSE.txt), so you can consider my code LGPLv3 too. +Copyright (c) 2015 EnricoViola +naus3a@gmail.com + +Installation +------------ +Copy to your openFrameworks/addons folder. + +Compatibility +------------ +openFrameworks 009.x + + +Known issues +------------ +For some reason (I think it's a libjpg issue), it seems like you cannot load .iset image set files (used for NFT) from OF; since I could not find documentation about the .iset format, I simply made my own custom.dat file providing the same functionality. + +You can use ofxArtool5::saveSurfaceSetData to make a your own custom file from an Artoolkit surface set. + +Version history +------------ + + + diff --git a/artool5NFTexample/Makefile b/artool5NFTexample/Makefile new file mode 100644 index 0000000..8d8e4c0 --- /dev/null +++ b/artool5NFTexample/Makefile @@ -0,0 +1,13 @@ +# Attempt to load a config.make file. +# If none is found, project defaults in config.project.make will be used. +ifneq ($(wildcard config.make),) + include config.make +endif + +# make sure the the OF_ROOT location is defined +ifndef OF_ROOT + OF_ROOT=$(realpath ../../..) +endif + +# call the project makefile! +include $(OF_ROOT)/libs/openFrameworksCompiled/project/makefileCommon/compile.project.mk diff --git a/artool5NFTexample/Project.xcconfig b/artool5NFTexample/Project.xcconfig new file mode 100644 index 0000000..e570b15 --- /dev/null +++ b/artool5NFTexample/Project.xcconfig @@ -0,0 +1,17 @@ +//THE PATH TO THE ROOT OF OUR OF PATH RELATIVE TO THIS PROJECT. +//THIS NEEDS TO BE DEFINED BEFORE CoreOF.xcconfig IS INCLUDED +OF_PATH = ../../.. + +//THIS HAS ALL THE HEADER AND LIBS FOR OF CORE +#include "../../../libs/openFrameworksCompiled/project/osx/CoreOF.xcconfig" + +//ICONS - NEW IN 0072 +ICON_NAME_DEBUG = icon-debug.icns +ICON_NAME_RELEASE = icon.icns +ICON_FILE_PATH = $(OF_PATH)/libs/openFrameworksCompiled/project/osx/ + +//IF YOU WANT AN APP TO HAVE A CUSTOM ICON - PUT THEM IN YOUR DATA FOLDER AND CHANGE ICON_FILE_PATH to: +//ICON_FILE_PATH = bin/data/ + +OTHER_LDFLAGS = $(OF_CORE_LIBS) $(OF_CORE_FRAMEWORKS) +HEADER_SEARCH_PATHS = $(OF_CORE_HEADERS) diff --git a/artool5NFTexample/addons.make b/artool5NFTexample/addons.make new file mode 100644 index 0000000..a90804d --- /dev/null +++ b/artool5NFTexample/addons.make @@ -0,0 +1,3 @@ +ofxArtool5 +ofxOpenCv +ofxXmlSettings diff --git a/artool5NFTexample/artool5example.xcodeproj/project.pbxproj b/artool5NFTexample/artool5example.xcodeproj/project.pbxproj new file mode 100644 index 0000000..cde2fc7 --- /dev/null +++ b/artool5NFTexample/artool5example.xcodeproj/project.pbxproj @@ -0,0 +1,2290 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 46; + objects = { + +/* Begin PBXBuildFile section */ + 1496CC601C1EC3E800EA3164 /* libAR.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1496CC561C1EC3E800EA3164 /* libAR.a */; }; + 1496CC611C1EC3E800EA3164 /* libAR2.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1496CC571C1EC3E800EA3164 /* libAR2.a */; }; + 1496CC621C1EC3E800EA3164 /* libARgsub_lite.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1496CC581C1EC3E800EA3164 /* libARgsub_lite.a */; }; + 1496CC631C1EC3E800EA3164 /* libARgsub.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1496CC591C1EC3E800EA3164 /* libARgsub.a */; }; + 1496CC641C1EC3E800EA3164 /* libARICP.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1496CC5A1C1EC3E800EA3164 /* libARICP.a */; }; + 1496CC651C1EC3E800EA3164 /* libARMulti.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1496CC5B1C1EC3E800EA3164 /* libARMulti.a */; }; + 1496CC661C1EC3E800EA3164 /* libARosg.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1496CC5C1C1EC3E800EA3164 /* libARosg.a */; }; + 1496CC671C1EC3E800EA3164 /* libARUtil.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1496CC5D1C1EC3E800EA3164 /* libARUtil.a */; }; + 1496CC681C1EC3E800EA3164 /* libARvideo.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1496CC5E1C1EC3E800EA3164 /* libARvideo.a */; }; + 1496CC691C1EC3E800EA3164 /* libKPM.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1496CC5F1C1EC3E800EA3164 /* libKPM.a */; }; + 14B90C9F1C2B20A8004D0E12 /* trackingSub.c in Sources */ = {isa = PBXBuildFile; fileRef = 14B90C9D1C2B20A8004D0E12 /* trackingSub.c */; }; + 14B90CA21C2B20B8004D0E12 /* ARMarkerNFT.c in Sources */ = {isa = PBXBuildFile; fileRef = 14B90CA01C2B20B8004D0E12 /* ARMarkerNFT.c */; }; + 14B90CA91C2B20D3004D0E12 /* ofxARTGenericTracker.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 14B90CA31C2B20D3004D0E12 /* ofxARTGenericTracker.cpp */; }; + 14B90CAA1C2B20D3004D0E12 /* ofxARTNftTracker.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 14B90CA51C2B20D3004D0E12 /* ofxARTNftTracker.cpp */; }; + 14B90CAB1C2B20D3004D0E12 /* ofxARTPattern.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 14B90CA71C2B20D3004D0E12 /* ofxARTPattern.cpp */; }; + 14D0A7BA1C47F54600BFDBAB /* libjpeg.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 14D0A7B91C47F54600BFDBAB /* libjpeg.a */; }; + 169D3C72FDE6C5590A1616F5 /* ofxCvFloatImage.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7B6A03390302D5A2C9F0E4AB /* ofxCvFloatImage.cpp */; }; + 1D5F3298C2FA073628012944 /* ofxCvContourFinder.cpp in Sources */ = {isa = PBXBuildFile; fileRef = C76DE5C29BDBD2CAA1DD0021 /* ofxCvContourFinder.cpp */; }; + 250A95BA26587BE85DB0A353 /* ofxCvColorImage.cpp in Sources */ = {isa = PBXBuildFile; fileRef = CE9C7160245B19131DAE6128 /* ofxCvColorImage.cpp */; }; + 5A4349E9754D6FA14C0F2A3A /* tinyxmlparser.cpp in Sources */ = {isa = PBXBuildFile; fileRef = FC5DA1C87211D4F6377DA719 /* tinyxmlparser.cpp */; }; + 63020F16C7E8DED980111241 /* ofxCvImage.cpp in Sources */ = {isa = PBXBuildFile; fileRef = C6151136D101F857DAE12722 /* ofxCvImage.cpp */; }; + 63B57AC5BF4EF088491E0317 /* ofxXmlSettings.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 50DF87D612C5AAE17AAFA6C0 /* ofxXmlSettings.cpp */; }; + 933A2227713C720CEFF80FD9 /* tinyxml.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 2B40EDA85BEB63E46785BC29 /* tinyxml.cpp */; }; + 9D44DC88EF9E7991B4A09951 /* tinyxmlerror.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 832BDC407620CDBA568B713D /* tinyxmlerror.cpp */; }; + D3301F6A0B43BB293ED97C1D /* ofxCvShortImage.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 8A4DD23693DFAB8EC05FAA5D /* ofxCvShortImage.cpp */; }; + E212C821D1064B92DD953A42 /* ofxCvHaarFinder.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 9A16CBF2E8CFE43AF54FE6F5 /* ofxCvHaarFinder.cpp */; }; + E4328149138ABC9F0047C5CB /* openFrameworksDebug.a in Frameworks */ = {isa = PBXBuildFile; fileRef = E4328148138ABC890047C5CB /* openFrameworksDebug.a */; }; + E4B69E200A3A1BDC003C02F2 /* main.cpp in Sources */ = {isa = PBXBuildFile; fileRef = E4B69E1D0A3A1BDC003C02F2 /* main.cpp */; }; + E4B69E210A3A1BDC003C02F2 /* ofApp.cpp in Sources */ = {isa = PBXBuildFile; fileRef = E4B69E1E0A3A1BDC003C02F2 /* ofApp.cpp */; }; + FB09C6B2A1DA0EA217240CB8 /* ofxCvGrayscaleImage.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 057122A817D12571F8C0C7A4 /* ofxCvGrayscaleImage.cpp */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + E4328147138ABC890047C5CB /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = E4328143138ABC890047C5CB /* openFrameworksLib.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = E4B27C1510CBEB8E00536013; + remoteInfo = openFrameworks; + }; + E4EEB9AB138B136A00A80321 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = E4328143138ABC890047C5CB /* openFrameworksLib.xcodeproj */; + proxyType = 1; + remoteGlobalIDString = E4B27C1410CBEB8E00536013; + remoteInfo = openFrameworks; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXCopyFilesBuildPhase section */ + E4C2427710CC5ABF004149E2 /* CopyFiles */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 10; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 00F3ABE019A17E4D55D8087D /* pnglibconf.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = pnglibconf.h; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/pnglibconf.h"; sourceTree = SOURCE_ROOT; }; + 011E372AEA4DFBC1A32C2851 /* all_indices.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = all_indices.h; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/flann/all_indices.h; sourceTree = SOURCE_ROOT; }; + 0173A3F435DECD5A4DDE0B8E /* logger.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = logger.h; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/flann/logger.h; sourceTree = SOURCE_ROOT; }; + 01DAE5C2E3E0A74207B2BE49 /* saving.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = saving.h; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/flann/saving.h; sourceTree = SOURCE_ROOT; }; + 01DCC0911400F9ACF5B65578 /* ofxXmlSettings.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = ofxXmlSettings.h; path = ../../../addons/ofxXmlSettings/src/ofxXmlSettings.h; sourceTree = SOURCE_ROOT; }; + 032B3A66B347FA0994B1F157 /* all_indices.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = all_indices.h; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/flann/all_indices.h"; sourceTree = SOURCE_ROOT; }; + 0339099A1F7B84040D88AD3C /* warp_shuffle.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = warp_shuffle.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/gpu/device/warp_shuffle.hpp; sourceTree = SOURCE_ROOT; }; + 04B8558FC9D04B0164C0A142 /* icpCore.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = icpCore.h; path = ../../../addons/ofxArtool5/libs/include/AR/icpCore.h; sourceTree = SOURCE_ROOT; }; + 057122A817D12571F8C0C7A4 /* ofxCvGrayscaleImage.cpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.cpp; fileEncoding = 30; name = ofxCvGrayscaleImage.cpp; path = ../../../addons/ofxOpenCv/src/ofxCvGrayscaleImage.cpp; sourceTree = SOURCE_ROOT; }; + 057D8E7580EA21E2254ADDDA /* camera.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = camera.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/stitching/detail/camera.hpp; sourceTree = SOURCE_ROOT; }; + 058528378576B4E04FB78842 /* linear_index.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = linear_index.h; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/flann/linear_index.h"; sourceTree = SOURCE_ROOT; }; + 05F316AD41D315CEB402E383 /* icpCalib.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = icpCalib.h; path = ../../../addons/ofxArtool5/libs/include/AR/icpCalib.h; sourceTree = SOURCE_ROOT; }; + 06BF0D5DFA7981166A713F58 /* datamov_utils.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = datamov_utils.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/gpu/device/datamov_utils.hpp"; sourceTree = SOURCE_ROOT; }; + 06E6D9F57013B015362D7F7F /* opengl_interop_deprecated.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = opengl_interop_deprecated.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/core/opengl_interop_deprecated.hpp"; sourceTree = SOURCE_ROOT; }; + 075597E52E99BDE94F8036B2 /* fast_marching_inl.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = fast_marching_inl.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/videostab/fast_marching_inl.hpp; sourceTree = SOURCE_ROOT; }; + 087522EA37A32B8D902CAB64 /* core_c.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = core_c.h; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/core/core_c.h; sourceTree = SOURCE_ROOT; }; + 096CB33CAD6C5A446E7026E9 /* dynamic_bitset.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = dynamic_bitset.h; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/flann/dynamic_bitset.h; sourceTree = SOURCE_ROOT; }; + 09C0538EF14B23442E6A8B25 /* defines.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = defines.h; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/flann/defines.h"; sourceTree = SOURCE_ROOT; }; + 0A17F47CA705D34314F9D9EE /* template.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = template.h; path = ../../../addons/ofxArtool5/libs/include/AR2/template.h; sourceTree = SOURCE_ROOT; }; + 0A7A79EFF93F6BB4C9415539 /* features2d.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = features2d.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/features2d/features2d.hpp"; sourceTree = SOURCE_ROOT; }; + 0ADD044A3066779F3673F1FE /* static_check.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = static_check.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/gpu/device/static_check.hpp; sourceTree = SOURCE_ROOT; }; + 0B87BF43E5302005FEF650B6 /* ios.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = ios.h; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/highgui/ios.h; sourceTree = SOURCE_ROOT; }; + 0BB5C619A159529C006E15A4 /* sampling.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = sampling.h; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/flann/sampling.h"; sourceTree = SOURCE_ROOT; }; + 0C452162C2CE29FB58F53E5C /* stream_accessor.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = stream_accessor.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/gpu/stream_accessor.hpp"; sourceTree = SOURCE_ROOT; }; + 0CEC1FE946DBDBAB82AF6FE3 /* global_motion.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = global_motion.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/videostab/global_motion.hpp; sourceTree = SOURCE_ROOT; }; + 0CF0AA3895D28E97D8A1E4A9 /* ground_truth.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = ground_truth.h; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/flann/ground_truth.h; sourceTree = SOURCE_ROOT; }; + 0E8B230ABD3E15CB838BC68A /* EdenError.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = EdenError.h; path = ../../../addons/ofxArtool5/libs/include/Eden/EdenError.h; sourceTree = SOURCE_ROOT; }; + 0EA1B984E5A716EF974AB308 /* streams.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = streams.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/legacy/streams.hpp"; sourceTree = SOURCE_ROOT; }; + 0EA20DDEFA1EFA2EB57FB6B1 /* gpu.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = gpu.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/gpu/gpu.hpp"; sourceTree = SOURCE_ROOT; }; + 1054B4574F75C1F693C147C6 /* optical_flow.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = optical_flow.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/videostab/optical_flow.hpp; sourceTree = SOURCE_ROOT; }; + 105C46BD1A7DC856FD49499D /* readtex.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = readtex.h; path = ../../../addons/ofxArtool5/libs/include/Eden/readtex.h; sourceTree = SOURCE_ROOT; }; + 1096663EC01E472E05F84D97 /* core_c.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = core_c.h; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/core/core_c.h"; sourceTree = SOURCE_ROOT; }; + 114B872696817CC33990FC83 /* imgproc.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = imgproc.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/imgproc/imgproc.hpp; sourceTree = SOURCE_ROOT; }; + 121DCDF461D181123CCC093E /* cuda_devptrs.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = cuda_devptrs.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/core/cuda_devptrs.hpp"; sourceTree = SOURCE_ROOT; }; + 125F19BE8968F0531BD54AC8 /* cxeigen.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = cxeigen.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv/cxeigen.hpp"; sourceTree = SOURCE_ROOT; }; + 12880E3C833A75D578638C30 /* videoDummy.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = videoDummy.h; path = ../../../addons/ofxArtool5/libs/include/AR/sys/videoDummy.h; sourceTree = SOURCE_ROOT; }; + 12D7B23266A840BA325518D1 /* type_traits_detail.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = type_traits_detail.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/gpu/device/detail/type_traits_detail.hpp"; sourceTree = SOURCE_ROOT; }; + 1335F3F49E8A72CB04FA873D /* util_inl.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = util_inl.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/stitching/detail/util_inl.hpp; sourceTree = SOURCE_ROOT; }; + 13C35E1A5B5BF01EFD26C29E /* Eden.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = Eden.h; path = ../../../addons/ofxArtool5/libs/include/Eden/Eden.h; sourceTree = SOURCE_ROOT; }; + 1496CC561C1EC3E800EA3164 /* libAR.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = libAR.a; path = ../libs/lib/libAR.a; sourceTree = ""; }; + 1496CC571C1EC3E800EA3164 /* libAR2.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = libAR2.a; path = ../libs/lib/libAR2.a; sourceTree = ""; }; + 1496CC581C1EC3E800EA3164 /* libARgsub_lite.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = libARgsub_lite.a; path = ../libs/lib/libARgsub_lite.a; sourceTree = ""; }; + 1496CC591C1EC3E800EA3164 /* libARgsub.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = libARgsub.a; path = ../libs/lib/libARgsub.a; sourceTree = ""; }; + 1496CC5A1C1EC3E800EA3164 /* libARICP.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = libARICP.a; path = ../libs/lib/libARICP.a; sourceTree = ""; }; + 1496CC5B1C1EC3E800EA3164 /* libARMulti.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = libARMulti.a; path = ../libs/lib/libARMulti.a; sourceTree = ""; }; + 1496CC5C1C1EC3E800EA3164 /* libARosg.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = libARosg.a; path = ../libs/lib/libARosg.a; sourceTree = ""; }; + 1496CC5D1C1EC3E800EA3164 /* libARUtil.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = libARUtil.a; path = ../libs/lib/libARUtil.a; sourceTree = ""; }; + 1496CC5E1C1EC3E800EA3164 /* libARvideo.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = libARvideo.a; path = ../libs/lib/libARvideo.a; sourceTree = ""; }; + 1496CC5F1C1EC3E800EA3164 /* libKPM.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = libKPM.a; path = ../libs/lib/libKPM.a; sourceTree = ""; }; + 14ABFE71BD54EB8CC74F4773 /* detection_based_tracker.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = detection_based_tracker.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/contrib/detection_based_tracker.hpp"; sourceTree = SOURCE_ROOT; }; + 14B90C9D1C2B20A8004D0E12 /* trackingSub.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; name = trackingSub.c; path = ../src/trackingSub.c; sourceTree = ""; }; + 14B90C9E1C2B20A8004D0E12 /* trackingSub.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = trackingSub.h; path = ../src/trackingSub.h; sourceTree = ""; }; + 14B90CA01C2B20B8004D0E12 /* ARMarkerNFT.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; name = ARMarkerNFT.c; path = ../src/ARMarkerNFT.c; sourceTree = ""; }; + 14B90CA11C2B20B8004D0E12 /* ARMarkerNFT.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = ARMarkerNFT.h; path = ../src/ARMarkerNFT.h; sourceTree = ""; }; + 14B90CA31C2B20D3004D0E12 /* ofxARTGenericTracker.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = ofxARTGenericTracker.cpp; path = ../src/ofxARTGenericTracker.cpp; sourceTree = ""; }; + 14B90CA41C2B20D3004D0E12 /* ofxARTGenericTracker.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = ofxARTGenericTracker.h; path = ../src/ofxARTGenericTracker.h; sourceTree = ""; }; + 14B90CA51C2B20D3004D0E12 /* ofxARTNftTracker.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = ofxARTNftTracker.cpp; path = ../src/ofxARTNftTracker.cpp; sourceTree = ""; }; + 14B90CA61C2B20D3004D0E12 /* ofxARTNftTracker.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = ofxARTNftTracker.h; path = ../src/ofxARTNftTracker.h; sourceTree = ""; }; + 14B90CA71C2B20D3004D0E12 /* ofxARTPattern.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = ofxARTPattern.cpp; path = ../src/ofxARTPattern.cpp; sourceTree = ""; }; + 14B90CA81C2B20D3004D0E12 /* ofxARTPattern.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = ofxARTPattern.h; path = ../src/ofxARTPattern.h; sourceTree = ""; }; + 14D0A7B81C47DDCF00BFDBAB /* ofxARTNftUtils.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = ofxARTNftUtils.h; path = ../src/ofxARTNftUtils.h; sourceTree = ""; }; + 14D0A7B91C47F54600BFDBAB /* libjpeg.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = libjpeg.a; path = ../libs/lib/libjpeg.a; sourceTree = ""; }; + 1545130E4C53AAE200153F52 /* util_inl.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = util_inl.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/stitching/detail/util_inl.hpp"; sourceTree = SOURCE_ROOT; }; + 17CE5A4068930946980DE788 /* stabilizer.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = stabilizer.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/videostab/stabilizer.hpp; sourceTree = SOURCE_ROOT; }; + 1847F7FE85977D3E65AD9F95 /* flann_base.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = flann_base.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/flann/flann_base.hpp"; sourceTree = SOURCE_ROOT; }; + 18E16A7CA55F6761C64833F7 /* vec_traits.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = vec_traits.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/gpu/device/vec_traits.hpp; sourceTree = SOURCE_ROOT; }; + 191CF9ACD27233FD41B41566 /* operations.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = operations.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/core/operations.hpp"; sourceTree = SOURCE_ROOT; }; + 193FCB79070216E56D3F0F28 /* videoiPhone.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = videoiPhone.h; path = ../../../addons/ofxArtool5/libs/include/AR/sys/videoiPhone.h; sourceTree = SOURCE_ROOT; }; + 1A32C6C20A0C372D8F1896BE /* icp.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = icp.h; path = ../../../addons/ofxArtool5/libs/include/AR/icp.h; sourceTree = SOURCE_ROOT; }; + 1AD5FD8CB7EA240501080287 /* vec_math.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = vec_math.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/gpu/device/vec_math.hpp; sourceTree = SOURCE_ROOT; }; + 1BC7B0BC7149A647D551A418 /* transform.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = transform.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/gpu/device/transform.hpp"; sourceTree = SOURCE_ROOT; }; + 1BDEB4E4D908345A1935E0A0 /* warp_reduce.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = warp_reduce.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/gpu/device/warp_reduce.hpp"; sourceTree = SOURCE_ROOT; }; + 1C490B8705672F1410388922 /* reduce.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = reduce.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/gpu/device/detail/reduce.hpp; sourceTree = SOURCE_ROOT; }; + 1DFE1A829F216F2BB8605CD4 /* deblurring.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = deblurring.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/videostab/deblurring.hpp"; sourceTree = SOURCE_ROOT; }; + 1E95EFD35ED9C5D97F2F015E /* timer.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = timer.h; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/flann/timer.h; sourceTree = SOURCE_ROOT; }; + 1F9D46D19614774956DFE362 /* seam_finders.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = seam_finders.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/stitching/detail/seam_finders.hpp; sourceTree = SOURCE_ROOT; }; + 1FF41D5E98B5EE6FE02BED50 /* ARMarkerNFT.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = ARMarkerNFT.h; path = ../../../addons/ofxArtool5/libs/include/ARWrapper/ARMarkerNFT.h; sourceTree = SOURCE_ROOT; }; + 2107ED8B85EDAFF57C321715 /* object_factory.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = object_factory.h; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/flann/object_factory.h"; sourceTree = SOURCE_ROOT; }; + 216B0CD5704D450169A1AE5D /* kdtree_index.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = kdtree_index.h; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/flann/kdtree_index.h"; sourceTree = SOURCE_ROOT; }; + 23DC870D6D2B2B357DC66E50 /* dummy.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = dummy.h; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/flann/dummy.h"; sourceTree = SOURCE_ROOT; }; + 2411F6B35DAAAE5083D51167 /* motion_estimators.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = motion_estimators.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/stitching/detail/motion_estimators.hpp; sourceTree = SOURCE_ROOT; }; + 267DB674B0AAF153D6CAC0BF /* lsh_index.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = lsh_index.h; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/flann/lsh_index.h"; sourceTree = SOURCE_ROOT; }; + 26E4EEE253C8A6EFC3B3A639 /* warpers.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = warpers.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/stitching/detail/warpers.hpp; sourceTree = SOURCE_ROOT; }; + 292A490B7C98655F984E26AF /* exposure_compensate.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = exposure_compensate.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/stitching/detail/exposure_compensate.hpp"; sourceTree = SOURCE_ROOT; }; + 293D553B5067FBB8DEFA84D9 /* cap_ios.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = cap_ios.h; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/highgui/cap_ios.h; sourceTree = SOURCE_ROOT; }; + 29A5CDAC2210669DF446EF76 /* common.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = common.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/gpu/device/common.hpp"; sourceTree = SOURCE_ROOT; }; + 2A0F7FC47545EFFDB6B7D41E /* config.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = config.h; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/flann/config.h"; sourceTree = SOURCE_ROOT; }; + 2B40EDA85BEB63E46785BC29 /* tinyxml.cpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.cpp; fileEncoding = 30; name = tinyxml.cpp; path = ../../../addons/ofxXmlSettings/libs/tinyxml.cpp; sourceTree = SOURCE_ROOT; }; + 2B75A06D9EF1817256BA26F6 /* type_traits_detail.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = type_traits_detail.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/gpu/device/detail/type_traits_detail.hpp; sourceTree = SOURCE_ROOT; }; + 2B8F813570DDD3AEB054BEE2 /* autotuned_index.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = autotuned_index.h; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/flann/autotuned_index.h"; sourceTree = SOURCE_ROOT; }; + 2C361926446CE14F69A3B56A /* videoQuickTime.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = videoQuickTime.h; path = ../../../addons/ofxArtool5/libs/include/AR/sys/videoQuickTime.h; sourceTree = SOURCE_ROOT; }; + 2D2C520C7195C2802C74E41C /* hybridtracker.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = hybridtracker.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/contrib/hybridtracker.hpp"; sourceTree = SOURCE_ROOT; }; + 2D654A2C2B095DBA96FA9EB5 /* ml.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = ml.h; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv/ml.h"; sourceTree = SOURCE_ROOT; }; + 2DCD64353E2066D36F401938 /* Platform.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = Platform.h; path = ../../../addons/ofxArtool5/libs/include/ARWrapper/Platform.h; sourceTree = SOURCE_ROOT; }; + 2E411F99E3AB7154484B4F96 /* kmeans_index.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = kmeans_index.h; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/flann/kmeans_index.h; sourceTree = SOURCE_ROOT; }; + 2E946FDA0F3FFDB0F321B91B /* jpeglib.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = jpeglib.h; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/jpeglib.h"; sourceTree = SOURCE_ROOT; }; + 2F465648B7ABB10F10322946 /* cv.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = cv.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv/cv.hpp"; sourceTree = SOURCE_ROOT; }; + 30884ECD9C171AB1B1BDFC3F /* cv.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = cv.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv/cv.hpp; sourceTree = SOURCE_ROOT; }; + 311939239C3654DFEEB7E618 /* superres.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = superres.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/superres/superres.hpp"; sourceTree = SOURCE_ROOT; }; + 311F65A208008448840A0A42 /* opengl_interop_deprecated.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = opengl_interop_deprecated.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/core/opengl_interop_deprecated.hpp; sourceTree = SOURCE_ROOT; }; + 318C2FC28B9DE76FF67DD476 /* saturate_cast.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = saturate_cast.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/gpu/device/saturate_cast.hpp"; sourceTree = SOURCE_ROOT; }; + 319268D200F1BA567E4CCFF9 /* cxeigen.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = cxeigen.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv/cxeigen.hpp; sourceTree = SOURCE_ROOT; }; + 31BE73BA37686CA4E4904323 /* matchers.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = matchers.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/stitching/detail/matchers.hpp; sourceTree = SOURCE_ROOT; }; + 327617C1583F1AD5F48F5E1F /* miniflann.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = miniflann.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/flann/miniflann.hpp"; sourceTree = SOURCE_ROOT; }; + 32C0ABFFA61E10538E4B6F4A /* kdtree_single_index.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = kdtree_single_index.h; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/flann/kdtree_single_index.h"; sourceTree = SOURCE_ROOT; }; + 336A416F54B80EEA4170F43F /* dynamic_bitset.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = dynamic_bitset.h; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/flann/dynamic_bitset.h"; sourceTree = SOURCE_ROOT; }; + 33C5F7BE9EADBDBED640E6ED /* frame_source.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = frame_source.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/videostab/frame_source.hpp"; sourceTree = SOURCE_ROOT; }; + 33FF03222909C1A0ECE43753 /* cv.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = cv.h; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv/cv.h; sourceTree = SOURCE_ROOT; }; + 3493F9E8D3CC4B0CFD95D1D0 /* optical_flow.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = optical_flow.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/videostab/optical_flow.hpp"; sourceTree = SOURCE_ROOT; }; + 3533A3AE9C6571C3CCECE98D /* matchers.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = matchers.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/stitching/detail/matchers.hpp"; sourceTree = SOURCE_ROOT; }; + 35EEEA3F57EFB3D7DE4C0DED /* saturate_cast.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = saturate_cast.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/gpu/device/saturate_cast.hpp; sourceTree = SOURCE_ROOT; }; + 36507CEFC553ECF393BFA3F2 /* videoLinux1394Cam.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = videoLinux1394Cam.h; path = ../../../addons/ofxArtool5/libs/include/AR/sys/videoLinux1394Cam.h; sourceTree = SOURCE_ROOT; }; + 36F0FF7F8D7342D220CC6319 /* dummy.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = dummy.h; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/flann/dummy.h; sourceTree = SOURCE_ROOT; }; + 372EDE2892B6978261E277DF /* MovieVideo.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = MovieVideo.h; path = ../../../addons/ofxArtool5/libs/include/AR/sys/MovieVideo.h; sourceTree = SOURCE_ROOT; }; + 373564AC3DB989AE0AE96B01 /* reduce.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = reduce.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/gpu/device/reduce.hpp"; sourceTree = SOURCE_ROOT; }; + 37D155721DCC51F3D1DC2E02 /* color_detail.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = color_detail.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/gpu/device/detail/color_detail.hpp; sourceTree = SOURCE_ROOT; }; + 38F7826504DA273FBB14268A /* contrib.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = contrib.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/contrib/contrib.hpp"; sourceTree = SOURCE_ROOT; }; + 3948823F43672A6A234462CA /* warpers.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = warpers.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/stitching/detail/warpers.hpp"; sourceTree = SOURCE_ROOT; }; + 3A26AD0D61E8A4D2A78697EE /* AndroidFeatures.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = AndroidFeatures.h; path = ../../../addons/ofxArtool5/libs/include/ARWrapper/AndroidFeatures.h; sourceTree = SOURCE_ROOT; }; + 3ADB4E06C4EDB97E020A778D /* functional.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = functional.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/gpu/device/functional.hpp; sourceTree = SOURCE_ROOT; }; + 3BA1E6FB39E50FE9BFF48461 /* result_set.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = result_set.h; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/flann/result_set.h"; sourceTree = SOURCE_ROOT; }; + 3C7D79C5E01C9F74C72978CB /* glStateCache.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = glStateCache.h; path = ../../../addons/ofxArtool5/libs/include/glStateCache.h; sourceTree = SOURCE_ROOT; }; + 3C85BFFE8E1391CD3E493BF2 /* stitcher.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = stitcher.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/stitching/stitcher.hpp"; sourceTree = SOURCE_ROOT; }; + 3D5130A1AE0908069B11CDFE /* dist.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = dist.h; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/flann/dist.h"; sourceTree = SOURCE_ROOT; }; + 40558BF6D61AA5A193155C09 /* highgui.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = highgui.h; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv/highgui.h"; sourceTree = SOURCE_ROOT; }; + 40DC89EA94A2B7E5524E6727 /* EdenMath.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = EdenMath.h; path = ../../../addons/ofxArtool5/libs/include/Eden/EdenMath.h; sourceTree = SOURCE_ROOT; }; + 41540657118783F06D278554 /* videoWindowsMediaCapture.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = videoWindowsMediaCapture.h; path = ../../../addons/ofxArtool5/libs/include/AR/sys/videoWindowsMediaCapture.h; sourceTree = SOURCE_ROOT; }; + 417A0B7154103C22ECC253E8 /* reduce_key_val.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = reduce_key_val.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/gpu/device/detail/reduce_key_val.hpp; sourceTree = SOURCE_ROOT; }; + 41A55473C0BB857F4961F740 /* cvaux.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = cvaux.h; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv/cvaux.h"; sourceTree = SOURCE_ROOT; }; + 41E9090E543FC2D51BFD312C /* warp_reduce.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = warp_reduce.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/gpu/device/warp_reduce.hpp; sourceTree = SOURCE_ROOT; }; + 4321BB520593E59B319EAA39 /* cap_ios.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = cap_ios.h; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/highgui/cap_ios.h"; sourceTree = SOURCE_ROOT; }; + 44A8175B7C8A100B5BEF5DE4 /* autocalib.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = autocalib.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/stitching/detail/autocalib.hpp; sourceTree = SOURCE_ROOT; }; + 44B67493290FAB59F2E944BA /* EdenSound.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = EdenSound.h; path = ../../../addons/ofxArtool5/libs/include/Eden/EdenSound.h; sourceTree = SOURCE_ROOT; }; + 452417865E4BFB10C9CBF8A2 /* internal.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = internal.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/core/internal.hpp; sourceTree = SOURCE_ROOT; }; + 45410DD818BB205166E67E89 /* any.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = any.h; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/flann/any.h; sourceTree = SOURCE_ROOT; }; + 45E004D1064EC5B8C5C40A83 /* ts_perf.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = ts_perf.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/ts/ts_perf.hpp; sourceTree = SOURCE_ROOT; }; + 45F38573A0B0DEEC8BBC7A2C /* simplex_downhill.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = simplex_downhill.h; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/flann/simplex_downhill.h; sourceTree = SOURCE_ROOT; }; + 468AE2D36A92ECFA697D7B93 /* color.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = color.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/gpu/device/color.hpp"; sourceTree = SOURCE_ROOT; }; + 4694727ED9E385D5879DAA48 /* block.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = block.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/gpu/device/block.hpp"; sourceTree = SOURCE_ROOT; }; + 47807BFDC1FD685020A25205 /* EdenUtil.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = EdenUtil.h; path = ../../../addons/ofxArtool5/libs/include/Eden/EdenUtil.h; sourceTree = SOURCE_ROOT; }; + 48DE76DBB0333DF3CD2DDE22 /* autocalib.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = autocalib.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/stitching/detail/autocalib.hpp"; sourceTree = SOURCE_ROOT; }; + 49EFFCF36CF194CCE0E1FAAB /* kdtree_index.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = kdtree_index.h; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/flann/kdtree_index.h; sourceTree = SOURCE_ROOT; }; + 4B10C258D52310BA5B4823D9 /* png.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = png.h; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/png.h"; sourceTree = SOURCE_ROOT; }; + 4CD2228F2C8116D51179E3A3 /* devmem2d.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = devmem2d.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/core/devmem2d.hpp; sourceTree = SOURCE_ROOT; }; + 4CFA8A81B93736DE82F0090A /* gpumat.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = gpumat.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/core/gpumat.hpp; sourceTree = SOURCE_ROOT; }; + 4E2DEDD1595923E70E6DCEF0 /* config.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = config.h; path = ../../../addons/ofxArtool5/libs/include/AR/config.h; sourceTree = SOURCE_ROOT; }; + 4E7BDA7E30AB9A46688DAAEF /* random.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = random.h; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/flann/random.h"; sourceTree = SOURCE_ROOT; }; + 501DCE8C13E424354D5E3AB2 /* CameraVideo.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = CameraVideo.h; path = ../../../addons/ofxArtool5/libs/include/AR/sys/CameraVideo.h; sourceTree = SOURCE_ROOT; }; + 50DF87D612C5AAE17AAFA6C0 /* ofxXmlSettings.cpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.cpp; fileEncoding = 30; name = ofxXmlSettings.cpp; path = ../../../addons/ofxXmlSettings/src/ofxXmlSettings.cpp; sourceTree = SOURCE_ROOT; }; + 5105862F1606831E9239FEAF /* simd_functions.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = simd_functions.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/gpu/device/simd_functions.hpp; sourceTree = SOURCE_ROOT; }; + 516717F84C0146512C47A3EC /* ofxCvHaarFinder.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = ofxCvHaarFinder.h; path = ../../../addons/ofxOpenCv/src/ofxCvHaarFinder.h; sourceTree = SOURCE_ROOT; }; + 516A5DDB4873A0EA32A35796 /* blenders.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = blenders.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/stitching/detail/blenders.hpp"; sourceTree = SOURCE_ROOT; }; + 5224CB49C43C932C56A11B35 /* kmeans_index.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = kmeans_index.h; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/flann/kmeans_index.h"; sourceTree = SOURCE_ROOT; }; + 537B1CA73B5E062AF8FE3CFA /* jmorecfg.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = jmorecfg.h; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/jmorecfg.h"; sourceTree = SOURCE_ROOT; }; + 53B277E28B04F78A5B88520A /* gpu_perf.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = gpu_perf.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/ts/gpu_perf.hpp"; sourceTree = SOURCE_ROOT; }; + 54F6FED854433FB73BB07334 /* warp.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = warp.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/gpu/device/warp.hpp"; sourceTree = SOURCE_ROOT; }; + 55A9AB3E0575C89B96B58810 /* openfabmap.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = openfabmap.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/contrib/openfabmap.hpp"; sourceTree = SOURCE_ROOT; }; + 56ED74AD5FC73867F5E046F0 /* photo_c.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = photo_c.h; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/photo/photo_c.h; sourceTree = SOURCE_ROOT; }; + 574DACA623C3A9D405037FA7 /* videoWindowsDragonFly.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = videoWindowsDragonFly.h; path = ../../../addons/ofxArtool5/libs/include/AR/sys/videoWindowsDragonFly.h; sourceTree = SOURCE_ROOT; }; + 584DE0F392E877302F7DDB93 /* videoLinux1394CamV2.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = videoLinux1394CamV2.h; path = ../../../addons/ofxArtool5/libs/include/AR/sys/videoLinux1394CamV2.h; sourceTree = SOURCE_ROOT; }; + 586A8EC141BDFA82B3B0518C /* config.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = config.h; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/flann/config.h; sourceTree = SOURCE_ROOT; }; + 59570D160E1EDD6EB832826A /* frame_source.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = frame_source.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/videostab/frame_source.hpp; sourceTree = SOURCE_ROOT; }; + 59626D03C690200AD4E8B3A6 /* ml.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = ml.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/ml/ml.hpp; sourceTree = SOURCE_ROOT; }; + 59DC9BAE1FAD8D36CD5F324F /* glm.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = glm.h; path = ../../../addons/ofxArtool5/libs/include/Eden/glm.h; sourceTree = SOURCE_ROOT; }; + 5A59183C98FC5E69FC90F138 /* contrib.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = contrib.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/contrib/contrib.hpp; sourceTree = SOURCE_ROOT; }; + 5A5CDEE1BFF097614562CD88 /* common.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = common.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/gpu/device/common.hpp; sourceTree = SOURCE_ROOT; }; + 5B8D5239B004CE3CA49587A2 /* vec_distance.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = vec_distance.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/gpu/device/vec_distance.hpp"; sourceTree = SOURCE_ROOT; }; + 5D966EA1AA66E2D55D047733 /* blobtrack.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = blobtrack.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/legacy/blobtrack.hpp; sourceTree = SOURCE_ROOT; }; + 5E04ECD8243254906741012F /* EdenTime.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = EdenTime.h; path = ../../../addons/ofxArtool5/libs/include/Eden/EdenTime.h; sourceTree = SOURCE_ROOT; }; + 5EC2E0646C1AA03897CD4447 /* reduce_key_val.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = reduce_key_val.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/gpu/device/detail/reduce_key_val.hpp"; sourceTree = SOURCE_ROOT; }; + 5EC378F4D5B6B18CE5E66610 /* emulation.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = emulation.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/gpu/device/emulation.hpp"; sourceTree = SOURCE_ROOT; }; + 5FF4222C797A0433389500C7 /* hierarchical_clustering_index.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = hierarchical_clustering_index.h; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/flann/hierarchical_clustering_index.h"; sourceTree = SOURCE_ROOT; }; + 601152ABEB500E58F5F31264 /* pngconf.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = pngconf.h; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/pngconf.h"; sourceTree = SOURCE_ROOT; }; + 60179A75A6C5F9A54DA3A64C /* streams.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = streams.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/legacy/streams.hpp; sourceTree = SOURCE_ROOT; }; + 603F2267D449084A4187A049 /* ofxCvBlob.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = ofxCvBlob.h; path = ../../../addons/ofxOpenCv/src/ofxCvBlob.h; sourceTree = SOURCE_ROOT; }; + 61339778C58D921474B5729E /* features2d.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = features2d.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/features2d/features2d.hpp; sourceTree = SOURCE_ROOT; }; + 62BC9F3BC298D034438626B5 /* dynamic_smem.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = dynamic_smem.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/gpu/device/dynamic_smem.hpp"; sourceTree = SOURCE_ROOT; }; + 63152EF07846DECD2854B62C /* utility.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = utility.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/gpu/device/utility.hpp; sourceTree = SOURCE_ROOT; }; + 6519D7399258A2CE575AD59E /* calib3d.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = calib3d.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/calib3d/calib3d.hpp"; sourceTree = SOURCE_ROOT; }; + 665780A3005496E3A4A0D9EF /* compat.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = compat.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/legacy/compat.hpp; sourceTree = SOURCE_ROOT; }; + 67AF0E794FA186DD25454CC9 /* calib3d.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = calib3d.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/calib3d/calib3d.hpp; sourceTree = SOURCE_ROOT; }; + 68D0CACAFB6303756CE0BE6A /* kpmType.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = kpmType.h; path = ../../../addons/ofxArtool5/libs/include/KPM/kpmType.h; sourceTree = SOURCE_ROOT; }; + 6940F9A28CDC85ED7D1847C1 /* emulation.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = emulation.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/gpu/device/emulation.hpp; sourceTree = SOURCE_ROOT; }; + 6A46E9B76216C9D97F354267 /* profile.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = profile.h; path = ../../../addons/ofxArtool5/libs/include/profile.h; sourceTree = SOURCE_ROOT; }; + 6AA400C56F3B733F2745CEB6 /* coord.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = coord.h; path = ../../../addons/ofxArtool5/libs/include/AR2/coord.h; sourceTree = SOURCE_ROOT; }; + 6B907CFBB1B0FEDE76C41AA0 /* heap.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = heap.h; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/flann/heap.h; sourceTree = SOURCE_ROOT; }; + 6C1C5DA0E9AD077F2951E1D4 /* videoQuickTime7.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = videoQuickTime7.h; path = ../../../addons/ofxArtool5/libs/include/AR/sys/videoQuickTime7.h; sourceTree = SOURCE_ROOT; }; + 6C9BF7C449A19951F7BE2340 /* heap.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = heap.h; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/flann/heap.h"; sourceTree = SOURCE_ROOT; }; + 6DD5A3CBB6D5BBA1C1354F1B /* flann.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = flann.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/flann/flann.hpp; sourceTree = SOURCE_ROOT; }; + 6DDE7E140FC9CDD0A70C5FC3 /* compat.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = compat.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/legacy/compat.hpp"; sourceTree = SOURCE_ROOT; }; + 6EA973FFDBDDBDD03CF4448F /* fast_marching_inl.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = fast_marching_inl.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/videostab/fast_marching_inl.hpp"; sourceTree = SOURCE_ROOT; }; + 70405932ECA0CD36E8AFC425 /* gsub_mtx.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = gsub_mtx.h; path = ../../../addons/ofxArtool5/libs/include/AR/gsub_mtx.h; sourceTree = SOURCE_ROOT; }; + 706ED8D299F6DC8D2271550F /* types_c.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = types_c.h; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/core/types_c.h"; sourceTree = SOURCE_ROOT; }; + 7101CF2125B8B2BF46AA2662 /* cxcore.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = cxcore.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv/cxcore.hpp; sourceTree = SOURCE_ROOT; }; + 71740E886E2F15D9ED7A50F5 /* flann.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = flann.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/flann/flann.hpp"; sourceTree = SOURCE_ROOT; }; + 71AAFD9E525875B75110F31D /* photo.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = photo.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/photo/photo.hpp"; sourceTree = SOURCE_ROOT; }; + 71C98C3F44D63B39F1482A54 /* background_segm.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = background_segm.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/video/background_segm.hpp; sourceTree = SOURCE_ROOT; }; + 722542BCDC94162B6A8B9B72 /* defines.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = defines.h; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/flann/defines.h; sourceTree = SOURCE_ROOT; }; + 7279658ADA9582251CB1D783 /* log.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = log.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/videostab/log.hpp; sourceTree = SOURCE_ROOT; }; + 72B94F356CADE56182030526 /* videoConfig.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = videoConfig.h; path = ../../../addons/ofxArtool5/libs/include/AR/videoConfig.h; sourceTree = SOURCE_ROOT; }; + 73CB9E4F6812598081C2FE01 /* opengl_interop.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = opengl_interop.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/core/opengl_interop.hpp; sourceTree = SOURCE_ROOT; }; + 73FAF82FD751EAA91F34C221 /* internal.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = internal.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/core/internal.hpp"; sourceTree = SOURCE_ROOT; }; + 74889E354F64911B56A1CAD1 /* warp.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = warp.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/gpu/device/warp.hpp; sourceTree = SOURCE_ROOT; }; + 74ABE32586A1A622FB4902BB /* video.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = video.h; path = ../../../addons/ofxArtool5/libs/include/AR/video.h; sourceTree = SOURCE_ROOT; }; + 7580F08204F3287FD45E7176 /* arImageProc.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = arImageProc.h; path = ../../../addons/ofxArtool5/libs/include/AR/arImageProc.h; sourceTree = SOURCE_ROOT; }; + 758F19335D4E46A5E0DE449F /* kdtree_single_index.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = kdtree_single_index.h; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/flann/kdtree_single_index.h; sourceTree = SOURCE_ROOT; }; + 76506F8866AC39A5276E5648 /* highgui_c.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = highgui_c.h; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/highgui/highgui_c.h"; sourceTree = SOURCE_ROOT; }; + 7673F0AA19794A4C9517CF14 /* ts.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = ts.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/ts/ts.hpp; sourceTree = SOURCE_ROOT; }; + 76FDA209FE142FBDE46F1376 /* color_detail.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = color_detail.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/gpu/device/detail/color_detail.hpp"; sourceTree = SOURCE_ROOT; }; + 7725A887B72BE1C4F5332528 /* mat.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = mat.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/core/mat.hpp"; sourceTree = SOURCE_ROOT; }; + 77C5FDA779939B373FD0729E /* warp_shuffle.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = warp_shuffle.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/gpu/device/warp_shuffle.hpp"; sourceTree = SOURCE_ROOT; }; + 77CCDF5787485AB378EAAF41 /* ocl.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = ocl.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/nonfree/ocl.hpp"; sourceTree = SOURCE_ROOT; }; + 78D6F0B645B0CA57181BB404 /* AndroidVideoSource.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = AndroidVideoSource.h; path = ../../../addons/ofxArtool5/libs/include/ARWrapper/AndroidVideoSource.h; sourceTree = SOURCE_ROOT; }; + 78EE8C3C54E6D186AA66E52F /* gsub.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = gsub.h; path = ../../../addons/ofxArtool5/libs/include/AR/gsub.h; sourceTree = SOURCE_ROOT; }; + 79E285EDBBEA89226444A4D0 /* blenders.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = blenders.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/stitching/detail/blenders.hpp; sourceTree = SOURCE_ROOT; }; + 79EBCCC1657111CC5BF0A090 /* param.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = param.h; path = ../../../addons/ofxArtool5/libs/include/AR/param.h; sourceTree = SOURCE_ROOT; }; + 7B6A03390302D5A2C9F0E4AB /* ofxCvFloatImage.cpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.cpp; fileEncoding = 30; name = ofxCvFloatImage.cpp; path = ../../../addons/ofxOpenCv/src/ofxCvFloatImage.cpp; sourceTree = SOURCE_ROOT; }; + 7C3D9C0EAC738ED2624D264B /* ml.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = ml.h; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv/ml.h; sourceTree = SOURCE_ROOT; }; + 7C67530288E980E0EE66DA3A /* searchPoint.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = searchPoint.h; path = ../../../addons/ofxArtool5/libs/include/AR2/searchPoint.h; sourceTree = SOURCE_ROOT; }; + 7D86D41170A02B361853AB73 /* vec_distance.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = vec_distance.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/gpu/device/vec_distance.hpp; sourceTree = SOURCE_ROOT; }; + 7E57AAE3FAB29F87D19451BC /* sampling.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = sampling.h; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/flann/sampling.h; sourceTree = SOURCE_ROOT; }; + 7EBD7AF7397E5C072B05A9EB /* wimage.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = wimage.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/core/wimage.hpp"; sourceTree = SOURCE_ROOT; }; + 7ED6D6EFE04E5839E10F8E3E /* cxcore.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = cxcore.h; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv/cxcore.h"; sourceTree = SOURCE_ROOT; }; + 7FF509E292BEC89FF126DED8 /* arConfig.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = arConfig.h; path = ../../../addons/ofxArtool5/libs/include/AR/arConfig.h; sourceTree = SOURCE_ROOT; }; + 810826C8598BDB25EFD9FC71 /* video.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = video.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/video/video.hpp"; sourceTree = SOURCE_ROOT; }; + 8115E3F30A9B3F09BA08E59D /* imageFormat.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = imageFormat.h; path = ../../../addons/ofxArtool5/libs/include/AR2/imageFormat.h; sourceTree = SOURCE_ROOT; }; + 824E193BB4FBD633CD037EC9 /* gpu_test.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = gpu_test.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/ts/gpu_test.hpp"; sourceTree = SOURCE_ROOT; }; + 82F38A8CEADEE9F485ADC380 /* gsubConfig.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = gsubConfig.h; path = ../../../addons/ofxArtool5/libs/include/AR/gsubConfig.h; sourceTree = SOURCE_ROOT; }; + 832BDC407620CDBA568B713D /* tinyxmlerror.cpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.cpp; fileEncoding = 30; name = tinyxmlerror.cpp; path = ../../../addons/ofxXmlSettings/libs/tinyxmlerror.cpp; sourceTree = SOURCE_ROOT; }; + 838C0A631612A5E26A4C4EE9 /* transform_detail.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = transform_detail.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/gpu/device/detail/transform_detail.hpp"; sourceTree = SOURCE_ROOT; }; + 84238297E460936905B92D16 /* limits.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = limits.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/gpu/device/limits.hpp; sourceTree = SOURCE_ROOT; }; + 84E02E22D76A6E6ACE6FAB7A /* cvaux.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = cvaux.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv/cvaux.hpp"; sourceTree = SOURCE_ROOT; }; + 8530EAD600CD792B81B2E79D /* legacy.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = legacy.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/legacy/legacy.hpp; sourceTree = SOURCE_ROOT; }; + 863E8D68BCF580E6E3184C76 /* opengl_interop.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = opengl_interop.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/core/opengl_interop.hpp"; sourceTree = SOURCE_ROOT; }; + 8655B83EDEA07FF3DF4C6BE7 /* objdetect.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = objdetect.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/objdetect/objdetect.hpp"; sourceTree = SOURCE_ROOT; }; + 87DBF560FF25F1CD2E737825 /* openfabmap.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = openfabmap.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/contrib/openfabmap.hpp; sourceTree = SOURCE_ROOT; }; + 8A4DD23693DFAB8EC05FAA5D /* ofxCvShortImage.cpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.cpp; fileEncoding = 30; name = ofxCvShortImage.cpp; path = ../../../addons/ofxOpenCv/src/ofxCvShortImage.cpp; sourceTree = SOURCE_ROOT; }; + 8B37D9B1B3905BC34151EEF4 /* EdenGLFont.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = EdenGLFont.h; path = ../../../addons/ofxArtool5/libs/include/Eden/EdenGLFont.h; sourceTree = SOURCE_ROOT; }; + 8C5B6033A209406858A4F020 /* cxcore.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = cxcore.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv/cxcore.hpp"; sourceTree = SOURCE_ROOT; }; + 8D2AE620ADCA6300B31A7B04 /* arvrml.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = arvrml.h; path = ../../../addons/ofxArtool5/libs/include/AR/arvrml.h; sourceTree = SOURCE_ROOT; }; + 8DB45DE3BD6BB97E34BDB411 /* nn_index.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = nn_index.h; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/flann/nn_index.h; sourceTree = SOURCE_ROOT; }; + 8E79CF8911DFABAFE23EA45B /* ofxCvConstants.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = ofxCvConstants.h; path = ../../../addons/ofxOpenCv/src/ofxCvConstants.h; sourceTree = SOURCE_ROOT; }; + 8E8C45D5096159AFE8620E52 /* videoWindowsDirectShow.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = videoWindowsDirectShow.h; path = ../../../addons/ofxArtool5/libs/include/AR/sys/videoWindowsDirectShow.h; sourceTree = SOURCE_ROOT; }; + 8F7BF7F7D3DFE78B2623C882 /* EdenSurfaces.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = EdenSurfaces.h; path = ../../../addons/ofxArtool5/libs/include/Eden/EdenSurfaces.h; sourceTree = SOURCE_ROOT; }; + 8FB4573CDB2FB9658ACF87AA /* gpu_test.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = gpu_test.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/ts/gpu_test.hpp; sourceTree = SOURCE_ROOT; }; + 9175BC65D347086F5E48C072 /* eigen.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = eigen.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/core/eigen.hpp"; sourceTree = SOURCE_ROOT; }; + 92925CF0555136012F8CF99D /* lsh_table.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = lsh_table.h; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/flann/lsh_table.h"; sourceTree = SOURCE_ROOT; }; + 946187321200AC04E570E6EC /* hierarchical_clustering_index.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = hierarchical_clustering_index.h; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/flann/hierarchical_clustering_index.h; sourceTree = SOURCE_ROOT; }; + 960BD311ABBA7D3299D7FE1F /* datamov_utils.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = datamov_utils.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/gpu/device/datamov_utils.hpp; sourceTree = SOURCE_ROOT; }; + 962242971E021F5CB5C56AB2 /* imgproc.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = imgproc.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/imgproc/imgproc.hpp"; sourceTree = SOURCE_ROOT; }; + 974AACF856A0A1B7D8F259E0 /* result_set.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = result_set.h; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/flann/result_set.h; sourceTree = SOURCE_ROOT; }; + 97CFAD0B2F2DB004A8A3BC0B /* objdetect.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = objdetect.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/objdetect/objdetect.hpp; sourceTree = SOURCE_ROOT; }; + 97F20BDB0AB952886E41E761 /* config.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = config.h; path = ../../../addons/ofxArtool5/libs/include/AR2/config.h; sourceTree = SOURCE_ROOT; }; + 97FBD89E6180673035AD1083 /* video.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = video.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/video/video.hpp; sourceTree = SOURCE_ROOT; }; + 9800D28620FC85E5248F0631 /* ground_truth.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = ground_truth.h; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/flann/ground_truth.h"; sourceTree = SOURCE_ROOT; }; + 9A048549F08C6DFFA79E6DEF /* ofxCvGrayscaleImage.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = ofxCvGrayscaleImage.h; path = ../../../addons/ofxOpenCv/src/ofxCvGrayscaleImage.h; sourceTree = SOURCE_ROOT; }; + 9A16CBF2E8CFE43AF54FE6F5 /* ofxCvHaarFinder.cpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.cpp; fileEncoding = 30; name = ofxCvHaarFinder.cpp; path = ../../../addons/ofxOpenCv/src/ofxCvHaarFinder.cpp; sourceTree = SOURCE_ROOT; }; + 9A807ED85FFB53D3638FCBE0 /* videostab.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = videostab.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/videostab/videostab.hpp; sourceTree = SOURCE_ROOT; }; + 9ABD8CF34D37FADFEB352B88 /* opencv_modules.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = opencv_modules.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/opencv_modules.hpp; sourceTree = SOURCE_ROOT; }; + 9ACCECC8FB1479C0CFF55823 /* videoQuickTimeMovie.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = videoQuickTimeMovie.h; path = ../../../addons/ofxArtool5/libs/include/AR/sys/videoQuickTimeMovie.h; sourceTree = SOURCE_ROOT; }; + 9B076DCB5B800BE9AF1B71A6 /* flann_base.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = flann_base.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/flann/flann_base.hpp; sourceTree = SOURCE_ROOT; }; + 9B55998E41388AD8704E4F9A /* imgproc_c.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = imgproc_c.h; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/imgproc/imgproc_c.h; sourceTree = SOURCE_ROOT; }; + 9B589ED62A60FEBC844243C0 /* any.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = any.h; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/flann/any.h"; sourceTree = SOURCE_ROOT; }; + 9B7D592E7AB311451A27C46E /* opencv.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = opencv.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/opencv.hpp; sourceTree = SOURCE_ROOT; }; + 9B90B3EE60497170AA00BFE8 /* types_c.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = types_c.h; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/imgproc/types_c.h; sourceTree = SOURCE_ROOT; }; + 9DA0CBD43DA38386EB04C9AE /* miniflann.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = miniflann.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/flann/miniflann.hpp; sourceTree = SOURCE_ROOT; }; + 9E26AC538CE46FA5FFB076E5 /* cvwimage.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = cvwimage.h; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv/cvwimage.h"; sourceTree = SOURCE_ROOT; }; + 9EFB64FFBA8E2092A2A81658 /* marker.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = marker.h; path = ../../../addons/ofxArtool5/libs/include/AR2/marker.h; sourceTree = SOURCE_ROOT; }; + 9FC9360D6DAF4EB699E338B9 /* gsub_lite.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = gsub_lite.h; path = ../../../addons/ofxArtool5/libs/include/AR/gsub_lite.h; sourceTree = SOURCE_ROOT; }; + 9FF9126184DFBDE8A912373E /* highgui.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = highgui.h; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv/highgui.h; sourceTree = SOURCE_ROOT; }; + A0399084868E7CAFB7E3D8E9 /* retina.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = retina.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/contrib/retina.hpp; sourceTree = SOURCE_ROOT; }; + A05D2E672AD4A6342B607BDD /* warpers_inl.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = warpers_inl.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/stitching/detail/warpers_inl.hpp"; sourceTree = SOURCE_ROOT; }; + A15E0125B8C9B7F01DED5695 /* matrix.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = matrix.h; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/flann/matrix.h; sourceTree = SOURCE_ROOT; }; + A1E5C3C977BF213B183ABC28 /* block.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = block.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/gpu/device/block.hpp; sourceTree = SOURCE_ROOT; }; + A2690F8A92FF3A09D5D39F63 /* ARMarker.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = ARMarker.h; path = ../../../addons/ofxArtool5/libs/include/ARWrapper/ARMarker.h; sourceTree = SOURCE_ROOT; }; + A2C86A44C1FD1CB1DD189DFA /* transform.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = transform.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/gpu/device/transform.hpp; sourceTree = SOURCE_ROOT; }; + A2EE5E80B134EA52A8B369D2 /* eigen.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = eigen.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/core/eigen.hpp; sourceTree = SOURCE_ROOT; }; + A3411731962D0402217F182B /* fast_marching.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = fast_marching.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/videostab/fast_marching.hpp; sourceTree = SOURCE_ROOT; }; + A6CA08CE7613370E944EB2AC /* jconfig.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = jconfig.h; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/jconfig.h"; sourceTree = SOURCE_ROOT; }; + A6E7FBA444FAF5C275D32E6A /* saving.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = saving.h; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/flann/saving.h"; sourceTree = SOURCE_ROOT; }; + A770C8D74DA82B9944013381 /* gpu_perf.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = gpu_perf.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/ts/gpu_perf.hpp; sourceTree = SOURCE_ROOT; }; + A809E96D8FCBBDB59AF3024F /* gpu.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = gpu.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/nonfree/gpu.hpp"; sourceTree = SOURCE_ROOT; }; + A97A6FD1A16E9F89A101243D /* matrix.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = matrix.h; path = ../../../addons/ofxArtool5/libs/include/AR/matrix.h; sourceTree = SOURCE_ROOT; }; + A9C85208C7E45FB9D1926789 /* wimage.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = wimage.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/core/wimage.hpp; sourceTree = SOURCE_ROOT; }; + A9CA57F96E23B2978F11A893 /* gsub_es.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = gsub_es.h; path = ../../../addons/ofxArtool5/libs/include/AR/gsub_es.h; sourceTree = SOURCE_ROOT; }; + AAEB476019ED9B5709A62435 /* fast_marching.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = fast_marching.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/videostab/fast_marching.hpp"; sourceTree = SOURCE_ROOT; }; + AB2AE477F82ACF17D0121166 /* mat.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = mat.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/core/mat.hpp; sourceTree = SOURCE_ROOT; }; + AC69B0C8D3AA7224DA5D37A4 /* vec_math.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = vec_math.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/gpu/device/vec_math.hpp"; sourceTree = SOURCE_ROOT; }; + AD444F259A571E024AD576C8 /* static_check.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = static_check.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/gpu/device/static_check.hpp"; sourceTree = SOURCE_ROOT; }; + AE433383D6CA170C418C8A9E /* highgui_c.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = highgui_c.h; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/highgui/highgui_c.h; sourceTree = SOURCE_ROOT; }; + AF7C3C8465AD112E066C67A7 /* type_traits.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = type_traits.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/gpu/device/type_traits.hpp; sourceTree = SOURCE_ROOT; }; + AF9A155219FEDFA6E95454EA /* gpu.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = gpu.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/gpu/gpu.hpp; sourceTree = SOURCE_ROOT; }; + B04449613A997CBC31738276 /* allocator.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = allocator.h; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/flann/allocator.h"; sourceTree = SOURCE_ROOT; }; + B09FCFF976DCEACB7C7C8D4E /* optical_flow.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = optical_flow.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/superres/optical_flow.hpp; sourceTree = SOURCE_ROOT; }; + B1579F602B98D48A6937B341 /* util.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = util.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/stitching/detail/util.hpp; sourceTree = SOURCE_ROOT; }; + B1DCC53B17C50537AACC8DF0 /* reduce.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = reduce.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/gpu/device/reduce.hpp; sourceTree = SOURCE_ROOT; }; + B21491648BCF81718A49D855 /* timer.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = timer.h; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/flann/timer.h"; sourceTree = SOURCE_ROOT; }; + B21E7E5F548EEA92F368040B /* tinyxml.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = tinyxml.h; path = ../../../addons/ofxXmlSettings/libs/tinyxml.h; sourceTree = SOURCE_ROOT; }; + B2546D432D16A0DB78970321 /* videoLinux1394CamV1.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = videoLinux1394CamV1.h; path = ../../../addons/ofxArtool5/libs/include/AR/sys/videoLinux1394CamV1.h; sourceTree = SOURCE_ROOT; }; + B353080168DCA97D7DF8732F /* ocl.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = ocl.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/nonfree/ocl.hpp; sourceTree = SOURCE_ROOT; }; + B4B21E8B1A45C28C0F8E59EA /* videoWindowsMediaFoundation.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = videoWindowsMediaFoundation.h; path = ../../../addons/ofxArtool5/libs/include/AR/sys/videoWindowsMediaFoundation.h; sourceTree = SOURCE_ROOT; }; + B590852E2273F057FAB540DC /* EdenMessage.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = EdenMessage.h; path = ../../../addons/ofxArtool5/libs/include/Eden/EdenMessage.h; sourceTree = SOURCE_ROOT; }; + B61FD2A2BF41E6BA2CFA4302 /* ARMarkerSquare.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = ARMarkerSquare.h; path = ../../../addons/ofxArtool5/libs/include/ARWrapper/ARMarkerSquare.h; sourceTree = SOURCE_ROOT; }; + B7BF51E8E757FF8A162D3662 /* lsh_index.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = lsh_index.h; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/flann/lsh_index.h; sourceTree = SOURCE_ROOT; }; + B8427966039B53A0FE69C1F0 /* cxcore.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = cxcore.h; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv/cxcore.h; sourceTree = SOURCE_ROOT; }; + B8CC47DCFD5FF04A4A7375CA /* types_c.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = types_c.h; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/imgproc/types_c.h"; sourceTree = SOURCE_ROOT; }; + BA2345C0AC2330B6CF370764 /* detection_based_tracker.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = detection_based_tracker.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/contrib/detection_based_tracker.hpp; sourceTree = SOURCE_ROOT; }; + BA476F336F0E2175BC2C5434 /* log.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = log.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/videostab/log.hpp"; sourceTree = SOURCE_ROOT; }; + BA8FE37406E9CC8BC78CBAD9 /* videoImage.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = videoImage.h; path = ../../../addons/ofxArtool5/libs/include/AR/sys/videoImage.h; sourceTree = SOURCE_ROOT; }; + BAA655EFD80DAE3BF24EDD26 /* ARPattern.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = ARPattern.h; path = ../../../addons/ofxArtool5/libs/include/ARWrapper/ARPattern.h; sourceTree = SOURCE_ROOT; }; + BB3AD017D3D6CD77A9E85DC0 /* ts_gtest.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = ts_gtest.h; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/ts/ts_gtest.h"; sourceTree = SOURCE_ROOT; }; + BBACB46BA43322AB900C9A81 /* logger.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = logger.h; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/flann/logger.h"; sourceTree = SOURCE_ROOT; }; + BBAF9D981351C596CA67CAF9 /* hybridtracker.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = hybridtracker.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/contrib/hybridtracker.hpp; sourceTree = SOURCE_ROOT; }; + BBC7DE17082EC1E530EB0514 /* reduce.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = reduce.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/gpu/device/detail/reduce.hpp"; sourceTree = SOURCE_ROOT; }; + BBDDB831B55992B6A4927506 /* gsub_es2.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = gsub_es2.h; path = ../../../addons/ofxArtool5/libs/include/AR/gsub_es2.h; sourceTree = SOURCE_ROOT; }; + BDC9888C5FDF2876004EC463 /* videoLinuxV4L.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = videoLinuxV4L.h; path = ../../../addons/ofxArtool5/libs/include/AR/sys/videoLinuxV4L.h; sourceTree = SOURCE_ROOT; }; + C1A2E81B4FD0713346D7E806 /* affine.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = affine.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/core/affine.hpp; sourceTree = SOURCE_ROOT; }; + C1C56D20A1A57DC44096BFE7 /* ofxCvContourFinder.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = ofxCvContourFinder.h; path = ../../../addons/ofxOpenCv/src/ofxCvContourFinder.h; sourceTree = SOURCE_ROOT; }; + C362FD421E9C5E4962E410EB /* dynamic_smem.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = dynamic_smem.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/gpu/device/dynamic_smem.hpp; sourceTree = SOURCE_ROOT; }; + C3D31A4D26C710C365002C0B /* filters.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = filters.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/gpu/device/filters.hpp"; sourceTree = SOURCE_ROOT; }; + C438B38E43EE4E9097A606B7 /* videoGStreamer.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = videoGStreamer.h; path = ../../../addons/ofxArtool5/libs/include/AR/sys/videoGStreamer.h; sourceTree = SOURCE_ROOT; }; + C4BA8097B54C90163F99F5C1 /* transform_detail.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = transform_detail.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/gpu/device/detail/transform_detail.hpp; sourceTree = SOURCE_ROOT; }; + C4FB85020773DA0F09B8B6CE /* ts_gtest.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = ts_gtest.h; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/ts/ts_gtest.h; sourceTree = SOURCE_ROOT; }; + C5D8D30AF8B9106909F7C433 /* ml.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = ml.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/ml/ml.hpp"; sourceTree = SOURCE_ROOT; }; + C6151136D101F857DAE12722 /* ofxCvImage.cpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.cpp; fileEncoding = 30; name = ofxCvImage.cpp; path = ../../../addons/ofxOpenCv/src/ofxCvImage.cpp; sourceTree = SOURCE_ROOT; }; + C61AD0EE460E5F7F1C5EC2A5 /* devmem2d.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = devmem2d.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/core/devmem2d.hpp"; sourceTree = SOURCE_ROOT; }; + C61D3DACE506E4A1C3A6D782 /* highgui.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = highgui.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/highgui/highgui.hpp; sourceTree = SOURCE_ROOT; }; + C65A89034372885C3F7259F5 /* superres.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = superres.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/superres/superres.hpp; sourceTree = SOURCE_ROOT; }; + C669B91F6711BEE214FB72C7 /* ARController.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = ARController.h; path = ../../../addons/ofxArtool5/libs/include/ARWrapper/ARController.h; sourceTree = SOURCE_ROOT; }; + C66C6414C8B86FDB99ED3B70 /* core.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = core.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/core/core.hpp; sourceTree = SOURCE_ROOT; }; + C7178EBE5A9A3912E58D1F0F /* features2d.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = features2d.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/nonfree/features2d.hpp; sourceTree = SOURCE_ROOT; }; + C76842900F3D5DFEEA04306C /* legacy.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = legacy.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/legacy/legacy.hpp"; sourceTree = SOURCE_ROOT; }; + C76DE5C29BDBD2CAA1DD0021 /* ofxCvContourFinder.cpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.cpp; fileEncoding = 30; name = ofxCvContourFinder.cpp; path = ../../../addons/ofxOpenCv/src/ofxCvContourFinder.cpp; sourceTree = SOURCE_ROOT; }; + C79C42BE4423853D097F4828 /* global_motion.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = global_motion.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/videostab/global_motion.hpp"; sourceTree = SOURCE_ROOT; }; + C7D283FE06CE2C7BB83BDE1A /* vec_traits.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = vec_traits.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/gpu/device/vec_traits.hpp"; sourceTree = SOURCE_ROOT; }; + C8BDC943F632842F0BB0A010 /* glStateCache2.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = glStateCache2.h; path = ../../../addons/ofxArtool5/libs/include/glStateCache2.h; sourceTree = SOURCE_ROOT; }; + C9441E60608F0B765F77D6D8 /* ts.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = ts.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/ts/ts.hpp"; sourceTree = SOURCE_ROOT; }; + C9F5BC338D9C1A995645DB8B /* stabilizer.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = stabilizer.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/videostab/stabilizer.hpp"; sourceTree = SOURCE_ROOT; }; + CA0126BFECF31BAC1DDBBDBE /* photo_c.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = photo_c.h; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/photo/photo_c.h"; sourceTree = SOURCE_ROOT; }; + CAA3766ACAFF06FD76F6E4F8 /* utility.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = utility.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/gpu/device/utility.hpp"; sourceTree = SOURCE_ROOT; }; + CBD95F574DF6041B8008E93B /* arosg.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = arosg.h; path = ../../../addons/ofxArtool5/libs/include/AR/arosg.h; sourceTree = SOURCE_ROOT; }; + CBDE84185E2969BA4AB209FC /* general.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = general.h; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/flann/general.h; sourceTree = SOURCE_ROOT; }; + CC566203C99B995E71EB2CA1 /* matrix.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = matrix.h; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/flann/matrix.h"; sourceTree = SOURCE_ROOT; }; + CC90E1821448E174161B60F4 /* arFilterTransMat.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = arFilterTransMat.h; path = ../../../addons/ofxArtool5/libs/include/AR/arFilterTransMat.h; sourceTree = SOURCE_ROOT; }; + CCEF89DB1EFB33729187CB32 /* imageSet.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = imageSet.h; path = ../../../addons/ofxArtool5/libs/include/AR2/imageSet.h; sourceTree = SOURCE_ROOT; }; + CCFB64CDA537F2B5A54CDC13 /* photo.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = photo.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/photo/photo.hpp; sourceTree = SOURCE_ROOT; }; + CD8565F2F122EECA0C095526 /* types_c.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = types_c.h; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/core/types_c.h; sourceTree = SOURCE_ROOT; }; + CE1D4FE73640B94B8479DD22 /* ARMarkerMulti.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = ARMarkerMulti.h; path = ../../../addons/ofxArtool5/libs/include/ARWrapper/ARMarkerMulti.h; sourceTree = SOURCE_ROOT; }; + CE5203B78839A661DA972B33 /* warpers_inl.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = warpers_inl.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/stitching/detail/warpers_inl.hpp; sourceTree = SOURCE_ROOT; }; + CE81A5E39EB3C871FDF3D4D5 /* ofxOpenCv.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = ofxOpenCv.h; path = ../../../addons/ofxOpenCv/src/ofxOpenCv.h; sourceTree = SOURCE_ROOT; }; + CE9C7160245B19131DAE6128 /* ofxCvColorImage.cpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.cpp; fileEncoding = 30; name = ofxCvColorImage.cpp; path = ../../../addons/ofxOpenCv/src/ofxCvColorImage.cpp; sourceTree = SOURCE_ROOT; }; + CF29BFB3FD3CAA54F336E6FD /* cvaux.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = cvaux.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv/cvaux.hpp; sourceTree = SOURCE_ROOT; }; + CFACEB58C0C7C28D5B9970A1 /* blobtrack.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = blobtrack.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/legacy/blobtrack.hpp"; sourceTree = SOURCE_ROOT; }; + CFC6795838E471E8F0309390 /* background_segm.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = background_segm.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/video/background_segm.hpp"; sourceTree = SOURCE_ROOT; }; + D078C50BFCDE342496B5D1F3 /* nonfree.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = nonfree.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/nonfree/nonfree.hpp; sourceTree = SOURCE_ROOT; }; + D2991184C57509808BF041C8 /* inpainting.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = inpainting.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/videostab/inpainting.hpp; sourceTree = SOURCE_ROOT; }; + D2A0C90494A29801CC5ED5BA /* videoWindowsDSVideoLib.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = videoWindowsDSVideoLib.h; path = ../../../addons/ofxArtool5/libs/include/AR/sys/videoWindowsDSVideoLib.h; sourceTree = SOURCE_ROOT; }; + D2E468A43F6E981DD9B460B5 /* stitcher.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = stitcher.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/stitching/stitcher.hpp; sourceTree = SOURCE_ROOT; }; + D363B90E27A45FBD9694F154 /* featureSet.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = featureSet.h; path = ../../../addons/ofxArtool5/libs/include/AR2/featureSet.h; sourceTree = SOURCE_ROOT; }; + D41B817B291B0687CE60F7FE /* cxmisc.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = cxmisc.h; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv/cxmisc.h"; sourceTree = SOURCE_ROOT; }; + D5074A182D9DE095F5A75AB1 /* type_traits.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = type_traits.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/gpu/device/type_traits.hpp"; sourceTree = SOURCE_ROOT; }; + D5A3AFF36064B2CACAD31716 /* composite_index.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = composite_index.h; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/flann/composite_index.h; sourceTree = SOURCE_ROOT; }; + D5BB6F0357B6422E1B1656B4 /* ofxCvColorImage.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = ofxCvColorImage.h; path = ../../../addons/ofxOpenCv/src/ofxCvColorImage.h; sourceTree = SOURCE_ROOT; }; + D5C04125322B78313C964C94 /* motion_stabilizing.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = motion_stabilizing.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/videostab/motion_stabilizing.hpp"; sourceTree = SOURCE_ROOT; }; + D62BF7B97C80F01DD827BE18 /* features2d.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = features2d.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/nonfree/features2d.hpp"; sourceTree = SOURCE_ROOT; }; + D6426FE9886FD3B4A831A446 /* exposure_compensate.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = exposure_compensate.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/stitching/detail/exposure_compensate.hpp; sourceTree = SOURCE_ROOT; }; + D76A59E7B3601E76351C9BDB /* cvaux.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = cvaux.h; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv/cvaux.h; sourceTree = SOURCE_ROOT; }; + D847EBE484F4F500F9CF2549 /* ofxCvImage.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = ofxCvImage.h; path = ../../../addons/ofxOpenCv/src/ofxCvImage.h; sourceTree = SOURCE_ROOT; }; + D902EB2409214285BCF5F191 /* stream_accessor.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = stream_accessor.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/gpu/stream_accessor.hpp; sourceTree = SOURCE_ROOT; }; + D9096CBF0FA5B49EC2081A99 /* videoAndroid.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = videoAndroid.h; path = ../../../addons/ofxArtool5/libs/include/AR/sys/videoAndroid.h; sourceTree = SOURCE_ROOT; }; + D9613459E2788BF99E572ED1 /* deblurring.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = deblurring.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/videostab/deblurring.hpp; sourceTree = SOURCE_ROOT; }; + D9F0442FA36643AFF7A08438 /* gluttext.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = gluttext.h; path = ../../../addons/ofxArtool5/libs/include/Eden/gluttext.h; sourceTree = SOURCE_ROOT; }; + DA71BD3D5EB1A1F5E64B6751 /* gpu.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = gpu.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/nonfree/gpu.hpp; sourceTree = SOURCE_ROOT; }; + DB8653D6433E14BF06F3EFAF /* cvwimage.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = cvwimage.h; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv/cvwimage.h; sourceTree = SOURCE_ROOT; }; + DBC5BA6354245CD3152DF4B2 /* videostab.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = videostab.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/videostab/videostab.hpp"; sourceTree = SOURCE_ROOT; }; + DBCD81E9A9DD37186CEE341F /* util.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = util.h; path = ../../../addons/ofxArtool5/libs/include/AR2/util.h; sourceTree = SOURCE_ROOT; }; + DCB56F4E9F44E31D571BC9C4 /* index_testing.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = index_testing.h; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/flann/index_testing.h; sourceTree = SOURCE_ROOT; }; + DE5510F10F3FF555332788B5 /* matrix_operations.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = matrix_operations.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/ocl/matrix_operations.hpp"; sourceTree = SOURCE_ROOT; }; + DEA2EDC0AFD59176FDEDC222 /* ofxCvShortImage.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = ofxCvShortImage.h; path = ../../../addons/ofxOpenCv/src/ofxCvShortImage.h; sourceTree = SOURCE_ROOT; }; + DEF077BFBC7788F62449523D /* gpumat.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = gpumat.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/core/gpumat.hpp"; sourceTree = SOURCE_ROOT; }; + DF7D499E8E04804AF9424496 /* ocl.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = ocl.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/ocl/ocl.hpp"; sourceTree = SOURCE_ROOT; }; + E0EF3200B795B4AD0A91B238 /* hdf5.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = hdf5.h; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/flann/hdf5.h"; sourceTree = SOURCE_ROOT; }; + E14D3EF03E140F5604900412 /* tracking.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = tracking.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/video/tracking.hpp; sourceTree = SOURCE_ROOT; }; + E21FF871B93E31DA43FE7E42 /* vec_distance_detail.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = vec_distance_detail.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/gpu/device/detail/vec_distance_detail.hpp; sourceTree = SOURCE_ROOT; }; + E354468911BA093791076DD7 /* gpumat.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = gpumat.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/gpu/gpumat.hpp; sourceTree = SOURCE_ROOT; }; + E3E0D71A46F534589DB7261B /* scan.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = scan.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/gpu/device/scan.hpp"; sourceTree = SOURCE_ROOT; }; + E4328143138ABC890047C5CB /* openFrameworksLib.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = openFrameworksLib.xcodeproj; path = ../../../libs/openFrameworksCompiled/project/osx/openFrameworksLib.xcodeproj; sourceTree = SOURCE_ROOT; }; + E4385429A1E63ACEDC39A612 /* operations.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = operations.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/core/operations.hpp; sourceTree = SOURCE_ROOT; }; + E4B69B5B0A3A1756003C02F2 /* artool5exampleDebug.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = artool5exampleDebug.app; sourceTree = BUILT_PRODUCTS_DIR; }; + E4B69E1D0A3A1BDC003C02F2 /* main.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; name = main.cpp; path = src/main.cpp; sourceTree = SOURCE_ROOT; }; + E4B69E1E0A3A1BDC003C02F2 /* ofApp.cpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.cpp; fileEncoding = 30; name = ofApp.cpp; path = src/ofApp.cpp; sourceTree = SOURCE_ROOT; }; + E4B69E1F0A3A1BDC003C02F2 /* ofApp.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; name = ofApp.h; path = src/ofApp.h; sourceTree = SOURCE_ROOT; }; + E4B6FCAD0C3E899E008CF71C /* openFrameworks-Info.plist */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text.plist.xml; path = "openFrameworks-Info.plist"; sourceTree = ""; }; + E4EB691F138AFCF100A09F29 /* CoreOF.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = CoreOF.xcconfig; path = ../../../libs/openFrameworksCompiled/project/osx/CoreOF.xcconfig; sourceTree = SOURCE_ROOT; }; + E4EB6923138AFD0F00A09F29 /* Project.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = Project.xcconfig; sourceTree = ""; }; + E5782506879D53B1024D4C95 /* ios.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = ios.h; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/highgui/ios.h"; sourceTree = SOURCE_ROOT; }; + E5F6E381641665852B997FC4 /* allocator.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = allocator.h; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/flann/allocator.h; sourceTree = SOURCE_ROOT; }; + E6B4A5620BFAA3AEF4724253 /* jversion.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = jversion.h; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/jversion.h"; sourceTree = SOURCE_ROOT; }; + E7097C5139D81810D8E7A183 /* simd_functions.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = simd_functions.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/gpu/device/simd_functions.hpp"; sourceTree = SOURCE_ROOT; }; + E798C88F1A0E2511E1756CE0 /* cuda_devptrs.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = cuda_devptrs.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/core/cuda_devptrs.hpp; sourceTree = SOURCE_ROOT; }; + E7B80CC0EB7994714340016A /* cv.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = cv.h; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv/cv.h"; sourceTree = SOURCE_ROOT; }; + E7DDB716B5AE0DEA82DFFEDA /* autotuned_index.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = autotuned_index.h; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/flann/autotuned_index.h; sourceTree = SOURCE_ROOT; }; + E83FB008593E6759DCFB0B39 /* arMulti.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = arMulti.h; path = ../../../addons/ofxArtool5/libs/include/AR/arMulti.h; sourceTree = SOURCE_ROOT; }; + E86738CE3F1443D36AEAEB1F /* ColorConversion.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = ColorConversion.h; path = ../../../addons/ofxArtool5/libs/include/ARWrapper/ColorConversion.h; sourceTree = SOURCE_ROOT; }; + E8AF1E9150AD818FA9D9195D /* version.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = version.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/core/version.hpp; sourceTree = SOURCE_ROOT; }; + E90542C149C83316678AB011 /* cxmisc.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = cxmisc.h; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv/cxmisc.h; sourceTree = SOURCE_ROOT; }; + E91710EE46CEF4551B523032 /* simplex_downhill.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = simplex_downhill.h; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/flann/simplex_downhill.h"; sourceTree = SOURCE_ROOT; }; + E9A50666D984CCA0F9932C17 /* tracking.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = tracking.h; path = ../../../addons/ofxArtool5/libs/include/AR2/tracking.h; sourceTree = SOURCE_ROOT; }; + E9BCAAE359F840B4C030878F /* ARToolKitVideoSource.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = ARToolKitVideoSource.h; path = ../../../addons/ofxArtool5/libs/include/ARWrapper/ARToolKitVideoSource.h; sourceTree = SOURCE_ROOT; }; + E9CF4BBF10F3BC59D0EED4FD /* version.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = version.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/core/version.hpp"; sourceTree = SOURCE_ROOT; }; + E9D96AED50E72CBBF32DD210 /* limits.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = limits.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/gpu/device/limits.hpp"; sourceTree = SOURCE_ROOT; }; + EA0F4E7A8F6B199A106A3DD1 /* inpainting.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = inpainting.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/videostab/inpainting.hpp"; sourceTree = SOURCE_ROOT; }; + EA65C764D841776F062BA281 /* optical_flow.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = optical_flow.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/superres/optical_flow.hpp"; sourceTree = SOURCE_ROOT; }; + EAB951061A30201E3F3DB3C9 /* border_interpolate.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = border_interpolate.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/gpu/device/border_interpolate.hpp"; sourceTree = SOURCE_ROOT; }; + EABE4B42765495583275AA6B /* VideoSource.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = VideoSource.h; path = ../../../addons/ofxArtool5/libs/include/ARWrapper/VideoSource.h; sourceTree = SOURCE_ROOT; }; + EB9334BE4C8EF1E3D2467EF2 /* index_testing.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = index_testing.h; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/flann/index_testing.h"; sourceTree = SOURCE_ROOT; }; + EBBA82550412B77EFA70AE87 /* funcattrib.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = funcattrib.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/gpu/device/funcattrib.hpp; sourceTree = SOURCE_ROOT; }; + EC61161F818EF5CC624B2E11 /* util.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = util.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/stitching/detail/util.hpp"; sourceTree = SOURCE_ROOT; }; + EC6222F2EC1058124B7FE7A1 /* imgproc_c.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = imgproc_c.h; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/imgproc/imgproc_c.h"; sourceTree = SOURCE_ROOT; }; + ECB0BCCA6832E3864264B486 /* opencv_modules.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = opencv_modules.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/opencv_modules.hpp"; sourceTree = SOURCE_ROOT; }; + ECC34C470C60F0A2AE2761B1 /* random.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = random.h; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/flann/random.h; sourceTree = SOURCE_ROOT; }; + EDC1B4EB0F86D93F1F0713B9 /* ARToolKitWrapperExportedAPI.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = ARToolKitWrapperExportedAPI.h; path = ../../../addons/ofxArtool5/libs/include/ARWrapper/ARToolKitWrapperExportedAPI.h; sourceTree = SOURCE_ROOT; }; + EE00607F82BD0A7CAF743FAB /* Image.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = Image.h; path = ../../../addons/ofxArtool5/libs/include/ARWrapper/Image.h; sourceTree = SOURCE_ROOT; }; + EEEA907F4732A9D8875ABB9C /* motion_stabilizing.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = motion_stabilizing.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/videostab/motion_stabilizing.hpp; sourceTree = SOURCE_ROOT; }; + EFB3B7B6967F5F8909C48032 /* warpers.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = warpers.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/stitching/warpers.hpp"; sourceTree = SOURCE_ROOT; }; + EFD1C55A957CC83D4497F3D9 /* retina.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = retina.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/contrib/retina.hpp"; sourceTree = SOURCE_ROOT; }; + EFD7A848C199282BE0705483 /* WindowsMediaCapture.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = WindowsMediaCapture.h; path = ../../../addons/ofxArtool5/libs/include/AR/sys/WindowsMediaCapture.h; sourceTree = SOURCE_ROOT; }; + EFF2505B0DC586A4BE7A1727 /* funcattrib.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = funcattrib.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/gpu/device/funcattrib.hpp"; sourceTree = SOURCE_ROOT; }; + EFF882C022E6AE8AE6E80585 /* kpm.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = kpm.h; path = ../../../addons/ofxArtool5/libs/include/KPM/kpm.h; sourceTree = SOURCE_ROOT; }; + F02CB2A1A86FC38A73F742DA /* ar.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = ar.h; path = ../../../addons/ofxArtool5/libs/include/AR/ar.h; sourceTree = SOURCE_ROOT; }; + F070AF5E3926EB2CB7A15D1B /* params.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = params.h; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/flann/params.h; sourceTree = SOURCE_ROOT; }; + F0FCA82EC2A69AEB3BA6AF38 /* filters.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = filters.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/gpu/device/filters.hpp; sourceTree = SOURCE_ROOT; }; + F116E87D0265F1B2AD8B8F59 /* highgui.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = highgui.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/highgui/highgui.hpp"; sourceTree = SOURCE_ROOT; }; + F12A5119769688B3818FAAB9 /* general.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = general.h; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/flann/general.h"; sourceTree = SOURCE_ROOT; }; + F14FC45547CD1DD943A4BCEF /* Error.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = Error.h; path = ../../../addons/ofxArtool5/libs/include/ARWrapper/Error.h; sourceTree = SOURCE_ROOT; }; + F1552EE5C3811E2C20924DB5 /* nn_index.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = nn_index.h; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/flann/nn_index.h"; sourceTree = SOURCE_ROOT; }; + F16236F72454124A6B5F1111 /* vec_distance_detail.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = vec_distance_detail.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/gpu/device/detail/vec_distance_detail.hpp"; sourceTree = SOURCE_ROOT; }; + F1A322222F4CB100AE8B471D /* functional.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = functional.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/gpu/device/functional.hpp"; sourceTree = SOURCE_ROOT; }; + F24EECBD6E1FFB2CDB6E17D3 /* params.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = params.h; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/flann/params.h"; sourceTree = SOURCE_ROOT; }; + F2F75C2513DDF24A79A894DF /* warpers.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = warpers.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/stitching/warpers.hpp; sourceTree = SOURCE_ROOT; }; + F38AB91361456BF84AB04DD1 /* border_interpolate.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = border_interpolate.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/gpu/device/border_interpolate.hpp; sourceTree = SOURCE_ROOT; }; + F697F17FBC2341D43AB497D0 /* seam_finders.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = seam_finders.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/stitching/detail/seam_finders.hpp"; sourceTree = SOURCE_ROOT; }; + F7269F96AC34A2B44A680D03 /* ofxCvFloatImage.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = ofxCvFloatImage.h; path = ../../../addons/ofxOpenCv/src/ofxCvFloatImage.h; sourceTree = SOURCE_ROOT; }; + F8651D9F17ABA3ED3ECBD58C /* gpumat.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = gpumat.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/gpu/gpumat.hpp"; sourceTree = SOURCE_ROOT; }; + F886EBA3F8F05C7F74633933 /* devmem2d.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = devmem2d.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/gpu/devmem2d.hpp; sourceTree = SOURCE_ROOT; }; + F94C6CC49A42363786E26CE3 /* opencv.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = opencv.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/opencv.hpp"; sourceTree = SOURCE_ROOT; }; + F9E5040C37DDD4C9E5B72CE5 /* ts_perf.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = ts_perf.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/ts/ts_perf.hpp"; sourceTree = SOURCE_ROOT; }; + F9EC3DDC0E9F85C34B21C760 /* object_factory.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = object_factory.h; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/flann/object_factory.h; sourceTree = SOURCE_ROOT; }; + FAEBF4DACC608B65EEE4F481 /* nonfree.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = nonfree.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/nonfree/nonfree.hpp"; sourceTree = SOURCE_ROOT; }; + FB213FF0567D1B312DDBD05D /* linear_index.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = linear_index.h; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/flann/linear_index.h; sourceTree = SOURCE_ROOT; }; + FB2852BC651C91987A1C26FB /* scan.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = scan.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/gpu/device/scan.hpp; sourceTree = SOURCE_ROOT; }; + FB73E8B97197E45AE40AF0FA /* tracking.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = tracking.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/video/tracking.hpp"; sourceTree = SOURCE_ROOT; }; + FC5DA1C87211D4F6377DA719 /* tinyxmlparser.cpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.cpp; fileEncoding = 30; name = tinyxmlparser.cpp; path = ../../../addons/ofxXmlSettings/libs/tinyxmlparser.cpp; sourceTree = SOURCE_ROOT; }; + FCCA500E8C8517D2E1D7C3CF /* motion_estimators.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = motion_estimators.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/stitching/detail/motion_estimators.hpp"; sourceTree = SOURCE_ROOT; }; + FD2373742F56BFA0EF7FBF09 /* color.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = color.hpp; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/gpu/device/color.hpp; sourceTree = SOURCE_ROOT; }; + FD5122B1C899C308E2563E75 /* core.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = core.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/core/core.hpp"; sourceTree = SOURCE_ROOT; }; + FD609E2EC17FCE181DFE635F /* dist.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = dist.h; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/flann/dist.h; sourceTree = SOURCE_ROOT; }; + FE644F5B159EC3F148FF62F6 /* devmem2d.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = devmem2d.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/gpu/devmem2d.hpp"; sourceTree = SOURCE_ROOT; }; + FE64B46039FE624CFAFF2FEB /* camera.hpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = camera.hpp; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/stitching/detail/camera.hpp"; sourceTree = SOURCE_ROOT; }; + FEDA0B6056089762F5FA11CA /* lsh_table.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = lsh_table.h; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/flann/lsh_table.h; sourceTree = SOURCE_ROOT; }; + FEDAC73D76F5FBDF32163E62 /* thread_sub.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = thread_sub.h; path = ../../../addons/ofxArtool5/libs/include/thread_sub.h; sourceTree = SOURCE_ROOT; }; + FF0C629FE4CFCB32689B212D /* composite_index.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = composite_index.h; path = "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/flann/composite_index.h"; sourceTree = SOURCE_ROOT; }; + FF58A50E588D6A64EE206840 /* hdf5.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.c.h; fileEncoding = 30; name = hdf5.h; path = ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/flann/hdf5.h; sourceTree = SOURCE_ROOT; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + E4B69B590A3A1756003C02F2 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 1496CC611C1EC3E800EA3164 /* libAR2.a in Frameworks */, + 1496CC601C1EC3E800EA3164 /* libAR.a in Frameworks */, + 1496CC671C1EC3E800EA3164 /* libARUtil.a in Frameworks */, + 1496CC631C1EC3E800EA3164 /* libARgsub.a in Frameworks */, + 1496CC681C1EC3E800EA3164 /* libARvideo.a in Frameworks */, + 14D0A7BA1C47F54600BFDBAB /* libjpeg.a in Frameworks */, + 1496CC651C1EC3E800EA3164 /* libARMulti.a in Frameworks */, + 1496CC661C1EC3E800EA3164 /* libARosg.a in Frameworks */, + E4328149138ABC9F0047C5CB /* openFrameworksDebug.a in Frameworks */, + 1496CC621C1EC3E800EA3164 /* libARgsub_lite.a in Frameworks */, + 1496CC691C1EC3E800EA3164 /* libKPM.a in Frameworks */, + 1496CC641C1EC3E800EA3164 /* libARICP.a in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 01F7BD3D78127FCD873395F7 /* contrib */ = { + isa = PBXGroup; + children = ( + 38F7826504DA273FBB14268A /* contrib.hpp */, + 14ABFE71BD54EB8CC74F4773 /* detection_based_tracker.hpp */, + 2D2C520C7195C2802C74E41C /* hybridtracker.hpp */, + 55A9AB3E0575C89B96B58810 /* openfabmap.hpp */, + EFD1C55A957CC83D4497F3D9 /* retina.hpp */, + ); + name = contrib; + sourceTree = ""; + }; + 0478E60892BF4C0731AE0763 /* ts */ = { + isa = PBXGroup; + children = ( + A770C8D74DA82B9944013381 /* gpu_perf.hpp */, + 8FB4573CDB2FB9658ACF87AA /* gpu_test.hpp */, + 7673F0AA19794A4C9517CF14 /* ts.hpp */, + C4FB85020773DA0F09B8B6CE /* ts_gtest.h */, + 45E004D1064EC5B8C5C40A83 /* ts_perf.hpp */, + ); + name = ts; + sourceTree = ""; + }; + 0F07FE174552DEF007BF5AD5 /* opencv2 */ = { + isa = PBXGroup; + children = ( + 428EB732FD42504F37BCA78A /* calib3d */, + 170C3384C93B182490DDC9CC /* contrib */, + A5A3A2F98919E2243C73199C /* core */, + 86FEC009E2721D0FB23338D7 /* features2d */, + 1E45F8C3CCFF6847BFF957AA /* flann */, + 5236346776DB8ECC4B121CA3 /* gpu */, + 9C99831C330874C2B245AB48 /* highgui */, + 3E44059DCBC2444D65660B9C /* imgproc */, + 961A625BD21068033782887C /* legacy */, + 0F288FD421D474F4AE2684D3 /* ml */, + 7BC63C2C5B49F4CFBC87C288 /* nonfree */, + D0CAFE48EE488EEED9149670 /* objdetect */, + 9B7D592E7AB311451A27C46E /* opencv.hpp */, + 9ABD8CF34D37FADFEB352B88 /* opencv_modules.hpp */, + 3B8F70BFDA30BBA2A5A060FC /* photo */, + AF43D9569510BEB0E2DFB944 /* stitching */, + ED977EFE7B82B0D53CB5C778 /* superres */, + 0478E60892BF4C0731AE0763 /* ts */, + C58CC92A5283B95AA31D50FB /* video */, + 38D119387412EF71F9FAA033 /* videostab */, + ); + name = opencv2; + sourceTree = ""; + }; + 0F288FD421D474F4AE2684D3 /* ml */ = { + isa = PBXGroup; + children = ( + 59626D03C690200AD4E8B3A6 /* ml.hpp */, + ); + name = ml; + sourceTree = ""; + }; + 11C4A9461DFF7D3955C3621D /* photo */ = { + isa = PBXGroup; + children = ( + 71AAFD9E525875B75110F31D /* photo.hpp */, + CA0126BFECF31BAC1DDBBDBE /* photo_c.h */, + ); + name = photo; + sourceTree = ""; + }; + 1496CC551C1EC3D800EA3164 /* lib */ = { + isa = PBXGroup; + children = ( + 14D0A7B91C47F54600BFDBAB /* libjpeg.a */, + 1496CC561C1EC3E800EA3164 /* libAR.a */, + 1496CC571C1EC3E800EA3164 /* libAR2.a */, + 1496CC581C1EC3E800EA3164 /* libARgsub_lite.a */, + 1496CC591C1EC3E800EA3164 /* libARgsub.a */, + 1496CC5A1C1EC3E800EA3164 /* libARICP.a */, + 1496CC5B1C1EC3E800EA3164 /* libARMulti.a */, + 1496CC5C1C1EC3E800EA3164 /* libARosg.a */, + 1496CC5D1C1EC3E800EA3164 /* libARUtil.a */, + 1496CC5E1C1EC3E800EA3164 /* libARvideo.a */, + 1496CC5F1C1EC3E800EA3164 /* libKPM.a */, + ); + name = lib; + sourceTree = ""; + }; + 14B4C6541C217BF6006F5CE4 /* ARMarkerNFT */ = { + isa = PBXGroup; + children = ( + 14B90CA01C2B20B8004D0E12 /* ARMarkerNFT.c */, + 14B90CA11C2B20B8004D0E12 /* ARMarkerNFT.h */, + ); + name = ARMarkerNFT; + sourceTree = ""; + }; + 14B4C6581C217FEB006F5CE4 /* trackingSub */ = { + isa = PBXGroup; + children = ( + 14B90C9D1C2B20A8004D0E12 /* trackingSub.c */, + 14B90C9E1C2B20A8004D0E12 /* trackingSub.h */, + ); + name = trackingSub; + sourceTree = ""; + }; + 170C3384C93B182490DDC9CC /* contrib */ = { + isa = PBXGroup; + children = ( + 5A59183C98FC5E69FC90F138 /* contrib.hpp */, + BA2345C0AC2330B6CF370764 /* detection_based_tracker.hpp */, + BBAF9D981351C596CA67CAF9 /* hybridtracker.hpp */, + 87DBF560FF25F1CD2E737825 /* openfabmap.hpp */, + A0399084868E7CAFB7E3D8E9 /* retina.hpp */, + ); + name = contrib; + sourceTree = ""; + }; + 1E45F8C3CCFF6847BFF957AA /* flann */ = { + isa = PBXGroup; + children = ( + 011E372AEA4DFBC1A32C2851 /* all_indices.h */, + E5F6E381641665852B997FC4 /* allocator.h */, + 45410DD818BB205166E67E89 /* any.h */, + E7DDB716B5AE0DEA82DFFEDA /* autotuned_index.h */, + D5A3AFF36064B2CACAD31716 /* composite_index.h */, + 586A8EC141BDFA82B3B0518C /* config.h */, + 722542BCDC94162B6A8B9B72 /* defines.h */, + FD609E2EC17FCE181DFE635F /* dist.h */, + 36F0FF7F8D7342D220CC6319 /* dummy.h */, + 096CB33CAD6C5A446E7026E9 /* dynamic_bitset.h */, + 6DD5A3CBB6D5BBA1C1354F1B /* flann.hpp */, + 9B076DCB5B800BE9AF1B71A6 /* flann_base.hpp */, + CBDE84185E2969BA4AB209FC /* general.h */, + 0CF0AA3895D28E97D8A1E4A9 /* ground_truth.h */, + FF58A50E588D6A64EE206840 /* hdf5.h */, + 6B907CFBB1B0FEDE76C41AA0 /* heap.h */, + 946187321200AC04E570E6EC /* hierarchical_clustering_index.h */, + DCB56F4E9F44E31D571BC9C4 /* index_testing.h */, + 49EFFCF36CF194CCE0E1FAAB /* kdtree_index.h */, + 758F19335D4E46A5E0DE449F /* kdtree_single_index.h */, + 2E411F99E3AB7154484B4F96 /* kmeans_index.h */, + FB213FF0567D1B312DDBD05D /* linear_index.h */, + 0173A3F435DECD5A4DDE0B8E /* logger.h */, + B7BF51E8E757FF8A162D3662 /* lsh_index.h */, + FEDA0B6056089762F5FA11CA /* lsh_table.h */, + A15E0125B8C9B7F01DED5695 /* matrix.h */, + 9DA0CBD43DA38386EB04C9AE /* miniflann.hpp */, + 8DB45DE3BD6BB97E34BDB411 /* nn_index.h */, + F9EC3DDC0E9F85C34B21C760 /* object_factory.h */, + F070AF5E3926EB2CB7A15D1B /* params.h */, + ECC34C470C60F0A2AE2761B1 /* random.h */, + 974AACF856A0A1B7D8F259E0 /* result_set.h */, + 7E57AAE3FAB29F87D19451BC /* sampling.h */, + 01DAE5C2E3E0A74207B2BE49 /* saving.h */, + 45F38573A0B0DEEC8BBC7A2C /* simplex_downhill.h */, + 1E95EFD35ED9C5D97F2F015E /* timer.h */, + ); + name = flann; + sourceTree = ""; + }; + 1F4FB5C423662B96ADFDCC0B /* ofxXmlSettings */ = { + isa = PBXGroup; + children = ( + 6ECEF0D76BC33727823EADFF /* src */, + 6E54289412D2D94F45A05113 /* libs */, + ); + name = ofxXmlSettings; + sourceTree = ""; + }; + 210053B36246928A2C9D5E51 /* imgproc */ = { + isa = PBXGroup; + children = ( + 962242971E021F5CB5C56AB2 /* imgproc.hpp */, + EC6222F2EC1058124B7FE7A1 /* imgproc_c.h */, + B8CC47DCFD5FF04A4A7375CA /* types_c.h */, + ); + name = imgproc; + sourceTree = ""; + }; + 21638266218E35A217E9CC30 /* gpu */ = { + isa = PBXGroup; + children = ( + 28D4FF5412F11329DC44E2C0 /* device */, + FE644F5B159EC3F148FF62F6 /* devmem2d.hpp */, + 0EA20DDEFA1EFA2EB57FB6B1 /* gpu.hpp */, + F8651D9F17ABA3ED3ECBD58C /* gpumat.hpp */, + 0C452162C2CE29FB58F53E5C /* stream_accessor.hpp */, + ); + name = gpu; + sourceTree = ""; + }; + 24DA51E7051C358698708222 /* AR */ = { + isa = PBXGroup; + children = ( + F02CB2A1A86FC38A73F742DA /* ar.h */, + 7FF509E292BEC89FF126DED8 /* arConfig.h */, + CC90E1821448E174161B60F4 /* arFilterTransMat.h */, + 7580F08204F3287FD45E7176 /* arImageProc.h */, + E83FB008593E6759DCFB0B39 /* arMulti.h */, + CBD95F574DF6041B8008E93B /* arosg.h */, + 8D2AE620ADCA6300B31A7B04 /* arvrml.h */, + 4E2DEDD1595923E70E6DCEF0 /* config.h */, + 78EE8C3C54E6D186AA66E52F /* gsub.h */, + A9CA57F96E23B2978F11A893 /* gsub_es.h */, + BBDDB831B55992B6A4927506 /* gsub_es2.h */, + 9FC9360D6DAF4EB699E338B9 /* gsub_lite.h */, + 70405932ECA0CD36E8AFC425 /* gsub_mtx.h */, + 82F38A8CEADEE9F485ADC380 /* gsubConfig.h */, + 1A32C6C20A0C372D8F1896BE /* icp.h */, + 05F316AD41D315CEB402E383 /* icpCalib.h */, + 04B8558FC9D04B0164C0A142 /* icpCore.h */, + A97A6FD1A16E9F89A101243D /* matrix.h */, + 79EBCCC1657111CC5BF0A090 /* param.h */, + 3250AED5A8A992D2A38380B1 /* sys */, + 74ABE32586A1A622FB4902BB /* video.h */, + 72B94F356CADE56182030526 /* videoConfig.h */, + ); + name = AR; + sourceTree = ""; + }; + 28D4FF5412F11329DC44E2C0 /* device */ = { + isa = PBXGroup; + children = ( + 4694727ED9E385D5879DAA48 /* block.hpp */, + EAB951061A30201E3F3DB3C9 /* border_interpolate.hpp */, + 468AE2D36A92ECFA697D7B93 /* color.hpp */, + 29A5CDAC2210669DF446EF76 /* common.hpp */, + 06BF0D5DFA7981166A713F58 /* datamov_utils.hpp */, + CC9E4303845894DAAAB30DBE /* detail */, + 62BC9F3BC298D034438626B5 /* dynamic_smem.hpp */, + 5EC378F4D5B6B18CE5E66610 /* emulation.hpp */, + C3D31A4D26C710C365002C0B /* filters.hpp */, + EFF2505B0DC586A4BE7A1727 /* funcattrib.hpp */, + F1A322222F4CB100AE8B471D /* functional.hpp */, + E9D96AED50E72CBBF32DD210 /* limits.hpp */, + 373564AC3DB989AE0AE96B01 /* reduce.hpp */, + 318C2FC28B9DE76FF67DD476 /* saturate_cast.hpp */, + E3E0D71A46F534589DB7261B /* scan.hpp */, + E7097C5139D81810D8E7A183 /* simd_functions.hpp */, + AD444F259A571E024AD576C8 /* static_check.hpp */, + 1BC7B0BC7149A647D551A418 /* transform.hpp */, + D5074A182D9DE095F5A75AB1 /* type_traits.hpp */, + CAA3766ACAFF06FD76F6E4F8 /* utility.hpp */, + 5B8D5239B004CE3CA49587A2 /* vec_distance.hpp */, + AC69B0C8D3AA7224DA5D37A4 /* vec_math.hpp */, + C7D283FE06CE2C7BB83BDE1A /* vec_traits.hpp */, + 54F6FED854433FB73BB07334 /* warp.hpp */, + 1BDEB4E4D908345A1935E0A0 /* warp_reduce.hpp */, + 77C5FDA779939B373FD0729E /* warp_shuffle.hpp */, + ); + name = device; + sourceTree = ""; + }; + 2B0FDE48B3014CDEFE073022 /* videostab */ = { + isa = PBXGroup; + children = ( + 1DFE1A829F216F2BB8605CD4 /* deblurring.hpp */, + AAEB476019ED9B5709A62435 /* fast_marching.hpp */, + 6EA973FFDBDDBDD03CF4448F /* fast_marching_inl.hpp */, + 33C5F7BE9EADBDBED640E6ED /* frame_source.hpp */, + C79C42BE4423853D097F4828 /* global_motion.hpp */, + EA0F4E7A8F6B199A106A3DD1 /* inpainting.hpp */, + BA476F336F0E2175BC2C5434 /* log.hpp */, + D5C04125322B78313C964C94 /* motion_stabilizing.hpp */, + 3493F9E8D3CC4B0CFD95D1D0 /* optical_flow.hpp */, + C9F5BC338D9C1A995645DB8B /* stabilizer.hpp */, + DBC5BA6354245CD3152DF4B2 /* videostab.hpp */, + ); + name = videostab; + sourceTree = ""; + }; + 2D59AA814151DF78F8BA624F /* KPM */ = { + isa = PBXGroup; + children = ( + EFF882C022E6AE8AE6E80585 /* kpm.h */, + 68D0CACAFB6303756CE0BE6A /* kpmType.h */, + ); + name = KPM; + sourceTree = ""; + }; + 2E2ACA4D54A7708521D72E7B /* nonfree */ = { + isa = PBXGroup; + children = ( + D62BF7B97C80F01DD827BE18 /* features2d.hpp */, + A809E96D8FCBBDB59AF3024F /* gpu.hpp */, + FAEBF4DACC608B65EEE4F481 /* nonfree.hpp */, + 77CCDF5787485AB378EAAF41 /* ocl.hpp */, + ); + name = nonfree; + sourceTree = ""; + }; + 303E2D4AF80E80BD1FD5E5F6 /* detail */ = { + isa = PBXGroup; + children = ( + 44A8175B7C8A100B5BEF5DE4 /* autocalib.hpp */, + 79E285EDBBEA89226444A4D0 /* blenders.hpp */, + 057D8E7580EA21E2254ADDDA /* camera.hpp */, + D6426FE9886FD3B4A831A446 /* exposure_compensate.hpp */, + 31BE73BA37686CA4E4904323 /* matchers.hpp */, + 2411F6B35DAAAE5083D51167 /* motion_estimators.hpp */, + 1F9D46D19614774956DFE362 /* seam_finders.hpp */, + B1579F602B98D48A6937B341 /* util.hpp */, + 1335F3F49E8A72CB04FA873D /* util_inl.hpp */, + 26E4EEE253C8A6EFC3B3A639 /* warpers.hpp */, + CE5203B78839A661DA972B33 /* warpers_inl.hpp */, + ); + name = detail; + sourceTree = ""; + }; + 3250AED5A8A992D2A38380B1 /* sys */ = { + isa = PBXGroup; + children = ( + 501DCE8C13E424354D5E3AB2 /* CameraVideo.h */, + 372EDE2892B6978261E277DF /* MovieVideo.h */, + D9096CBF0FA5B49EC2081A99 /* videoAndroid.h */, + 12880E3C833A75D578638C30 /* videoDummy.h */, + C438B38E43EE4E9097A606B7 /* videoGStreamer.h */, + BA8FE37406E9CC8BC78CBAD9 /* videoImage.h */, + 193FCB79070216E56D3F0F28 /* videoiPhone.h */, + 36507CEFC553ECF393BFA3F2 /* videoLinux1394Cam.h */, + B2546D432D16A0DB78970321 /* videoLinux1394CamV1.h */, + 584DE0F392E877302F7DDB93 /* videoLinux1394CamV2.h */, + BDC9888C5FDF2876004EC463 /* videoLinuxV4L.h */, + 2C361926446CE14F69A3B56A /* videoQuickTime.h */, + 6C1C5DA0E9AD077F2951E1D4 /* videoQuickTime7.h */, + 9ACCECC8FB1479C0CFF55823 /* videoQuickTimeMovie.h */, + 8E8C45D5096159AFE8620E52 /* videoWindowsDirectShow.h */, + 574DACA623C3A9D405037FA7 /* videoWindowsDragonFly.h */, + D2A0C90494A29801CC5ED5BA /* videoWindowsDSVideoLib.h */, + 41540657118783F06D278554 /* videoWindowsMediaCapture.h */, + B4B21E8B1A45C28C0F8E59EA /* videoWindowsMediaFoundation.h */, + EFD7A848C199282BE0705483 /* WindowsMediaCapture.h */, + ); + name = sys; + sourceTree = ""; + }; + 3522014B5FBDF9AF64431969 /* opencv2 */ = { + isa = PBXGroup; + children = ( + 462029E3450A5F08046C105C /* calib3d */, + 01F7BD3D78127FCD873395F7 /* contrib */, + 7DFC158229D76C8FE9042EB3 /* core */, + 626B648B18675B3C88942A8F /* features2d */, + 68A81167E5A40AC5A3FB0674 /* flann */, + 21638266218E35A217E9CC30 /* gpu */, + B70651BFA4120D26FFE23ABC /* highgui */, + 210053B36246928A2C9D5E51 /* imgproc */, + 4BC3C2765C244FBB9452B029 /* legacy */, + 91A3470D09C485B2A6A5CA7A /* ml */, + 2E2ACA4D54A7708521D72E7B /* nonfree */, + 971089368D3EFE2BE512127E /* objdetect */, + CC496B19754CB6120D9E32F8 /* ocl */, + F94C6CC49A42363786E26CE3 /* opencv.hpp */, + ECB0BCCA6832E3864264B486 /* opencv_modules.hpp */, + 11C4A9461DFF7D3955C3621D /* photo */, + A2DAFB411FAE5717F5632EF0 /* stitching */, + 9ACEC2A8C76C628FA9850D06 /* superres */, + 6F4EA391D9D7A92D800F918B /* ts */, + 670F8638B7F5851A4150CBCD /* video */, + 2B0FDE48B3014CDEFE073022 /* videostab */, + ); + name = opencv2; + sourceTree = ""; + }; + 371C7C765DED66AA23F35C69 /* libs */ = { + isa = PBXGroup; + children = ( + 1496CC551C1EC3D800EA3164 /* lib */, + 47FCA766B63F8A77521DDE8C /* include */, + ); + name = libs; + sourceTree = ""; + }; + 38D119387412EF71F9FAA033 /* videostab */ = { + isa = PBXGroup; + children = ( + D9613459E2788BF99E572ED1 /* deblurring.hpp */, + A3411731962D0402217F182B /* fast_marching.hpp */, + 075597E52E99BDE94F8036B2 /* fast_marching_inl.hpp */, + 59570D160E1EDD6EB832826A /* frame_source.hpp */, + 0CEC1FE946DBDBAB82AF6FE3 /* global_motion.hpp */, + D2991184C57509808BF041C8 /* inpainting.hpp */, + 7279658ADA9582251CB1D783 /* log.hpp */, + EEEA907F4732A9D8875ABB9C /* motion_stabilizing.hpp */, + 1054B4574F75C1F693C147C6 /* optical_flow.hpp */, + 17CE5A4068930946980DE788 /* stabilizer.hpp */, + 9A807ED85FFB53D3638FCBE0 /* videostab.hpp */, + ); + name = videostab; + sourceTree = ""; + }; + 3B8F70BFDA30BBA2A5A060FC /* photo */ = { + isa = PBXGroup; + children = ( + CCFB64CDA537F2B5A54CDC13 /* photo.hpp */, + 56ED74AD5FC73867F5E046F0 /* photo_c.h */, + ); + name = photo; + sourceTree = ""; + }; + 3E44059DCBC2444D65660B9C /* imgproc */ = { + isa = PBXGroup; + children = ( + 114B872696817CC33990FC83 /* imgproc.hpp */, + 9B55998E41388AD8704E4F9A /* imgproc_c.h */, + 9B90B3EE60497170AA00BFE8 /* types_c.h */, + ); + name = imgproc; + sourceTree = ""; + }; + 428EB732FD42504F37BCA78A /* calib3d */ = { + isa = PBXGroup; + children = ( + 67AF0E794FA186DD25454CC9 /* calib3d.hpp */, + ); + name = calib3d; + sourceTree = ""; + }; + 462029E3450A5F08046C105C /* calib3d */ = { + isa = PBXGroup; + children = ( + 6519D7399258A2CE575AD59E /* calib3d.hpp */, + ); + name = calib3d; + sourceTree = ""; + }; + 47FCA766B63F8A77521DDE8C /* include */ = { + isa = PBXGroup; + children = ( + 24DA51E7051C358698708222 /* AR */, + DD2B5B46F3C951ACDB5A75F0 /* AR2 */, + A55CDA802933EF2BBA4CA0C6 /* ARWrapper */, + EF390536765EAE0B3914B079 /* Eden */, + 3C7D79C5E01C9F74C72978CB /* glStateCache.h */, + C8BDC943F632842F0BB0A010 /* glStateCache2.h */, + 2D59AA814151DF78F8BA624F /* KPM */, + 7345487E97C9449AF3D44068 /* macosx-universal */, + 6A46E9B76216C9D97F354267 /* profile.h */, + FEDAC73D76F5FBDF32163E62 /* thread_sub.h */, + ); + name = include; + sourceTree = ""; + }; + 4BC3C2765C244FBB9452B029 /* legacy */ = { + isa = PBXGroup; + children = ( + CFACEB58C0C7C28D5B9970A1 /* blobtrack.hpp */, + 6DDE7E140FC9CDD0A70C5FC3 /* compat.hpp */, + C76842900F3D5DFEEA04306C /* legacy.hpp */, + 0EA1B984E5A716EF974AB308 /* streams.hpp */, + ); + name = legacy; + sourceTree = ""; + }; + 5236346776DB8ECC4B121CA3 /* gpu */ = { + isa = PBXGroup; + children = ( + C830064088936DB0F1158554 /* device */, + F886EBA3F8F05C7F74633933 /* devmem2d.hpp */, + AF9A155219FEDFA6E95454EA /* gpu.hpp */, + E354468911BA093791076DD7 /* gpumat.hpp */, + D902EB2409214285BCF5F191 /* stream_accessor.hpp */, + ); + name = gpu; + sourceTree = ""; + }; + 626B648B18675B3C88942A8F /* features2d */ = { + isa = PBXGroup; + children = ( + 0A7A79EFF93F6BB4C9415539 /* features2d.hpp */, + ); + name = features2d; + sourceTree = ""; + }; + 670F8638B7F5851A4150CBCD /* video */ = { + isa = PBXGroup; + children = ( + CFC6795838E471E8F0309390 /* background_segm.hpp */, + FB73E8B97197E45AE40AF0FA /* tracking.hpp */, + 810826C8598BDB25EFD9FC71 /* video.hpp */, + ); + name = video; + sourceTree = ""; + }; + 68A81167E5A40AC5A3FB0674 /* flann */ = { + isa = PBXGroup; + children = ( + 032B3A66B347FA0994B1F157 /* all_indices.h */, + B04449613A997CBC31738276 /* allocator.h */, + 9B589ED62A60FEBC844243C0 /* any.h */, + 2B8F813570DDD3AEB054BEE2 /* autotuned_index.h */, + FF0C629FE4CFCB32689B212D /* composite_index.h */, + 2A0F7FC47545EFFDB6B7D41E /* config.h */, + 09C0538EF14B23442E6A8B25 /* defines.h */, + 3D5130A1AE0908069B11CDFE /* dist.h */, + 23DC870D6D2B2B357DC66E50 /* dummy.h */, + 336A416F54B80EEA4170F43F /* dynamic_bitset.h */, + 71740E886E2F15D9ED7A50F5 /* flann.hpp */, + 1847F7FE85977D3E65AD9F95 /* flann_base.hpp */, + F12A5119769688B3818FAAB9 /* general.h */, + 9800D28620FC85E5248F0631 /* ground_truth.h */, + E0EF3200B795B4AD0A91B238 /* hdf5.h */, + 6C9BF7C449A19951F7BE2340 /* heap.h */, + 5FF4222C797A0433389500C7 /* hierarchical_clustering_index.h */, + EB9334BE4C8EF1E3D2467EF2 /* index_testing.h */, + 216B0CD5704D450169A1AE5D /* kdtree_index.h */, + 32C0ABFFA61E10538E4B6F4A /* kdtree_single_index.h */, + 5224CB49C43C932C56A11B35 /* kmeans_index.h */, + 058528378576B4E04FB78842 /* linear_index.h */, + BBACB46BA43322AB900C9A81 /* logger.h */, + 267DB674B0AAF153D6CAC0BF /* lsh_index.h */, + 92925CF0555136012F8CF99D /* lsh_table.h */, + CC566203C99B995E71EB2CA1 /* matrix.h */, + 327617C1583F1AD5F48F5E1F /* miniflann.hpp */, + F1552EE5C3811E2C20924DB5 /* nn_index.h */, + 2107ED8B85EDAFF57C321715 /* object_factory.h */, + F24EECBD6E1FFB2CDB6E17D3 /* params.h */, + 4E7BDA7E30AB9A46688DAAEF /* random.h */, + 3BA1E6FB39E50FE9BFF48461 /* result_set.h */, + 0BB5C619A159529C006E15A4 /* sampling.h */, + A6E7FBA444FAF5C275D32E6A /* saving.h */, + E91710EE46CEF4551B523032 /* simplex_downhill.h */, + B21491648BCF81718A49D855 /* timer.h */, + ); + name = flann; + sourceTree = ""; + }; + 6948EE371B920CB800B5AC1A /* local_addons */ = { + isa = PBXGroup; + children = ( + ); + name = local_addons; + sourceTree = ""; + }; + 6E54289412D2D94F45A05113 /* libs */ = { + isa = PBXGroup; + children = ( + 2B40EDA85BEB63E46785BC29 /* tinyxml.cpp */, + B21E7E5F548EEA92F368040B /* tinyxml.h */, + 832BDC407620CDBA568B713D /* tinyxmlerror.cpp */, + FC5DA1C87211D4F6377DA719 /* tinyxmlparser.cpp */, + ); + name = libs; + sourceTree = ""; + }; + 6ECEF0D76BC33727823EADFF /* src */ = { + isa = PBXGroup; + children = ( + 50DF87D612C5AAE17AAFA6C0 /* ofxXmlSettings.cpp */, + 01DCC0911400F9ACF5B65578 /* ofxXmlSettings.h */, + ); + name = src; + sourceTree = ""; + }; + 6F4EA391D9D7A92D800F918B /* ts */ = { + isa = PBXGroup; + children = ( + 53B277E28B04F78A5B88520A /* gpu_perf.hpp */, + 824E193BB4FBD633CD037EC9 /* gpu_test.hpp */, + C9441E60608F0B765F77D6D8 /* ts.hpp */, + BB3AD017D3D6CD77A9E85DC0 /* ts_gtest.h */, + F9E5040C37DDD4C9E5B72CE5 /* ts_perf.hpp */, + ); + name = ts; + sourceTree = ""; + }; + 7345487E97C9449AF3D44068 /* macosx-universal */ = { + isa = PBXGroup; + children = ( + A6CA08CE7613370E944EB2AC /* jconfig.h */, + 537B1CA73B5E062AF8FE3CFA /* jmorecfg.h */, + 2E946FDA0F3FFDB0F321B91B /* jpeglib.h */, + E6B4A5620BFAA3AEF4724253 /* jversion.h */, + E8C62539B35497B22A589E6D /* opencv */, + 3522014B5FBDF9AF64431969 /* opencv2 */, + 4B10C258D52310BA5B4823D9 /* png.h */, + 601152ABEB500E58F5F31264 /* pngconf.h */, + 00F3ABE019A17E4D55D8087D /* pnglibconf.h */, + ); + name = "macosx-universal"; + sourceTree = ""; + }; + 737B033AA777B67BA4F8F4D2 /* opencv */ = { + isa = PBXGroup; + children = ( + 33FF03222909C1A0ECE43753 /* cv.h */, + 30884ECD9C171AB1B1BDFC3F /* cv.hpp */, + D76A59E7B3601E76351C9BDB /* cvaux.h */, + CF29BFB3FD3CAA54F336E6FD /* cvaux.hpp */, + DB8653D6433E14BF06F3EFAF /* cvwimage.h */, + B8427966039B53A0FE69C1F0 /* cxcore.h */, + 7101CF2125B8B2BF46AA2662 /* cxcore.hpp */, + 319268D200F1BA567E4CCFF9 /* cxeigen.hpp */, + E90542C149C83316678AB011 /* cxmisc.h */, + 9FF9126184DFBDE8A912373E /* highgui.h */, + 7C3D9C0EAC738ED2624D264B /* ml.h */, + ); + name = opencv; + sourceTree = ""; + }; + 7BC63C2C5B49F4CFBC87C288 /* nonfree */ = { + isa = PBXGroup; + children = ( + C7178EBE5A9A3912E58D1F0F /* features2d.hpp */, + DA71BD3D5EB1A1F5E64B6751 /* gpu.hpp */, + D078C50BFCDE342496B5D1F3 /* nonfree.hpp */, + B353080168DCA97D7DF8732F /* ocl.hpp */, + ); + name = nonfree; + sourceTree = ""; + }; + 7DFC158229D76C8FE9042EB3 /* core */ = { + isa = PBXGroup; + children = ( + FD5122B1C899C308E2563E75 /* core.hpp */, + 1096663EC01E472E05F84D97 /* core_c.h */, + 121DCDF461D181123CCC093E /* cuda_devptrs.hpp */, + C61AD0EE460E5F7F1C5EC2A5 /* devmem2d.hpp */, + 9175BC65D347086F5E48C072 /* eigen.hpp */, + DEF077BFBC7788F62449523D /* gpumat.hpp */, + 73FAF82FD751EAA91F34C221 /* internal.hpp */, + 7725A887B72BE1C4F5332528 /* mat.hpp */, + 863E8D68BCF580E6E3184C76 /* opengl_interop.hpp */, + 06E6D9F57013B015362D7F7F /* opengl_interop_deprecated.hpp */, + 191CF9ACD27233FD41B41566 /* operations.hpp */, + 706ED8D299F6DC8D2271550F /* types_c.h */, + E9CF4BBF10F3BC59D0EED4FD /* version.hpp */, + 7EBD7AF7397E5C072B05A9EB /* wimage.hpp */, + ); + name = core; + sourceTree = ""; + }; + 86FEC009E2721D0FB23338D7 /* features2d */ = { + isa = PBXGroup; + children = ( + 61339778C58D921474B5729E /* features2d.hpp */, + ); + name = features2d; + sourceTree = ""; + }; + 91A3470D09C485B2A6A5CA7A /* ml */ = { + isa = PBXGroup; + children = ( + C5D8D30AF8B9106909F7C433 /* ml.hpp */, + ); + name = ml; + sourceTree = ""; + }; + 961A625BD21068033782887C /* legacy */ = { + isa = PBXGroup; + children = ( + 5D966EA1AA66E2D55D047733 /* blobtrack.hpp */, + 665780A3005496E3A4A0D9EF /* compat.hpp */, + 8530EAD600CD792B81B2E79D /* legacy.hpp */, + 60179A75A6C5F9A54DA3A64C /* streams.hpp */, + ); + name = legacy; + sourceTree = ""; + }; + 971089368D3EFE2BE512127E /* objdetect */ = { + isa = PBXGroup; + children = ( + 8655B83EDEA07FF3DF4C6BE7 /* objdetect.hpp */, + ); + name = objdetect; + sourceTree = ""; + }; + 9ACEC2A8C76C628FA9850D06 /* superres */ = { + isa = PBXGroup; + children = ( + EA65C764D841776F062BA281 /* optical_flow.hpp */, + 311939239C3654DFEEB7E618 /* superres.hpp */, + ); + name = superres; + sourceTree = ""; + }; + 9C99831C330874C2B245AB48 /* highgui */ = { + isa = PBXGroup; + children = ( + 293D553B5067FBB8DEFA84D9 /* cap_ios.h */, + C61D3DACE506E4A1C3A6D782 /* highgui.hpp */, + AE433383D6CA170C418C8A9E /* highgui_c.h */, + 0B87BF43E5302005FEF650B6 /* ios.h */, + ); + name = highgui; + sourceTree = ""; + }; + A0B90D3B0ADB9C1716816714 /* ofxOpenCv */ = { + isa = PBXGroup; + children = ( + C756CAAFD542831674E15FE6 /* src */, + DCC60D6724B56635AE867535 /* libs */, + ); + name = ofxOpenCv; + sourceTree = ""; + }; + A2DAFB411FAE5717F5632EF0 /* stitching */ = { + isa = PBXGroup; + children = ( + BA2C919B7887E1EDF4E4EE09 /* detail */, + 3C85BFFE8E1391CD3E493BF2 /* stitcher.hpp */, + EFB3B7B6967F5F8909C48032 /* warpers.hpp */, + ); + name = stitching; + sourceTree = ""; + }; + A4EB522F447A248482BFB138 /* src */ = { + isa = PBXGroup; + children = ( + 14B90CA31C2B20D3004D0E12 /* ofxARTGenericTracker.cpp */, + 14B90CA41C2B20D3004D0E12 /* ofxARTGenericTracker.h */, + 14B90CA51C2B20D3004D0E12 /* ofxARTNftTracker.cpp */, + 14B90CA61C2B20D3004D0E12 /* ofxARTNftTracker.h */, + 14D0A7B81C47DDCF00BFDBAB /* ofxARTNftUtils.h */, + 14B90CA71C2B20D3004D0E12 /* ofxARTPattern.cpp */, + 14B90CA81C2B20D3004D0E12 /* ofxARTPattern.h */, + 14B4C6581C217FEB006F5CE4 /* trackingSub */, + 14B4C6541C217BF6006F5CE4 /* ARMarkerNFT */, + ); + name = src; + sourceTree = ""; + }; + A55CDA802933EF2BBA4CA0C6 /* ARWrapper */ = { + isa = PBXGroup; + children = ( + 3A26AD0D61E8A4D2A78697EE /* AndroidFeatures.h */, + 78D6F0B645B0CA57181BB404 /* AndroidVideoSource.h */, + C669B91F6711BEE214FB72C7 /* ARController.h */, + A2690F8A92FF3A09D5D39F63 /* ARMarker.h */, + CE1D4FE73640B94B8479DD22 /* ARMarkerMulti.h */, + 1FF41D5E98B5EE6FE02BED50 /* ARMarkerNFT.h */, + B61FD2A2BF41E6BA2CFA4302 /* ARMarkerSquare.h */, + BAA655EFD80DAE3BF24EDD26 /* ARPattern.h */, + E9BCAAE359F840B4C030878F /* ARToolKitVideoSource.h */, + EDC1B4EB0F86D93F1F0713B9 /* ARToolKitWrapperExportedAPI.h */, + E86738CE3F1443D36AEAEB1F /* ColorConversion.h */, + F14FC45547CD1DD943A4BCEF /* Error.h */, + EE00607F82BD0A7CAF743FAB /* Image.h */, + 2DCD64353E2066D36F401938 /* Platform.h */, + EABE4B42765495583275AA6B /* VideoSource.h */, + ); + name = ARWrapper; + sourceTree = ""; + }; + A5A3A2F98919E2243C73199C /* core */ = { + isa = PBXGroup; + children = ( + C1A2E81B4FD0713346D7E806 /* affine.hpp */, + C66C6414C8B86FDB99ED3B70 /* core.hpp */, + 087522EA37A32B8D902CAB64 /* core_c.h */, + E798C88F1A0E2511E1756CE0 /* cuda_devptrs.hpp */, + 4CD2228F2C8116D51179E3A3 /* devmem2d.hpp */, + A2EE5E80B134EA52A8B369D2 /* eigen.hpp */, + 4CFA8A81B93736DE82F0090A /* gpumat.hpp */, + 452417865E4BFB10C9CBF8A2 /* internal.hpp */, + AB2AE477F82ACF17D0121166 /* mat.hpp */, + 73CB9E4F6812598081C2FE01 /* opengl_interop.hpp */, + 311F65A208008448840A0A42 /* opengl_interop_deprecated.hpp */, + E4385429A1E63ACEDC39A612 /* operations.hpp */, + CD8565F2F122EECA0C095526 /* types_c.h */, + E8AF1E9150AD818FA9D9195D /* version.hpp */, + A9C85208C7E45FB9D1926789 /* wimage.hpp */, + ); + name = core; + sourceTree = ""; + }; + AAA97F42C2FE4A31ECFD0585 /* opencv */ = { + isa = PBXGroup; + children = ( + F9F05170CB9BDF47DA2B6E6A /* include */, + ); + name = opencv; + sourceTree = ""; + }; + AF43D9569510BEB0E2DFB944 /* stitching */ = { + isa = PBXGroup; + children = ( + 303E2D4AF80E80BD1FD5E5F6 /* detail */, + D2E468A43F6E981DD9B460B5 /* stitcher.hpp */, + F2F75C2513DDF24A79A894DF /* warpers.hpp */, + ); + name = stitching; + sourceTree = ""; + }; + B70651BFA4120D26FFE23ABC /* highgui */ = { + isa = PBXGroup; + children = ( + 4321BB520593E59B319EAA39 /* cap_ios.h */, + F116E87D0265F1B2AD8B8F59 /* highgui.hpp */, + 76506F8866AC39A5276E5648 /* highgui_c.h */, + E5782506879D53B1024D4C95 /* ios.h */, + ); + name = highgui; + sourceTree = ""; + }; + BA2C919B7887E1EDF4E4EE09 /* detail */ = { + isa = PBXGroup; + children = ( + 48DE76DBB0333DF3CD2DDE22 /* autocalib.hpp */, + 516A5DDB4873A0EA32A35796 /* blenders.hpp */, + FE64B46039FE624CFAFF2FEB /* camera.hpp */, + 292A490B7C98655F984E26AF /* exposure_compensate.hpp */, + 3533A3AE9C6571C3CCECE98D /* matchers.hpp */, + FCCA500E8C8517D2E1D7C3CF /* motion_estimators.hpp */, + F697F17FBC2341D43AB497D0 /* seam_finders.hpp */, + EC61161F818EF5CC624B2E11 /* util.hpp */, + 1545130E4C53AAE200153F52 /* util_inl.hpp */, + 3948823F43672A6A234462CA /* warpers.hpp */, + A05D2E672AD4A6342B607BDD /* warpers_inl.hpp */, + ); + name = detail; + sourceTree = ""; + }; + BB4B014C10F69532006C3DED /* addons */ = { + isa = PBXGroup; + children = ( + E1353B123A9CD9750FE99DCA /* ofxArtool5 */, + A0B90D3B0ADB9C1716816714 /* ofxOpenCv */, + 1F4FB5C423662B96ADFDCC0B /* ofxXmlSettings */, + ); + name = addons; + sourceTree = ""; + }; + C58CC92A5283B95AA31D50FB /* video */ = { + isa = PBXGroup; + children = ( + 71C98C3F44D63B39F1482A54 /* background_segm.hpp */, + E14D3EF03E140F5604900412 /* tracking.hpp */, + 97FBD89E6180673035AD1083 /* video.hpp */, + ); + name = video; + sourceTree = ""; + }; + C756CAAFD542831674E15FE6 /* src */ = { + isa = PBXGroup; + children = ( + 603F2267D449084A4187A049 /* ofxCvBlob.h */, + CE9C7160245B19131DAE6128 /* ofxCvColorImage.cpp */, + D5BB6F0357B6422E1B1656B4 /* ofxCvColorImage.h */, + 8E79CF8911DFABAFE23EA45B /* ofxCvConstants.h */, + C76DE5C29BDBD2CAA1DD0021 /* ofxCvContourFinder.cpp */, + C1C56D20A1A57DC44096BFE7 /* ofxCvContourFinder.h */, + 7B6A03390302D5A2C9F0E4AB /* ofxCvFloatImage.cpp */, + F7269F96AC34A2B44A680D03 /* ofxCvFloatImage.h */, + 057122A817D12571F8C0C7A4 /* ofxCvGrayscaleImage.cpp */, + 9A048549F08C6DFFA79E6DEF /* ofxCvGrayscaleImage.h */, + 9A16CBF2E8CFE43AF54FE6F5 /* ofxCvHaarFinder.cpp */, + 516717F84C0146512C47A3EC /* ofxCvHaarFinder.h */, + C6151136D101F857DAE12722 /* ofxCvImage.cpp */, + D847EBE484F4F500F9CF2549 /* ofxCvImage.h */, + 8A4DD23693DFAB8EC05FAA5D /* ofxCvShortImage.cpp */, + DEA2EDC0AFD59176FDEDC222 /* ofxCvShortImage.h */, + CE81A5E39EB3C871FDF3D4D5 /* ofxOpenCv.h */, + ); + name = src; + sourceTree = ""; + }; + C830064088936DB0F1158554 /* device */ = { + isa = PBXGroup; + children = ( + A1E5C3C977BF213B183ABC28 /* block.hpp */, + F38AB91361456BF84AB04DD1 /* border_interpolate.hpp */, + FD2373742F56BFA0EF7FBF09 /* color.hpp */, + 5A5CDEE1BFF097614562CD88 /* common.hpp */, + 960BD311ABBA7D3299D7FE1F /* datamov_utils.hpp */, + DF5D380A1A4583A1636503A6 /* detail */, + C362FD421E9C5E4962E410EB /* dynamic_smem.hpp */, + 6940F9A28CDC85ED7D1847C1 /* emulation.hpp */, + F0FCA82EC2A69AEB3BA6AF38 /* filters.hpp */, + EBBA82550412B77EFA70AE87 /* funcattrib.hpp */, + 3ADB4E06C4EDB97E020A778D /* functional.hpp */, + 84238297E460936905B92D16 /* limits.hpp */, + B1DCC53B17C50537AACC8DF0 /* reduce.hpp */, + 35EEEA3F57EFB3D7DE4C0DED /* saturate_cast.hpp */, + FB2852BC651C91987A1C26FB /* scan.hpp */, + 5105862F1606831E9239FEAF /* simd_functions.hpp */, + 0ADD044A3066779F3673F1FE /* static_check.hpp */, + A2C86A44C1FD1CB1DD189DFA /* transform.hpp */, + AF7C3C8465AD112E066C67A7 /* type_traits.hpp */, + 63152EF07846DECD2854B62C /* utility.hpp */, + 7D86D41170A02B361853AB73 /* vec_distance.hpp */, + 1AD5FD8CB7EA240501080287 /* vec_math.hpp */, + 18E16A7CA55F6761C64833F7 /* vec_traits.hpp */, + 74889E354F64911B56A1CAD1 /* warp.hpp */, + 41E9090E543FC2D51BFD312C /* warp_reduce.hpp */, + 0339099A1F7B84040D88AD3C /* warp_shuffle.hpp */, + ); + name = device; + sourceTree = ""; + }; + CC496B19754CB6120D9E32F8 /* ocl */ = { + isa = PBXGroup; + children = ( + DE5510F10F3FF555332788B5 /* matrix_operations.hpp */, + DF7D499E8E04804AF9424496 /* ocl.hpp */, + ); + name = ocl; + sourceTree = ""; + }; + CC9E4303845894DAAAB30DBE /* detail */ = { + isa = PBXGroup; + children = ( + 76FDA209FE142FBDE46F1376 /* color_detail.hpp */, + BBC7DE17082EC1E530EB0514 /* reduce.hpp */, + 5EC2E0646C1AA03897CD4447 /* reduce_key_val.hpp */, + 838C0A631612A5E26A4C4EE9 /* transform_detail.hpp */, + 12D7B23266A840BA325518D1 /* type_traits_detail.hpp */, + F16236F72454124A6B5F1111 /* vec_distance_detail.hpp */, + ); + name = detail; + sourceTree = ""; + }; + D0CAFE48EE488EEED9149670 /* objdetect */ = { + isa = PBXGroup; + children = ( + 97CFAD0B2F2DB004A8A3BC0B /* objdetect.hpp */, + ); + name = objdetect; + sourceTree = ""; + }; + DCC60D6724B56635AE867535 /* libs */ = { + isa = PBXGroup; + children = ( + AAA97F42C2FE4A31ECFD0585 /* opencv */, + ); + name = libs; + sourceTree = ""; + }; + DD2B5B46F3C951ACDB5A75F0 /* AR2 */ = { + isa = PBXGroup; + children = ( + 97F20BDB0AB952886E41E761 /* config.h */, + 6AA400C56F3B733F2745CEB6 /* coord.h */, + D363B90E27A45FBD9694F154 /* featureSet.h */, + 8115E3F30A9B3F09BA08E59D /* imageFormat.h */, + CCEF89DB1EFB33729187CB32 /* imageSet.h */, + 9EFB64FFBA8E2092A2A81658 /* marker.h */, + 7C67530288E980E0EE66DA3A /* searchPoint.h */, + 0A17F47CA705D34314F9D9EE /* template.h */, + E9A50666D984CCA0F9932C17 /* tracking.h */, + DBCD81E9A9DD37186CEE341F /* util.h */, + ); + name = AR2; + sourceTree = ""; + }; + DF5D380A1A4583A1636503A6 /* detail */ = { + isa = PBXGroup; + children = ( + 37D155721DCC51F3D1DC2E02 /* color_detail.hpp */, + 1C490B8705672F1410388922 /* reduce.hpp */, + 417A0B7154103C22ECC253E8 /* reduce_key_val.hpp */, + C4BA8097B54C90163F99F5C1 /* transform_detail.hpp */, + 2B75A06D9EF1817256BA26F6 /* type_traits_detail.hpp */, + E21FF871B93E31DA43FE7E42 /* vec_distance_detail.hpp */, + ); + name = detail; + sourceTree = ""; + }; + E1353B123A9CD9750FE99DCA /* ofxArtool5 */ = { + isa = PBXGroup; + children = ( + A4EB522F447A248482BFB138 /* src */, + 371C7C765DED66AA23F35C69 /* libs */, + ); + name = ofxArtool5; + sourceTree = ""; + }; + E4328144138ABC890047C5CB /* Products */ = { + isa = PBXGroup; + children = ( + E4328148138ABC890047C5CB /* openFrameworksDebug.a */, + ); + name = Products; + sourceTree = ""; + }; + E4B69B4A0A3A1720003C02F2 = { + isa = PBXGroup; + children = ( + E4B6FCAD0C3E899E008CF71C /* openFrameworks-Info.plist */, + E4EB6923138AFD0F00A09F29 /* Project.xcconfig */, + E4B69E1C0A3A1BDC003C02F2 /* src */, + E4EEC9E9138DF44700A80321 /* openFrameworks */, + BB4B014C10F69532006C3DED /* addons */, + 6948EE371B920CB800B5AC1A /* local_addons */, + E4B69B5B0A3A1756003C02F2 /* artool5exampleDebug.app */, + ); + sourceTree = ""; + }; + E4B69E1C0A3A1BDC003C02F2 /* src */ = { + isa = PBXGroup; + children = ( + E4B69E1D0A3A1BDC003C02F2 /* main.cpp */, + E4B69E1E0A3A1BDC003C02F2 /* ofApp.cpp */, + E4B69E1F0A3A1BDC003C02F2 /* ofApp.h */, + ); + path = src; + sourceTree = SOURCE_ROOT; + }; + E4EEC9E9138DF44700A80321 /* openFrameworks */ = { + isa = PBXGroup; + children = ( + E4EB691F138AFCF100A09F29 /* CoreOF.xcconfig */, + E4328143138ABC890047C5CB /* openFrameworksLib.xcodeproj */, + ); + name = openFrameworks; + sourceTree = ""; + }; + E8C62539B35497B22A589E6D /* opencv */ = { + isa = PBXGroup; + children = ( + E7B80CC0EB7994714340016A /* cv.h */, + 2F465648B7ABB10F10322946 /* cv.hpp */, + 41A55473C0BB857F4961F740 /* cvaux.h */, + 84E02E22D76A6E6ACE6FAB7A /* cvaux.hpp */, + 9E26AC538CE46FA5FFB076E5 /* cvwimage.h */, + 7ED6D6EFE04E5839E10F8E3E /* cxcore.h */, + 8C5B6033A209406858A4F020 /* cxcore.hpp */, + 125F19BE8968F0531BD54AC8 /* cxeigen.hpp */, + D41B817B291B0687CE60F7FE /* cxmisc.h */, + 40558BF6D61AA5A193155C09 /* highgui.h */, + 2D654A2C2B095DBA96FA9EB5 /* ml.h */, + ); + name = opencv; + sourceTree = ""; + }; + ED977EFE7B82B0D53CB5C778 /* superres */ = { + isa = PBXGroup; + children = ( + B09FCFF976DCEACB7C7C8D4E /* optical_flow.hpp */, + C65A89034372885C3F7259F5 /* superres.hpp */, + ); + name = superres; + sourceTree = ""; + }; + EF390536765EAE0B3914B079 /* Eden */ = { + isa = PBXGroup; + children = ( + 13C35E1A5B5BF01EFD26C29E /* Eden.h */, + 0E8B230ABD3E15CB838BC68A /* EdenError.h */, + 8B37D9B1B3905BC34151EEF4 /* EdenGLFont.h */, + 40DC89EA94A2B7E5524E6727 /* EdenMath.h */, + B590852E2273F057FAB540DC /* EdenMessage.h */, + 44B67493290FAB59F2E944BA /* EdenSound.h */, + 8F7BF7F7D3DFE78B2623C882 /* EdenSurfaces.h */, + 5E04ECD8243254906741012F /* EdenTime.h */, + 47807BFDC1FD685020A25205 /* EdenUtil.h */, + 59DC9BAE1FAD8D36CD5F324F /* glm.h */, + D9F0442FA36643AFF7A08438 /* gluttext.h */, + 105C46BD1A7DC856FD49499D /* readtex.h */, + ); + name = Eden; + sourceTree = ""; + }; + F9F05170CB9BDF47DA2B6E6A /* include */ = { + isa = PBXGroup; + children = ( + 737B033AA777B67BA4F8F4D2 /* opencv */, + 0F07FE174552DEF007BF5AD5 /* opencv2 */, + ); + name = include; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + E4B69B5A0A3A1756003C02F2 /* artool5example */ = { + isa = PBXNativeTarget; + buildConfigurationList = E4B69B5F0A3A1757003C02F2 /* Build configuration list for PBXNativeTarget "artool5example" */; + buildPhases = ( + E4B69B580A3A1756003C02F2 /* Sources */, + E4B69B590A3A1756003C02F2 /* Frameworks */, + E4B6FFFD0C3F9AB9008CF71C /* ShellScript */, + E4C2427710CC5ABF004149E2 /* CopyFiles */, + ); + buildRules = ( + ); + dependencies = ( + E4EEB9AC138B136A00A80321 /* PBXTargetDependency */, + ); + name = artool5example; + productName = myOFApp; + productReference = E4B69B5B0A3A1756003C02F2 /* artool5exampleDebug.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + E4B69B4C0A3A1720003C02F2 /* Project object */ = { + isa = PBXProject; + attributes = { + LastUpgradeCheck = 0600; + }; + buildConfigurationList = E4B69B4D0A3A1720003C02F2 /* Build configuration list for PBXProject "artool5example" */; + compatibilityVersion = "Xcode 3.2"; + developmentRegion = English; + hasScannedForEncodings = 0; + knownRegions = ( + English, + Japanese, + French, + German, + ); + mainGroup = E4B69B4A0A3A1720003C02F2; + productRefGroup = E4B69B4A0A3A1720003C02F2; + projectDirPath = ""; + projectReferences = ( + { + ProductGroup = E4328144138ABC890047C5CB /* Products */; + ProjectRef = E4328143138ABC890047C5CB /* openFrameworksLib.xcodeproj */; + }, + ); + projectRoot = ""; + targets = ( + E4B69B5A0A3A1756003C02F2 /* artool5example */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXReferenceProxy section */ + E4328148138ABC890047C5CB /* openFrameworksDebug.a */ = { + isa = PBXReferenceProxy; + fileType = archive.ar; + path = openFrameworksDebug.a; + remoteRef = E4328147138ABC890047C5CB /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; +/* End PBXReferenceProxy section */ + +/* Begin PBXShellScriptBuildPhase section */ + E4B6FFFD0C3F9AB9008CF71C /* ShellScript */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "rsync -aved ../../../libs/fmodex/lib/osx/libfmodex.dylib \"$TARGET_BUILD_DIR/$PRODUCT_NAME.app/Contents/MacOS/\"; install_name_tool -change ./libfmodex.dylib @executable_path/libfmodex.dylib \"$TARGET_BUILD_DIR/$PRODUCT_NAME.app/Contents/MacOS/$PRODUCT_NAME\";\nmkdir -p \"$TARGET_BUILD_DIR/$PRODUCT_NAME.app/Contents/Resources/\"\nrsync -aved \"$ICON_FILE\" \"$TARGET_BUILD_DIR/$PRODUCT_NAME.app/Contents/Resources/\"\nrsync -aved ../../../libs/glut/lib/osx/GLUT.framework \"$TARGET_BUILD_DIR/$PRODUCT_NAME.app/Contents/Frameworks/\"\n"; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + E4B69B580A3A1756003C02F2 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + E4B69E200A3A1BDC003C02F2 /* main.cpp in Sources */, + E4B69E210A3A1BDC003C02F2 /* ofApp.cpp in Sources */, + 250A95BA26587BE85DB0A353 /* ofxCvColorImage.cpp in Sources */, + 14B90CAA1C2B20D3004D0E12 /* ofxARTNftTracker.cpp in Sources */, + 14B90C9F1C2B20A8004D0E12 /* trackingSub.c in Sources */, + 1D5F3298C2FA073628012944 /* ofxCvContourFinder.cpp in Sources */, + 169D3C72FDE6C5590A1616F5 /* ofxCvFloatImage.cpp in Sources */, + 14B90CA91C2B20D3004D0E12 /* ofxARTGenericTracker.cpp in Sources */, + 14B90CA21C2B20B8004D0E12 /* ARMarkerNFT.c in Sources */, + FB09C6B2A1DA0EA217240CB8 /* ofxCvGrayscaleImage.cpp in Sources */, + 14B90CAB1C2B20D3004D0E12 /* ofxARTPattern.cpp in Sources */, + E212C821D1064B92DD953A42 /* ofxCvHaarFinder.cpp in Sources */, + 63020F16C7E8DED980111241 /* ofxCvImage.cpp in Sources */, + D3301F6A0B43BB293ED97C1D /* ofxCvShortImage.cpp in Sources */, + 63B57AC5BF4EF088491E0317 /* ofxXmlSettings.cpp in Sources */, + 933A2227713C720CEFF80FD9 /* tinyxml.cpp in Sources */, + 9D44DC88EF9E7991B4A09951 /* tinyxmlerror.cpp in Sources */, + 5A4349E9754D6FA14C0F2A3A /* tinyxmlparser.cpp in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + E4EEB9AC138B136A00A80321 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = openFrameworks; + targetProxy = E4EEB9AB138B136A00A80321 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin XCBuildConfiguration section */ + E4B69B4E0A3A1720003C02F2 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = E4EB6923138AFD0F00A09F29 /* Project.xcconfig */; + buildSettings = { + CONFIGURATION_BUILD_DIR = "$(SRCROOT)/bin/"; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + GCC_AUTO_VECTORIZATION = YES; + GCC_ENABLE_SSE3_EXTENSIONS = YES; + GCC_ENABLE_SUPPLEMENTAL_SSE3_INSTRUCTIONS = YES; + GCC_INLINES_ARE_PRIVATE_EXTERN = NO; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_SYMBOLS_PRIVATE_EXTERN = NO; + GCC_WARN_ABOUT_DEPRECATED_FUNCTIONS = YES; + GCC_WARN_ABOUT_INVALID_OFFSETOF_MACRO = NO; + GCC_WARN_ALLOW_INCOMPLETE_PROTOCOL = NO; + GCC_WARN_UNINITIALIZED_AUTOS = NO; + GCC_WARN_UNUSED_VALUE = NO; + GCC_WARN_UNUSED_VARIABLE = NO; + HEADER_SEARCH_PATHS = ( + "$(OF_CORE_HEADERS)", + src, + ../../../addons/ofxArtool5/libs, + ../../../addons/ofxArtool5/libs/include, + ../../../addons/ofxArtool5/libs/include/AR, + ../../../addons/ofxArtool5/libs/include/AR/sys, + ../../../addons/ofxArtool5/libs/include/AR2, + ../../../addons/ofxArtool5/libs/include/ARWrapper, + ../../../addons/ofxArtool5/libs/include/Eden, + ../../../addons/ofxArtool5/libs/include/KPM, + ../../../addons/ofxArtool5/libs/include/android, + ../../../addons/ofxArtool5/libs/include/ios511, + ../../../addons/ofxArtool5/libs/include/ios511/OpenThreads, + ../../../addons/ofxArtool5/libs/include/ios511/freetype2, + ../../../addons/ofxArtool5/libs/include/ios511/freetype2/freetype, + ../../../addons/ofxArtool5/libs/include/ios511/freetype2/freetype/config, + ../../../addons/ofxArtool5/libs/include/ios511/osg, + ../../../addons/ofxArtool5/libs/include/ios511/osgAnimation, + ../../../addons/ofxArtool5/libs/include/ios511/osgDB, + ../../../addons/ofxArtool5/libs/include/ios511/osgFX, + ../../../addons/ofxArtool5/libs/include/ios511/osgGA, + ../../../addons/ofxArtool5/libs/include/ios511/osgManipulator, + ../../../addons/ofxArtool5/libs/include/ios511/osgParticle, + ../../../addons/ofxArtool5/libs/include/ios511/osgPresentation, + ../../../addons/ofxArtool5/libs/include/ios511/osgShadow, + ../../../addons/ofxArtool5/libs/include/ios511/osgSim, + ../../../addons/ofxArtool5/libs/include/ios511/osgTerrain, + ../../../addons/ofxArtool5/libs/include/ios511/osgText, + ../../../addons/ofxArtool5/libs/include/ios511/osgUtil, + ../../../addons/ofxArtool5/libs/include/ios511/osgViewer, + ../../../addons/ofxArtool5/libs/include/ios511/osgViewer/api, + ../../../addons/ofxArtool5/libs/include/ios511/osgViewer/api/IOS, + ../../../addons/ofxArtool5/libs/include/ios511/osgVolume, + ../../../addons/ofxArtool5/libs/include/ios511/osgWidget, + "../../../addons/ofxArtool5/libs/include/linux-i686", + "../../../addons/ofxArtool5/libs/include/linux-i686/opencv", + "../../../addons/ofxArtool5/libs/include/linux-i686/opencv2", + "../../../addons/ofxArtool5/libs/include/linux-i686/opencv2/calib3d", + "../../../addons/ofxArtool5/libs/include/linux-i686/opencv2/contrib", + "../../../addons/ofxArtool5/libs/include/linux-i686/opencv2/core", + "../../../addons/ofxArtool5/libs/include/linux-i686/opencv2/features2d", + "../../../addons/ofxArtool5/libs/include/linux-i686/opencv2/flann", + "../../../addons/ofxArtool5/libs/include/linux-i686/opencv2/gpu", + "../../../addons/ofxArtool5/libs/include/linux-i686/opencv2/gpu/device", + "../../../addons/ofxArtool5/libs/include/linux-i686/opencv2/gpu/device/detail", + "../../../addons/ofxArtool5/libs/include/linux-i686/opencv2/highgui", + "../../../addons/ofxArtool5/libs/include/linux-i686/opencv2/imgproc", + "../../../addons/ofxArtool5/libs/include/linux-i686/opencv2/legacy", + "../../../addons/ofxArtool5/libs/include/linux-i686/opencv2/ml", + "../../../addons/ofxArtool5/libs/include/linux-i686/opencv2/nonfree", + "../../../addons/ofxArtool5/libs/include/linux-i686/opencv2/objdetect", + "../../../addons/ofxArtool5/libs/include/linux-i686/opencv2/photo", + "../../../addons/ofxArtool5/libs/include/linux-i686/opencv2/stitching", + "../../../addons/ofxArtool5/libs/include/linux-i686/opencv2/stitching/detail", + "../../../addons/ofxArtool5/libs/include/linux-i686/opencv2/superres", + "../../../addons/ofxArtool5/libs/include/linux-i686/opencv2/video", + "../../../addons/ofxArtool5/libs/include/linux-i686/opencv2/videostab", + "../../../addons/ofxArtool5/libs/include/linux-x86_64", + "../../../addons/ofxArtool5/libs/include/linux-x86_64/opencv", + "../../../addons/ofxArtool5/libs/include/linux-x86_64/opencv2", + "../../../addons/ofxArtool5/libs/include/linux-x86_64/opencv2/calib3d", + "../../../addons/ofxArtool5/libs/include/linux-x86_64/opencv2/contrib", + "../../../addons/ofxArtool5/libs/include/linux-x86_64/opencv2/core", + "../../../addons/ofxArtool5/libs/include/linux-x86_64/opencv2/features2d", + "../../../addons/ofxArtool5/libs/include/linux-x86_64/opencv2/flann", + "../../../addons/ofxArtool5/libs/include/linux-x86_64/opencv2/gpu", + "../../../addons/ofxArtool5/libs/include/linux-x86_64/opencv2/gpu/device", + "../../../addons/ofxArtool5/libs/include/linux-x86_64/opencv2/gpu/device/detail", + "../../../addons/ofxArtool5/libs/include/linux-x86_64/opencv2/highgui", + "../../../addons/ofxArtool5/libs/include/linux-x86_64/opencv2/imgproc", + "../../../addons/ofxArtool5/libs/include/linux-x86_64/opencv2/legacy", + "../../../addons/ofxArtool5/libs/include/linux-x86_64/opencv2/ml", + "../../../addons/ofxArtool5/libs/include/linux-x86_64/opencv2/nonfree", + "../../../addons/ofxArtool5/libs/include/linux-x86_64/opencv2/objdetect", + "../../../addons/ofxArtool5/libs/include/linux-x86_64/opencv2/photo", + "../../../addons/ofxArtool5/libs/include/linux-x86_64/opencv2/stitching", + "../../../addons/ofxArtool5/libs/include/linux-x86_64/opencv2/stitching/detail", + "../../../addons/ofxArtool5/libs/include/linux-x86_64/opencv2/superres", + "../../../addons/ofxArtool5/libs/include/linux-x86_64/opencv2/video", + "../../../addons/ofxArtool5/libs/include/linux-x86_64/opencv2/videostab", + "../../../addons/ofxArtool5/libs/include/macosx-universal", + "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv", + "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2", + "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/calib3d", + "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/contrib", + "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/core", + "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/features2d", + "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/flann", + "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/gpu", + "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/gpu/device", + "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/gpu/device/detail", + "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/highgui", + "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/imgproc", + "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/legacy", + "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/ml", + "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/nonfree", + "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/objdetect", + "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/ocl", + "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/photo", + "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/stitching", + "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/stitching/detail", + "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/superres", + "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/ts", + "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/video", + "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/videostab", + "../../../addons/ofxArtool5/libs/include/win32-i386", + "../../../addons/ofxArtool5/libs/include/win64-x64", + "../../../addons/ofxArtool5/libs/include/winrt-w8_1-arm", + "../../../addons/ofxArtool5/libs/include/winrt-w8_1-x64", + "../../../addons/ofxArtool5/libs/include/winrt-w8_1-x86", + "../../../addons/ofxArtool5/libs/include/winrt-wp8_1-arm", + "../../../addons/ofxArtool5/libs/include/winrt-wp8_1-x86", + ../../../addons/ofxArtool5/libs/lib, + ../../../addons/ofxArtool5/src, + ../../../addons/ofxOpenCv/libs, + ../../../addons/ofxOpenCv/libs/opencv, + ../../../addons/ofxOpenCv/libs/opencv/include, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/calib3d, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/contrib, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/core, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/features2d, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/flann, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/gpu, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/gpu/device, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/gpu/device/detail, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/highgui, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/imgproc, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/legacy, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/ml, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/nonfree, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/objdetect, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/photo, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/stitching, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/stitching/detail, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/superres, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/ts, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/video, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/videostab, + ../../../addons/ofxOpenCv/libs/opencv/lib, + ../../../addons/ofxOpenCv/libs/opencv/lib/emscripten, + ../../../addons/ofxOpenCv/libs/opencv/lib/osx, + ../../../addons/ofxOpenCv/libs/opencv/license, + ../../../addons/ofxOpenCv/src, + ../../../addons/ofxXmlSettings/libs, + ../../../addons/ofxXmlSettings/src, + ); + MACOSX_DEPLOYMENT_TARGET = 10.8; + ONLY_ACTIVE_ARCH = YES; + OTHER_CPLUSPLUSFLAGS = ( + "-D__MACOSX_CORE__", + "-mtune=native", + ); + OTHER_LDFLAGS = ( + "$(OF_CORE_FRAMEWORKS)", + "$(OF_CORE_LIBS)", + ../../../addons/ofxOpenCv/libs/opencv/lib/osx/opencv.a, + ); + SDKROOT = macosx; + }; + name = Debug; + }; + E4B69B4F0A3A1720003C02F2 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = E4EB6923138AFD0F00A09F29 /* Project.xcconfig */; + buildSettings = { + CONFIGURATION_BUILD_DIR = "$(SRCROOT)/bin/"; + COPY_PHASE_STRIP = YES; + DEAD_CODE_STRIPPING = YES; + GCC_AUTO_VECTORIZATION = YES; + GCC_ENABLE_SSE3_EXTENSIONS = YES; + GCC_ENABLE_SUPPLEMENTAL_SSE3_INSTRUCTIONS = YES; + GCC_INLINES_ARE_PRIVATE_EXTERN = NO; + GCC_OPTIMIZATION_LEVEL = 3; + GCC_SYMBOLS_PRIVATE_EXTERN = NO; + GCC_UNROLL_LOOPS = YES; + GCC_WARN_ABOUT_DEPRECATED_FUNCTIONS = YES; + GCC_WARN_ABOUT_INVALID_OFFSETOF_MACRO = NO; + GCC_WARN_ALLOW_INCOMPLETE_PROTOCOL = NO; + GCC_WARN_UNINITIALIZED_AUTOS = NO; + GCC_WARN_UNUSED_VALUE = NO; + GCC_WARN_UNUSED_VARIABLE = NO; + HEADER_SEARCH_PATHS = ( + "$(OF_CORE_HEADERS)", + src, + ../../../addons/ofxArtool5/libs, + ../../../addons/ofxArtool5/libs/include, + ../../../addons/ofxArtool5/libs/include/AR, + ../../../addons/ofxArtool5/libs/include/AR/sys, + ../../../addons/ofxArtool5/libs/include/AR2, + ../../../addons/ofxArtool5/libs/include/ARWrapper, + ../../../addons/ofxArtool5/libs/include/Eden, + ../../../addons/ofxArtool5/libs/include/KPM, + ../../../addons/ofxArtool5/libs/include/android, + ../../../addons/ofxArtool5/libs/include/ios511, + ../../../addons/ofxArtool5/libs/include/ios511/OpenThreads, + ../../../addons/ofxArtool5/libs/include/ios511/freetype2, + ../../../addons/ofxArtool5/libs/include/ios511/freetype2/freetype, + ../../../addons/ofxArtool5/libs/include/ios511/freetype2/freetype/config, + ../../../addons/ofxArtool5/libs/include/ios511/osg, + ../../../addons/ofxArtool5/libs/include/ios511/osgAnimation, + ../../../addons/ofxArtool5/libs/include/ios511/osgDB, + ../../../addons/ofxArtool5/libs/include/ios511/osgFX, + ../../../addons/ofxArtool5/libs/include/ios511/osgGA, + ../../../addons/ofxArtool5/libs/include/ios511/osgManipulator, + ../../../addons/ofxArtool5/libs/include/ios511/osgParticle, + ../../../addons/ofxArtool5/libs/include/ios511/osgPresentation, + ../../../addons/ofxArtool5/libs/include/ios511/osgShadow, + ../../../addons/ofxArtool5/libs/include/ios511/osgSim, + ../../../addons/ofxArtool5/libs/include/ios511/osgTerrain, + ../../../addons/ofxArtool5/libs/include/ios511/osgText, + ../../../addons/ofxArtool5/libs/include/ios511/osgUtil, + ../../../addons/ofxArtool5/libs/include/ios511/osgViewer, + ../../../addons/ofxArtool5/libs/include/ios511/osgViewer/api, + ../../../addons/ofxArtool5/libs/include/ios511/osgViewer/api/IOS, + ../../../addons/ofxArtool5/libs/include/ios511/osgVolume, + ../../../addons/ofxArtool5/libs/include/ios511/osgWidget, + "../../../addons/ofxArtool5/libs/include/linux-i686", + "../../../addons/ofxArtool5/libs/include/linux-i686/opencv", + "../../../addons/ofxArtool5/libs/include/linux-i686/opencv2", + "../../../addons/ofxArtool5/libs/include/linux-i686/opencv2/calib3d", + "../../../addons/ofxArtool5/libs/include/linux-i686/opencv2/contrib", + "../../../addons/ofxArtool5/libs/include/linux-i686/opencv2/core", + "../../../addons/ofxArtool5/libs/include/linux-i686/opencv2/features2d", + "../../../addons/ofxArtool5/libs/include/linux-i686/opencv2/flann", + "../../../addons/ofxArtool5/libs/include/linux-i686/opencv2/gpu", + "../../../addons/ofxArtool5/libs/include/linux-i686/opencv2/gpu/device", + "../../../addons/ofxArtool5/libs/include/linux-i686/opencv2/gpu/device/detail", + "../../../addons/ofxArtool5/libs/include/linux-i686/opencv2/highgui", + "../../../addons/ofxArtool5/libs/include/linux-i686/opencv2/imgproc", + "../../../addons/ofxArtool5/libs/include/linux-i686/opencv2/legacy", + "../../../addons/ofxArtool5/libs/include/linux-i686/opencv2/ml", + "../../../addons/ofxArtool5/libs/include/linux-i686/opencv2/nonfree", + "../../../addons/ofxArtool5/libs/include/linux-i686/opencv2/objdetect", + "../../../addons/ofxArtool5/libs/include/linux-i686/opencv2/photo", + "../../../addons/ofxArtool5/libs/include/linux-i686/opencv2/stitching", + "../../../addons/ofxArtool5/libs/include/linux-i686/opencv2/stitching/detail", + "../../../addons/ofxArtool5/libs/include/linux-i686/opencv2/superres", + "../../../addons/ofxArtool5/libs/include/linux-i686/opencv2/video", + "../../../addons/ofxArtool5/libs/include/linux-i686/opencv2/videostab", + "../../../addons/ofxArtool5/libs/include/linux-x86_64", + "../../../addons/ofxArtool5/libs/include/linux-x86_64/opencv", + "../../../addons/ofxArtool5/libs/include/linux-x86_64/opencv2", + "../../../addons/ofxArtool5/libs/include/linux-x86_64/opencv2/calib3d", + "../../../addons/ofxArtool5/libs/include/linux-x86_64/opencv2/contrib", + "../../../addons/ofxArtool5/libs/include/linux-x86_64/opencv2/core", + "../../../addons/ofxArtool5/libs/include/linux-x86_64/opencv2/features2d", + "../../../addons/ofxArtool5/libs/include/linux-x86_64/opencv2/flann", + "../../../addons/ofxArtool5/libs/include/linux-x86_64/opencv2/gpu", + "../../../addons/ofxArtool5/libs/include/linux-x86_64/opencv2/gpu/device", + "../../../addons/ofxArtool5/libs/include/linux-x86_64/opencv2/gpu/device/detail", + "../../../addons/ofxArtool5/libs/include/linux-x86_64/opencv2/highgui", + "../../../addons/ofxArtool5/libs/include/linux-x86_64/opencv2/imgproc", + "../../../addons/ofxArtool5/libs/include/linux-x86_64/opencv2/legacy", + "../../../addons/ofxArtool5/libs/include/linux-x86_64/opencv2/ml", + "../../../addons/ofxArtool5/libs/include/linux-x86_64/opencv2/nonfree", + "../../../addons/ofxArtool5/libs/include/linux-x86_64/opencv2/objdetect", + "../../../addons/ofxArtool5/libs/include/linux-x86_64/opencv2/photo", + "../../../addons/ofxArtool5/libs/include/linux-x86_64/opencv2/stitching", + "../../../addons/ofxArtool5/libs/include/linux-x86_64/opencv2/stitching/detail", + "../../../addons/ofxArtool5/libs/include/linux-x86_64/opencv2/superres", + "../../../addons/ofxArtool5/libs/include/linux-x86_64/opencv2/video", + "../../../addons/ofxArtool5/libs/include/linux-x86_64/opencv2/videostab", + "../../../addons/ofxArtool5/libs/include/macosx-universal", + "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv", + "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2", + "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/calib3d", + "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/contrib", + "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/core", + "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/features2d", + "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/flann", + "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/gpu", + "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/gpu/device", + "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/gpu/device/detail", + "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/highgui", + "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/imgproc", + "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/legacy", + "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/ml", + "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/nonfree", + "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/objdetect", + "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/ocl", + "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/photo", + "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/stitching", + "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/stitching/detail", + "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/superres", + "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/ts", + "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/video", + "../../../addons/ofxArtool5/libs/include/macosx-universal/opencv2/videostab", + "../../../addons/ofxArtool5/libs/include/win32-i386", + "../../../addons/ofxArtool5/libs/include/win64-x64", + "../../../addons/ofxArtool5/libs/include/winrt-w8_1-arm", + "../../../addons/ofxArtool5/libs/include/winrt-w8_1-x64", + "../../../addons/ofxArtool5/libs/include/winrt-w8_1-x86", + "../../../addons/ofxArtool5/libs/include/winrt-wp8_1-arm", + "../../../addons/ofxArtool5/libs/include/winrt-wp8_1-x86", + ../../../addons/ofxArtool5/libs/lib, + ../../../addons/ofxArtool5/src, + ../../../addons/ofxOpenCv/libs, + ../../../addons/ofxOpenCv/libs/opencv, + ../../../addons/ofxOpenCv/libs/opencv/include, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/calib3d, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/contrib, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/core, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/features2d, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/flann, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/gpu, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/gpu/device, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/gpu/device/detail, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/highgui, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/imgproc, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/legacy, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/ml, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/nonfree, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/objdetect, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/photo, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/stitching, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/stitching/detail, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/superres, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/ts, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/video, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/videostab, + ../../../addons/ofxOpenCv/libs/opencv/lib, + ../../../addons/ofxOpenCv/libs/opencv/lib/emscripten, + ../../../addons/ofxOpenCv/libs/opencv/lib/osx, + ../../../addons/ofxOpenCv/libs/opencv/license, + ../../../addons/ofxOpenCv/src, + ../../../addons/ofxXmlSettings/libs, + ../../../addons/ofxXmlSettings/src, + ); + MACOSX_DEPLOYMENT_TARGET = 10.8; + OTHER_CPLUSPLUSFLAGS = ( + "-D__MACOSX_CORE__", + "-mtune=native", + ); + OTHER_LDFLAGS = ( + "$(OF_CORE_FRAMEWORKS)", + "$(OF_CORE_LIBS)", + ../../../addons/ofxOpenCv/libs/opencv/lib/osx/opencv.a, + ); + SDKROOT = macosx; + }; + name = Release; + }; + E4B69B600A3A1757003C02F2 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = E4EB6923138AFD0F00A09F29 /* Project.xcconfig */; + buildSettings = { + COMBINE_HIDPI_IMAGES = YES; + COPY_PHASE_STRIP = NO; + FRAMEWORK_SEARCH_PATHS = ( + "$(inherited)", + "$(FRAMEWORK_SEARCH_PATHS_QUOTED_FOR_TARGET_1)", + ); + FRAMEWORK_SEARCH_PATHS_QUOTED_FOR_TARGET_1 = "\"$(SRCROOT)/../../../libs/glut/lib/osx\""; + GCC_DYNAMIC_NO_PIC = NO; + GCC_GENERATE_DEBUGGING_SYMBOLS = YES; + GCC_MODEL_TUNING = NONE; + HEADER_SEARCH_PATHS = ( + "$(OF_CORE_HEADERS)", + src, + ../../../addons/ofxArtool5/libs, + ../../../addons/ofxArtool5/libs/include, + ../../../addons/ofxArtool5/libs/include/AR, + ../../../addons/ofxArtool5/libs/include/AR/sys, + ../../../addons/ofxArtool5/libs/include/AR2, + ../../../addons/ofxArtool5/libs/include/ARWrapper, + ../../../addons/ofxArtool5/libs/include/Eden, + ../../../addons/ofxArtool5/libs/include/KPM, + "../../../addons/ofxArtool5/libs/include/macosx-universal", + ../../../addons/ofxArtool5/libs/lib, + ../../../addons/ofxArtool5/src, + ../../../addons/ofxOpenCv/libs, + ../../../addons/ofxOpenCv/libs/opencv, + ../../../addons/ofxOpenCv/libs/opencv/include, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/calib3d, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/contrib, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/core, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/features2d, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/flann, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/gpu, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/gpu/device, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/gpu/device/detail, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/highgui, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/imgproc, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/legacy, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/ml, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/nonfree, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/objdetect, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/photo, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/stitching, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/stitching/detail, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/superres, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/ts, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/video, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/videostab, + ../../../addons/ofxOpenCv/libs/opencv/lib, + ../../../addons/ofxOpenCv/libs/opencv/lib/emscripten, + ../../../addons/ofxOpenCv/libs/opencv/lib/osx, + ../../../addons/ofxOpenCv/libs/opencv/license, + ../../../addons/ofxOpenCv/src, + ../../../addons/ofxXmlSettings/libs, + ../../../addons/ofxXmlSettings/src, + ); + ICON = "$(ICON_NAME_DEBUG)"; + ICON_FILE = "$(ICON_FILE_PATH)$(ICON)"; + INFOPLIST_FILE = "openFrameworks-Info.plist"; + INSTALL_PATH = "$(HOME)/Applications"; + LIBRARY_SEARCH_PATHS = ( + "$(inherited)", + "$(SYSTEM_APPS_DIR)/OF/of_v0.9.0_osx_release/addons/ofxArtool5/libs/lib", + ); + OTHER_LDFLAGS = ( + "$(OF_CORE_FRAMEWORKS)", + "$(OF_CORE_LIBS)", + ../../../addons/ofxOpenCv/libs/opencv/lib/osx/opencv.a, + ); + PRODUCT_NAME = "$(TARGET_NAME)Debug"; + WRAPPER_EXTENSION = app; + }; + name = Debug; + }; + E4B69B610A3A1757003C02F2 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = E4EB6923138AFD0F00A09F29 /* Project.xcconfig */; + buildSettings = { + COMBINE_HIDPI_IMAGES = YES; + COPY_PHASE_STRIP = YES; + FRAMEWORK_SEARCH_PATHS = ( + "$(inherited)", + "$(FRAMEWORK_SEARCH_PATHS_QUOTED_FOR_TARGET_1)", + ); + FRAMEWORK_SEARCH_PATHS_QUOTED_FOR_TARGET_1 = "\"$(SRCROOT)/../../../libs/glut/lib/osx\""; + GCC_GENERATE_DEBUGGING_SYMBOLS = YES; + GCC_MODEL_TUNING = NONE; + HEADER_SEARCH_PATHS = ( + "$(OF_CORE_HEADERS)", + src, + ../../../addons/ofxArtool5/libs, + ../../../addons/ofxArtool5/libs/include, + ../../../addons/ofxArtool5/libs/include/AR, + ../../../addons/ofxArtool5/libs/include/AR/sys, + ../../../addons/ofxArtool5/libs/include/AR2, + ../../../addons/ofxArtool5/libs/include/ARWrapper, + ../../../addons/ofxArtool5/libs/include/Eden, + ../../../addons/ofxArtool5/libs/include/KPM, + "../../../addons/ofxArtool5/libs/include/macosx-universal", + ../../../addons/ofxArtool5/libs/lib, + ../../../addons/ofxArtool5/src, + ../../../addons/ofxOpenCv/libs, + ../../../addons/ofxOpenCv/libs/opencv, + ../../../addons/ofxOpenCv/libs/opencv/include, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/calib3d, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/contrib, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/core, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/features2d, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/flann, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/gpu, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/gpu/device, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/gpu/device/detail, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/highgui, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/imgproc, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/legacy, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/ml, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/nonfree, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/objdetect, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/photo, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/stitching, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/stitching/detail, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/superres, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/ts, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/video, + ../../../addons/ofxOpenCv/libs/opencv/include/opencv2/videostab, + ../../../addons/ofxOpenCv/libs/opencv/lib, + ../../../addons/ofxOpenCv/libs/opencv/lib/emscripten, + ../../../addons/ofxOpenCv/libs/opencv/lib/osx, + ../../../addons/ofxOpenCv/libs/opencv/license, + ../../../addons/ofxOpenCv/src, + ../../../addons/ofxXmlSettings/libs, + ../../../addons/ofxXmlSettings/src, + ); + ICON = "$(ICON_NAME_RELEASE)"; + ICON_FILE = "$(ICON_FILE_PATH)$(ICON)"; + INFOPLIST_FILE = "openFrameworks-Info.plist"; + INSTALL_PATH = "$(HOME)/Applications"; + LIBRARY_SEARCH_PATHS = ( + "$(inherited)", + "$(SYSTEM_APPS_DIR)/OF/of_v0.9.0_osx_release/addons/ofxArtool5/libs/lib", + ); + OTHER_LDFLAGS = ( + "$(OF_CORE_FRAMEWORKS)", + "$(OF_CORE_LIBS)", + ../../../addons/ofxOpenCv/libs/opencv/lib/osx/opencv.a, + ); + PRODUCT_NAME = "$(TARGET_NAME)"; + WRAPPER_EXTENSION = app; + baseConfigurationReference = E4EB6923138AFD0F00A09F29; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + E4B69B4D0A3A1720003C02F2 /* Build configuration list for PBXProject "artool5example" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + E4B69B4E0A3A1720003C02F2 /* Debug */, + E4B69B4F0A3A1720003C02F2 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + E4B69B5F0A3A1757003C02F2 /* Build configuration list for PBXNativeTarget "artool5example" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + E4B69B600A3A1757003C02F2 /* Debug */, + E4B69B610A3A1757003C02F2 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = E4B69B4C0A3A1720003C02F2 /* Project object */; +} diff --git a/artool5NFTexample/artool5example.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/artool5NFTexample/artool5example.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..bf43b34 --- /dev/null +++ b/artool5NFTexample/artool5example.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/artool5NFTexample/artool5example.xcodeproj/project.xcworkspace/xcuserdata/nausea.xcuserdatad/UserInterfaceState.xcuserstate b/artool5NFTexample/artool5example.xcodeproj/project.xcworkspace/xcuserdata/nausea.xcuserdatad/UserInterfaceState.xcuserstate new file mode 100644 index 0000000..8ebde41 Binary files /dev/null and b/artool5NFTexample/artool5example.xcodeproj/project.xcworkspace/xcuserdata/nausea.xcuserdatad/UserInterfaceState.xcuserstate differ diff --git a/artool5NFTexample/artool5example.xcodeproj/xcshareddata/xcschemes/artool5example Debug.xcscheme b/artool5NFTexample/artool5example.xcodeproj/xcshareddata/xcschemes/artool5example Debug.xcscheme new file mode 100644 index 0000000..1500b9a --- /dev/null +++ b/artool5NFTexample/artool5example.xcodeproj/xcshareddata/xcschemes/artool5example Debug.xcscheme @@ -0,0 +1,86 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/artool5NFTexample/artool5example.xcodeproj/xcshareddata/xcschemes/artool5example Release.xcscheme b/artool5NFTexample/artool5example.xcodeproj/xcshareddata/xcschemes/artool5example Release.xcscheme new file mode 100644 index 0000000..59d3810 --- /dev/null +++ b/artool5NFTexample/artool5example.xcodeproj/xcshareddata/xcschemes/artool5example Release.xcscheme @@ -0,0 +1,86 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/artool5NFTexample/artool5example.xcodeproj/xcuserdata/nausea.xcuserdatad/xcschemes/xcschememanagement.plist b/artool5NFTexample/artool5example.xcodeproj/xcuserdata/nausea.xcuserdatad/xcschemes/xcschememanagement.plist new file mode 100644 index 0000000..13dfb6e --- /dev/null +++ b/artool5NFTexample/artool5example.xcodeproj/xcuserdata/nausea.xcuserdatad/xcschemes/xcschememanagement.plist @@ -0,0 +1,14 @@ + + + + + SuppressBuildableAutocreation + + E4B69B5A0A3A1756003C02F2 + + primary + + + + + diff --git a/artool5NFTexample/bin/data/ARTdata/camera_para.dat b/artool5NFTexample/bin/data/ARTdata/camera_para.dat new file mode 100755 index 0000000..73450c7 Binary files /dev/null and b/artool5NFTexample/bin/data/ARTdata/camera_para.dat differ diff --git a/artool5NFTexample/bin/data/ARTdata/custom.dat b/artool5NFTexample/bin/data/ARTdata/custom.dat new file mode 100644 index 0000000..3e474b2 Binary files /dev/null and b/artool5NFTexample/bin/data/ARTdata/custom.dat differ diff --git a/artool5NFTexample/bin/data/ARTdata/markers.dat b/artool5NFTexample/bin/data/ARTdata/markers.dat new file mode 100755 index 0000000..2d20c1e --- /dev/null +++ b/artool5NFTexample/bin/data/ARTdata/markers.dat @@ -0,0 +1,18 @@ +# Number of markers +1 + +# Entries for each marker. Format is: +# +# Name of pattern file (relative to this file) +# Marker type (SINGLE) +# Marker width in millimetres (floating point number) +# Optional tokens: +# FILTER [x] Enable pose estimate filtering for the preceding marker +# x (optional) specifies the cutoff frequency. Default +# value is AR_FILTER_TRANS_MAT_CUTOFF_FREQ_DEFAULT, which +# at time of writing, equals 5.0. +# A blank line + +pinball +NFT +FILTER 15.0 diff --git a/artool5NFTexample/bin/data/ARTdata/objects.dat b/artool5NFTexample/bin/data/ARTdata/objects.dat new file mode 100755 index 0000000..a092cbb --- /dev/null +++ b/artool5NFTexample/bin/data/ARTdata/objects.dat @@ -0,0 +1,14 @@ +2 + +../OSG/axes.osg +0.0 0.0 0.0 +0.0 1.0 0.0 0.0 +40.0 40.0 40.0 +MARKER 1 +LIGHTING 0 + +../OSG/p51d-jw-animated.osg +4.5 118.25 30.0 +90.0 1.0 0.0 0.0 +25.0 25.0 25.0 +MARKER 1 diff --git a/artool5NFTexample/bin/data/ARTdata/pinball.fset b/artool5NFTexample/bin/data/ARTdata/pinball.fset new file mode 100755 index 0000000..586f7bf Binary files /dev/null and b/artool5NFTexample/bin/data/ARTdata/pinball.fset differ diff --git a/artool5NFTexample/bin/data/ARTdata/pinball.fset3 b/artool5NFTexample/bin/data/ARTdata/pinball.fset3 new file mode 100755 index 0000000..0291b4a Binary files /dev/null and b/artool5NFTexample/bin/data/ARTdata/pinball.fset3 differ diff --git a/artool5NFTexample/bin/data/ARTdata/pinball.iset b/artool5NFTexample/bin/data/ARTdata/pinball.iset new file mode 100755 index 0000000..5d22898 Binary files /dev/null and b/artool5NFTexample/bin/data/ARTdata/pinball.iset differ diff --git a/artool5NFTexample/bin/pinball.jpg b/artool5NFTexample/bin/pinball.jpg new file mode 100755 index 0000000..d1444ad Binary files /dev/null and b/artool5NFTexample/bin/pinball.jpg differ diff --git a/artool5NFTexample/config.make b/artool5NFTexample/config.make new file mode 100644 index 0000000..df10f64 --- /dev/null +++ b/artool5NFTexample/config.make @@ -0,0 +1,142 @@ +################################################################################ +# CONFIGURE PROJECT MAKEFILE (optional) +# This file is where we make project specific configurations. +################################################################################ + +################################################################################ +# OF ROOT +# The location of your root openFrameworks installation +# (default) OF_ROOT = ../../.. +################################################################################ +# OF_ROOT = ../../.. + +################################################################################ +# PROJECT ROOT +# The location of the project - a starting place for searching for files +# (default) PROJECT_ROOT = . (this directory) +# +################################################################################ +# PROJECT_ROOT = . + +################################################################################ +# PROJECT SPECIFIC CHECKS +# This is a project defined section to create internal makefile flags to +# conditionally enable or disable the addition of various features within +# this makefile. For instance, if you want to make changes based on whether +# GTK is installed, one might test that here and create a variable to check. +################################################################################ +# None + +################################################################################ +# PROJECT EXTERNAL SOURCE PATHS +# These are fully qualified paths that are not within the PROJECT_ROOT folder. +# Like source folders in the PROJECT_ROOT, these paths are subject to +# exlclusion via the PROJECT_EXLCUSIONS list. +# +# (default) PROJECT_EXTERNAL_SOURCE_PATHS = (blank) +# +# Note: Leave a leading space when adding list items with the += operator +################################################################################ +# PROJECT_EXTERNAL_SOURCE_PATHS = + +################################################################################ +# PROJECT EXCLUSIONS +# These makefiles assume that all folders in your current project directory +# and any listed in the PROJECT_EXTERNAL_SOURCH_PATHS are are valid locations +# to look for source code. The any folders or files that match any of the +# items in the PROJECT_EXCLUSIONS list below will be ignored. +# +# Each item in the PROJECT_EXCLUSIONS list will be treated as a complete +# string unless teh user adds a wildcard (%) operator to match subdirectories. +# GNU make only allows one wildcard for matching. The second wildcard (%) is +# treated literally. +# +# (default) PROJECT_EXCLUSIONS = (blank) +# +# Will automatically exclude the following: +# +# $(PROJECT_ROOT)/bin% +# $(PROJECT_ROOT)/obj% +# $(PROJECT_ROOT)/%.xcodeproj +# +# Note: Leave a leading space when adding list items with the += operator +################################################################################ +# PROJECT_EXCLUSIONS = + +################################################################################ +# PROJECT LINKER FLAGS +# These flags will be sent to the linker when compiling the executable. +# +# (default) PROJECT_LDFLAGS = -Wl,-rpath=./libs +# +# Note: Leave a leading space when adding list items with the += operator +################################################################################ + +# Currently, shared libraries that are needed are copied to the +# $(PROJECT_ROOT)/bin/libs directory. The following LDFLAGS tell the linker to +# add a runtime path to search for those shared libraries, since they aren't +# incorporated directly into the final executable application binary. +# TODO: should this be a default setting? +# PROJECT_LDFLAGS=-Wl,-rpath=./libs + +################################################################################ +# PROJECT DEFINES +# Create a space-delimited list of DEFINES. The list will be converted into +# CFLAGS with the "-D" flag later in the makefile. +# +# (default) PROJECT_DEFINES = (blank) +# +# Note: Leave a leading space when adding list items with the += operator +################################################################################ +# PROJECT_DEFINES = + +################################################################################ +# PROJECT CFLAGS +# This is a list of fully qualified CFLAGS required when compiling for this +# project. These CFLAGS will be used IN ADDITION TO the PLATFORM_CFLAGS +# defined in your platform specific core configuration files. These flags are +# presented to the compiler BEFORE the PROJECT_OPTIMIZATION_CFLAGS below. +# +# (default) PROJECT_CFLAGS = (blank) +# +# Note: Before adding PROJECT_CFLAGS, note that the PLATFORM_CFLAGS defined in +# your platform specific configuration file will be applied by default and +# further flags here may not be needed. +# +# Note: Leave a leading space when adding list items with the += operator +################################################################################ +# PROJECT_CFLAGS = + +################################################################################ +# PROJECT OPTIMIZATION CFLAGS +# These are lists of CFLAGS that are target-specific. While any flags could +# be conditionally added, they are usually limited to optimization flags. +# These flags are added BEFORE the PROJECT_CFLAGS. +# +# PROJECT_OPTIMIZATION_CFLAGS_RELEASE flags are only applied to RELEASE targets. +# +# (default) PROJECT_OPTIMIZATION_CFLAGS_RELEASE = (blank) +# +# PROJECT_OPTIMIZATION_CFLAGS_DEBUG flags are only applied to DEBUG targets. +# +# (default) PROJECT_OPTIMIZATION_CFLAGS_DEBUG = (blank) +# +# Note: Before adding PROJECT_OPTIMIZATION_CFLAGS, please note that the +# PLATFORM_OPTIMIZATION_CFLAGS defined in your platform specific configuration +# file will be applied by default and further optimization flags here may not +# be needed. +# +# Note: Leave a leading space when adding list items with the += operator +################################################################################ +# PROJECT_OPTIMIZATION_CFLAGS_RELEASE = +# PROJECT_OPTIMIZATION_CFLAGS_DEBUG = + +################################################################################ +# PROJECT COMPILERS +# Custom compilers can be set for CC and CXX +# (default) PROJECT_CXX = (blank) +# (default) PROJECT_CC = (blank) +# Note: Leave a leading space when adding list items with the += operator +################################################################################ +# PROJECT_CXX = +# PROJECT_CC = diff --git a/artool5NFTexample/openFrameworks-Info.plist b/artool5NFTexample/openFrameworks-Info.plist new file mode 100644 index 0000000..8d64d2b --- /dev/null +++ b/artool5NFTexample/openFrameworks-Info.plist @@ -0,0 +1,22 @@ + + + + + CFBundleDevelopmentRegion + English + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + cc.openFrameworks.ofapp + CFBundleInfoDictionaryVersion + 6.0 + CFBundlePackageType + APPL + CFBundleSignature + ???? + CFBundleVersion + 1.0 + CFBundleIconFile + ${ICON} + + diff --git a/artool5NFTexample/src/main.cpp b/artool5NFTexample/src/main.cpp new file mode 100644 index 0000000..3916fb8 --- /dev/null +++ b/artool5NFTexample/src/main.cpp @@ -0,0 +1,13 @@ +#include "ofMain.h" +#include "ofApp.h" + +//======================================================================== +int main( ){ + ofSetupOpenGL(640,480,OF_WINDOW); // <-------- setup the GL context + + // this kicks off the running of my app + // can be OF_WINDOW or OF_FULLSCREEN + // pass in width and height too: + ofRunApp(new ofApp()); + +} diff --git a/artool5NFTexample/src/ofApp.cpp b/artool5NFTexample/src/ofApp.cpp new file mode 100644 index 0000000..66d8ed5 --- /dev/null +++ b/artool5NFTexample/src/ofApp.cpp @@ -0,0 +1,99 @@ +#include "ofApp.h" + +//-------------------------------------------------------------- +void ofApp::setup(){ + ofBackground(0, 0, 0); + ofSetFrameRate(60); + + cam.initGrabber(640, 480); + art.setup(ofVec2f(640,480),ofVec2f(640,480)); + + ofAddListener(art.evNewMarker, this, &ofApp::onNewMarker); + ofAddListener(art.evLostMarker, this, &ofApp::onLostMarker); +} + +//-------------------------------------------------------------- +void ofApp::update(){ + cam.update(); + if(cam.isFrameNew()){ + art.update(cam); + } +} + +//-------------------------------------------------------------- +void ofApp::draw(){ + cam.draw(0, 0); + + if(art.isFound()){ + art.beginAR(); + ofDrawLine(-1000, 0, 1000, 0); + ofDrawLine(0, -1000, 0, 1000); + ofDrawBox(0, 0, 0.5, 21, 21, 21); + art.endAR(); + } + + art.drawDebug(); +} + +void ofApp::onNewMarker(int & mId){ + cout<<"New Marker found!"< + + + + diff --git a/artool5example/artool5example.xcodeproj/project.xcworkspace/xcuserdata/nausea.xcuserdatad/UserInterfaceState.xcuserstate b/artool5example/artool5example.xcodeproj/project.xcworkspace/xcuserdata/nausea.xcuserdatad/UserInterfaceState.xcuserstate new file mode 100644 index 0000000..c664b76 Binary files /dev/null and b/artool5example/artool5example.xcodeproj/project.xcworkspace/xcuserdata/nausea.xcuserdatad/UserInterfaceState.xcuserstate differ diff --git a/artool5example/artool5example.xcodeproj/xcshareddata/xcschemes/artool5example Debug.xcscheme b/artool5example/artool5example.xcodeproj/xcshareddata/xcschemes/artool5example Debug.xcscheme new file mode 100644 index 0000000..1500b9a --- /dev/null +++ b/artool5example/artool5example.xcodeproj/xcshareddata/xcschemes/artool5example Debug.xcscheme @@ -0,0 +1,86 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/artool5example/artool5example.xcodeproj/xcshareddata/xcschemes/artool5example Release.xcscheme b/artool5example/artool5example.xcodeproj/xcshareddata/xcschemes/artool5example Release.xcscheme new file mode 100644 index 0000000..59d3810 --- /dev/null +++ b/artool5example/artool5example.xcodeproj/xcshareddata/xcschemes/artool5example Release.xcscheme @@ -0,0 +1,86 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/artool5example/artool5example.xcodeproj/xcuserdata/nausea.xcuserdatad/xcschemes/xcschememanagement.plist b/artool5example/artool5example.xcodeproj/xcuserdata/nausea.xcuserdatad/xcschemes/xcschememanagement.plist new file mode 100644 index 0000000..13dfb6e --- /dev/null +++ b/artool5example/artool5example.xcodeproj/xcuserdata/nausea.xcuserdatad/xcschemes/xcschememanagement.plist @@ -0,0 +1,14 @@ + + + + + SuppressBuildableAutocreation + + E4B69B5A0A3A1756003C02F2 + + primary + + + + + diff --git a/artool5example/bin/data/.gitkeep b/artool5example/bin/data/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/artool5example/bin/data/ARTdata/camera_para.dat b/artool5example/bin/data/ARTdata/camera_para.dat new file mode 100755 index 0000000..73450c7 Binary files /dev/null and b/artool5example/bin/data/ARTdata/camera_para.dat differ diff --git a/artool5example/bin/data/ARTdata/patt.hiro b/artool5example/bin/data/ARTdata/patt.hiro new file mode 100755 index 0000000..7f78e3c --- /dev/null +++ b/artool5example/bin/data/ARTdata/patt.hiro @@ -0,0 +1,196 @@ + 234 235 240 233 240 234 240 235 240 237 240 238 240 240 240 232 + 229 240 240 240 240 240 240 240 240 240 240 240 240 240 240 228 + 227 240 240 240 240 240 240 240 240 240 240 240 240 240 240 239 + 240 240 240 240 240 240 240 240 240 240 240 240 240 240 240 240 + 236 240 240 240 240 240 240 240 240 240 240 240 240 240 240 240 + 234 240 240 240 240 240 240 240 240 240 240 240 240 240 240 240 + 236 240 240 240 240 240 240 240 240 240 240 240 240 240 240 240 + 231 240 240 240 240 240 240 240 240 240 240 240 240 240 240 240 + 229 240 240 240 240 240 240 240 240 240 240 240 240 240 240 240 + 225 149 240 240 186 216 225 174 240 240 240 237 238 240 240 240 + 150 107 238 231 75 208 115 147 238 228 223 226 237 180 226 240 + 150 62 181 213 62 187 113 169 197 72 29 237 120 50 53 207 + 149 63 47 78 53 184 113 101 142 5 150 150 45 217 186 83 + 121 84 220 222 58 180 121 92 128 109 237 124 155 232 161 64 + 149 71 240 240 76 210 98 109 122 108 240 129 51 119 161 155 + 149 186 240 240 98 219 135 152 207 191 236 227 152 77 175 209 + 235 235 240 233 240 234 240 235 240 236 240 238 240 240 240 240 + 229 240 240 240 240 240 240 240 240 240 240 240 240 240 240 240 + 227 240 240 240 240 240 240 240 240 240 240 240 240 240 240 240 + 240 240 240 240 240 240 240 240 240 240 240 240 240 240 240 240 + 236 240 240 240 240 240 240 240 240 240 240 240 240 240 240 240 + 234 240 240 240 240 240 240 240 240 240 240 240 240 240 240 240 + 236 240 240 240 240 240 240 240 240 240 240 240 240 240 240 240 + 232 240 240 240 240 240 240 240 240 240 240 240 240 240 240 240 + 229 240 240 240 240 240 240 240 240 240 240 240 240 240 240 240 + 225 156 240 240 186 216 225 186 240 240 240 240 240 240 240 240 + 150 117 240 231 72 206 115 162 240 232 223 237 240 180 226 240 + 150 74 187 213 51 184 103 168 197 78 29 237 120 50 53 216 + 144 77 51 74 61 184 106 101 142 5 150 152 52 217 186 85 + 117 89 219 219 65 184 121 92 128 100 236 125 156 240 170 73 + 148 71 240 240 76 210 109 109 121 99 240 137 51 120 166 164 + 140 186 240 240 98 220 150 156 207 192 236 230 152 77 176 212 + 234 235 240 233 240 234 240 235 240 236 240 238 240 240 240 233 + 229 240 240 240 240 240 240 240 240 240 240 240 240 240 240 239 + 227 240 240 240 240 240 240 240 240 240 240 240 240 240 240 240 + 240 240 240 240 240 240 240 240 240 240 240 240 240 240 240 240 + 234 240 240 240 240 240 240 240 240 240 240 240 240 240 240 240 + 232 240 240 240 240 240 240 240 240 240 240 240 240 240 240 240 + 235 240 240 240 240 240 240 240 240 240 240 240 240 240 240 240 + 232 240 240 240 240 240 240 240 240 240 240 240 240 240 240 240 + 228 240 240 240 240 240 240 240 240 240 240 240 240 240 240 240 + 225 156 240 240 182 212 225 180 240 240 240 240 240 240 240 240 + 150 116 238 228 66 205 115 151 238 236 225 240 240 180 226 240 + 156 84 186 211 47 184 109 170 200 92 30 240 120 50 53 216 + 147 83 51 73 50 184 106 110 148 17 151 150 45 217 186 85 + 127 98 219 219 58 179 109 101 128 107 237 125 155 240 163 72 + 155 86 240 240 76 201 85 108 121 95 232 137 51 118 153 155 + 149 189 240 240 98 220 141 154 206 178 235 230 152 77 175 209 + + 232 228 239 240 240 240 240 240 240 240 240 207 83 64 155 209 + 240 240 240 240 240 240 240 240 240 240 226 53 186 161 161 175 + 240 240 240 240 240 240 240 240 240 240 180 50 217 232 119 77 + 240 240 240 240 240 240 240 240 240 238 237 120 45 155 51 152 + 238 240 240 240 240 240 240 240 240 237 226 237 150 124 129 227 + 240 240 240 240 240 240 240 240 240 240 223 29 150 237 240 236 + 237 240 240 240 240 240 240 240 240 240 228 72 5 109 108 191 + 240 240 240 240 240 240 240 240 240 240 238 197 142 128 122 207 + 235 240 240 240 240 240 240 240 240 174 147 169 101 92 109 152 + 240 240 240 240 240 240 240 240 240 225 115 113 113 121 98 135 + 234 240 240 240 240 240 240 240 240 216 208 187 184 180 210 219 + 240 240 240 240 240 240 240 240 240 186 75 62 53 58 76 98 + 233 240 240 240 240 240 240 240 240 240 231 213 78 222 240 240 + 240 240 240 240 240 240 240 240 240 240 238 181 47 220 240 240 + 235 240 240 240 240 240 240 240 240 149 107 62 63 84 71 186 + 234 229 227 240 236 234 236 231 229 225 150 150 149 121 149 149 + 240 240 240 240 240 240 240 240 240 240 240 216 85 73 164 212 + 240 240 240 240 240 240 240 240 240 240 226 53 186 170 166 176 + 240 240 240 240 240 240 240 240 240 240 180 50 217 240 120 77 + 240 240 240 240 240 240 240 240 240 240 240 120 52 156 51 152 + 238 240 240 240 240 240 240 240 240 240 237 237 152 125 137 230 + 240 240 240 240 240 240 240 240 240 240 223 29 150 236 240 236 + 236 240 240 240 240 240 240 240 240 240 232 78 5 100 99 192 + 240 240 240 240 240 240 240 240 240 240 240 197 142 128 121 207 + 235 240 240 240 240 240 240 240 240 186 162 168 101 92 109 156 + 240 240 240 240 240 240 240 240 240 225 115 103 106 121 109 150 + 234 240 240 240 240 240 240 240 240 216 206 184 184 184 210 220 + 240 240 240 240 240 240 240 240 240 186 72 51 61 65 76 98 + 233 240 240 240 240 240 240 240 240 240 231 213 74 219 240 240 + 240 240 240 240 240 240 240 240 240 240 240 187 51 219 240 240 + 235 240 240 240 240 240 240 240 240 156 117 74 77 89 71 186 + 235 229 227 240 236 234 236 232 229 225 150 150 144 117 148 140 + 233 239 240 240 240 240 240 240 240 240 240 216 85 72 155 209 + 240 240 240 240 240 240 240 240 240 240 226 53 186 163 153 175 + 240 240 240 240 240 240 240 240 240 240 180 50 217 240 118 77 + 240 240 240 240 240 240 240 240 240 240 240 120 45 155 51 152 + 238 240 240 240 240 240 240 240 240 240 240 240 150 125 137 230 + 240 240 240 240 240 240 240 240 240 240 225 30 151 237 232 235 + 236 240 240 240 240 240 240 240 240 240 236 92 17 107 95 178 + 240 240 240 240 240 240 240 240 240 240 238 200 148 128 121 206 + 235 240 240 240 240 240 240 240 240 180 151 170 110 101 108 154 + 240 240 240 240 240 240 240 240 240 225 115 109 106 109 85 141 + 234 240 240 240 240 240 240 240 240 212 205 184 184 179 201 220 + 240 240 240 240 240 240 240 240 240 182 66 47 50 58 76 98 + 233 240 240 240 240 240 240 240 240 240 228 211 73 219 240 240 + 240 240 240 240 240 240 240 240 240 240 238 186 51 219 240 240 + 235 240 240 240 240 240 240 240 240 156 116 84 83 98 86 189 + 234 229 227 240 234 232 235 232 228 225 150 156 147 127 155 149 + + 209 175 77 152 227 236 191 207 152 135 219 98 240 240 186 149 + 155 161 119 51 129 240 108 122 109 98 210 76 240 240 71 149 + 64 161 232 155 124 237 109 128 92 121 180 58 222 220 84 121 + 83 186 217 45 150 150 5 142 101 113 184 53 78 47 63 149 + 207 53 50 120 237 29 72 197 169 113 187 62 213 181 62 150 + 240 226 180 237 226 223 228 238 147 115 208 75 231 238 107 150 + 240 240 240 238 237 240 240 240 174 225 216 186 240 240 149 225 + 240 240 240 240 240 240 240 240 240 240 240 240 240 240 240 229 + 240 240 240 240 240 240 240 240 240 240 240 240 240 240 240 231 + 240 240 240 240 240 240 240 240 240 240 240 240 240 240 240 236 + 240 240 240 240 240 240 240 240 240 240 240 240 240 240 240 234 + 240 240 240 240 240 240 240 240 240 240 240 240 240 240 240 236 + 240 240 240 240 240 240 240 240 240 240 240 240 240 240 240 240 + 239 240 240 240 240 240 240 240 240 240 240 240 240 240 240 227 + 228 240 240 240 240 240 240 240 240 240 240 240 240 240 240 229 + 232 240 240 240 238 240 237 240 235 240 234 240 233 240 235 234 + 212 176 77 152 230 236 192 207 156 150 220 98 240 240 186 140 + 164 166 120 51 137 240 99 121 109 109 210 76 240 240 71 148 + 73 170 240 156 125 236 100 128 92 121 184 65 219 219 89 117 + 85 186 217 52 152 150 5 142 101 106 184 61 74 51 77 144 + 216 53 50 120 237 29 78 197 168 103 184 51 213 187 74 150 + 240 226 180 240 237 223 232 240 162 115 206 72 231 240 117 150 + 240 240 240 240 240 240 240 240 186 225 216 186 240 240 156 225 + 240 240 240 240 240 240 240 240 240 240 240 240 240 240 240 229 + 240 240 240 240 240 240 240 240 240 240 240 240 240 240 240 232 + 240 240 240 240 240 240 240 240 240 240 240 240 240 240 240 236 + 240 240 240 240 240 240 240 240 240 240 240 240 240 240 240 234 + 240 240 240 240 240 240 240 240 240 240 240 240 240 240 240 236 + 240 240 240 240 240 240 240 240 240 240 240 240 240 240 240 240 + 240 240 240 240 240 240 240 240 240 240 240 240 240 240 240 227 + 240 240 240 240 240 240 240 240 240 240 240 240 240 240 240 229 + 240 240 240 240 238 240 236 240 235 240 234 240 233 240 235 235 + 209 175 77 152 230 235 178 206 154 141 220 98 240 240 189 149 + 155 153 118 51 137 232 95 121 108 85 201 76 240 240 86 155 + 72 163 240 155 125 237 107 128 101 109 179 58 219 219 98 127 + 85 186 217 45 150 151 17 148 110 106 184 50 73 51 83 147 + 216 53 50 120 240 30 92 200 170 109 184 47 211 186 84 156 + 240 226 180 240 240 225 236 238 151 115 205 66 228 238 116 150 + 240 240 240 240 240 240 240 240 180 225 212 182 240 240 156 225 + 240 240 240 240 240 240 240 240 240 240 240 240 240 240 240 228 + 240 240 240 240 240 240 240 240 240 240 240 240 240 240 240 232 + 240 240 240 240 240 240 240 240 240 240 240 240 240 240 240 235 + 240 240 240 240 240 240 240 240 240 240 240 240 240 240 240 232 + 240 240 240 240 240 240 240 240 240 240 240 240 240 240 240 234 + 240 240 240 240 240 240 240 240 240 240 240 240 240 240 240 240 + 240 240 240 240 240 240 240 240 240 240 240 240 240 240 240 227 + 239 240 240 240 240 240 240 240 240 240 240 240 240 240 240 229 + 233 240 240 240 238 240 236 240 235 240 234 240 233 240 235 234 + + 149 149 121 149 150 150 225 229 231 236 234 236 240 227 229 234 + 186 71 84 63 62 107 149 240 240 240 240 240 240 240 240 235 + 240 240 220 47 181 238 240 240 240 240 240 240 240 240 240 240 + 240 240 222 78 213 231 240 240 240 240 240 240 240 240 240 233 + 98 76 58 53 62 75 186 240 240 240 240 240 240 240 240 240 + 219 210 180 184 187 208 216 240 240 240 240 240 240 240 240 234 + 135 98 121 113 113 115 225 240 240 240 240 240 240 240 240 240 + 152 109 92 101 169 147 174 240 240 240 240 240 240 240 240 235 + 207 122 128 142 197 238 240 240 240 240 240 240 240 240 240 240 + 191 108 109 5 72 228 240 240 240 240 240 240 240 240 240 237 + 236 240 237 150 29 223 240 240 240 240 240 240 240 240 240 240 + 227 129 124 150 237 226 237 240 240 240 240 240 240 240 240 238 + 152 51 155 45 120 237 238 240 240 240 240 240 240 240 240 240 + 77 119 232 217 50 180 240 240 240 240 240 240 240 240 240 240 + 175 161 161 186 53 226 240 240 240 240 240 240 240 240 240 240 + 209 155 64 83 207 240 240 240 240 240 240 240 240 239 228 232 + 140 148 117 144 150 150 225 229 232 236 234 236 240 227 229 235 + 186 71 89 77 74 117 156 240 240 240 240 240 240 240 240 235 + 240 240 219 51 187 240 240 240 240 240 240 240 240 240 240 240 + 240 240 219 74 213 231 240 240 240 240 240 240 240 240 240 233 + 98 76 65 61 51 72 186 240 240 240 240 240 240 240 240 240 + 220 210 184 184 184 206 216 240 240 240 240 240 240 240 240 234 + 150 109 121 106 103 115 225 240 240 240 240 240 240 240 240 240 + 156 109 92 101 168 162 186 240 240 240 240 240 240 240 240 235 + 207 121 128 142 197 240 240 240 240 240 240 240 240 240 240 240 + 192 99 100 5 78 232 240 240 240 240 240 240 240 240 240 236 + 236 240 236 150 29 223 240 240 240 240 240 240 240 240 240 240 + 230 137 125 152 237 237 240 240 240 240 240 240 240 240 240 238 + 152 51 156 52 120 240 240 240 240 240 240 240 240 240 240 240 + 77 120 240 217 50 180 240 240 240 240 240 240 240 240 240 240 + 176 166 170 186 53 226 240 240 240 240 240 240 240 240 240 240 + 212 164 73 85 216 240 240 240 240 240 240 240 240 240 240 240 + 149 155 127 147 156 150 225 228 232 235 232 234 240 227 229 234 + 189 86 98 83 84 116 156 240 240 240 240 240 240 240 240 235 + 240 240 219 51 186 238 240 240 240 240 240 240 240 240 240 240 + 240 240 219 73 211 228 240 240 240 240 240 240 240 240 240 233 + 98 76 58 50 47 66 182 240 240 240 240 240 240 240 240 240 + 220 201 179 184 184 205 212 240 240 240 240 240 240 240 240 234 + 141 85 109 106 109 115 225 240 240 240 240 240 240 240 240 240 + 154 108 101 110 170 151 180 240 240 240 240 240 240 240 240 235 + 206 121 128 148 200 238 240 240 240 240 240 240 240 240 240 240 + 178 95 107 17 92 236 240 240 240 240 240 240 240 240 240 236 + 235 232 237 151 30 225 240 240 240 240 240 240 240 240 240 240 + 230 137 125 150 240 240 240 240 240 240 240 240 240 240 240 238 + 152 51 155 45 120 240 240 240 240 240 240 240 240 240 240 240 + 77 118 240 217 50 180 240 240 240 240 240 240 240 240 240 240 + 175 153 163 186 53 226 240 240 240 240 240 240 240 240 240 240 + 209 155 72 85 216 240 240 240 240 240 240 240 240 240 239 233 + diff --git a/artool5example/config.make b/artool5example/config.make new file mode 100644 index 0000000..df10f64 --- /dev/null +++ b/artool5example/config.make @@ -0,0 +1,142 @@ +################################################################################ +# CONFIGURE PROJECT MAKEFILE (optional) +# This file is where we make project specific configurations. +################################################################################ + +################################################################################ +# OF ROOT +# The location of your root openFrameworks installation +# (default) OF_ROOT = ../../.. +################################################################################ +# OF_ROOT = ../../.. + +################################################################################ +# PROJECT ROOT +# The location of the project - a starting place for searching for files +# (default) PROJECT_ROOT = . (this directory) +# +################################################################################ +# PROJECT_ROOT = . + +################################################################################ +# PROJECT SPECIFIC CHECKS +# This is a project defined section to create internal makefile flags to +# conditionally enable or disable the addition of various features within +# this makefile. For instance, if you want to make changes based on whether +# GTK is installed, one might test that here and create a variable to check. +################################################################################ +# None + +################################################################################ +# PROJECT EXTERNAL SOURCE PATHS +# These are fully qualified paths that are not within the PROJECT_ROOT folder. +# Like source folders in the PROJECT_ROOT, these paths are subject to +# exlclusion via the PROJECT_EXLCUSIONS list. +# +# (default) PROJECT_EXTERNAL_SOURCE_PATHS = (blank) +# +# Note: Leave a leading space when adding list items with the += operator +################################################################################ +# PROJECT_EXTERNAL_SOURCE_PATHS = + +################################################################################ +# PROJECT EXCLUSIONS +# These makefiles assume that all folders in your current project directory +# and any listed in the PROJECT_EXTERNAL_SOURCH_PATHS are are valid locations +# to look for source code. The any folders or files that match any of the +# items in the PROJECT_EXCLUSIONS list below will be ignored. +# +# Each item in the PROJECT_EXCLUSIONS list will be treated as a complete +# string unless teh user adds a wildcard (%) operator to match subdirectories. +# GNU make only allows one wildcard for matching. The second wildcard (%) is +# treated literally. +# +# (default) PROJECT_EXCLUSIONS = (blank) +# +# Will automatically exclude the following: +# +# $(PROJECT_ROOT)/bin% +# $(PROJECT_ROOT)/obj% +# $(PROJECT_ROOT)/%.xcodeproj +# +# Note: Leave a leading space when adding list items with the += operator +################################################################################ +# PROJECT_EXCLUSIONS = + +################################################################################ +# PROJECT LINKER FLAGS +# These flags will be sent to the linker when compiling the executable. +# +# (default) PROJECT_LDFLAGS = -Wl,-rpath=./libs +# +# Note: Leave a leading space when adding list items with the += operator +################################################################################ + +# Currently, shared libraries that are needed are copied to the +# $(PROJECT_ROOT)/bin/libs directory. The following LDFLAGS tell the linker to +# add a runtime path to search for those shared libraries, since they aren't +# incorporated directly into the final executable application binary. +# TODO: should this be a default setting? +# PROJECT_LDFLAGS=-Wl,-rpath=./libs + +################################################################################ +# PROJECT DEFINES +# Create a space-delimited list of DEFINES. The list will be converted into +# CFLAGS with the "-D" flag later in the makefile. +# +# (default) PROJECT_DEFINES = (blank) +# +# Note: Leave a leading space when adding list items with the += operator +################################################################################ +# PROJECT_DEFINES = + +################################################################################ +# PROJECT CFLAGS +# This is a list of fully qualified CFLAGS required when compiling for this +# project. These CFLAGS will be used IN ADDITION TO the PLATFORM_CFLAGS +# defined in your platform specific core configuration files. These flags are +# presented to the compiler BEFORE the PROJECT_OPTIMIZATION_CFLAGS below. +# +# (default) PROJECT_CFLAGS = (blank) +# +# Note: Before adding PROJECT_CFLAGS, note that the PLATFORM_CFLAGS defined in +# your platform specific configuration file will be applied by default and +# further flags here may not be needed. +# +# Note: Leave a leading space when adding list items with the += operator +################################################################################ +# PROJECT_CFLAGS = + +################################################################################ +# PROJECT OPTIMIZATION CFLAGS +# These are lists of CFLAGS that are target-specific. While any flags could +# be conditionally added, they are usually limited to optimization flags. +# These flags are added BEFORE the PROJECT_CFLAGS. +# +# PROJECT_OPTIMIZATION_CFLAGS_RELEASE flags are only applied to RELEASE targets. +# +# (default) PROJECT_OPTIMIZATION_CFLAGS_RELEASE = (blank) +# +# PROJECT_OPTIMIZATION_CFLAGS_DEBUG flags are only applied to DEBUG targets. +# +# (default) PROJECT_OPTIMIZATION_CFLAGS_DEBUG = (blank) +# +# Note: Before adding PROJECT_OPTIMIZATION_CFLAGS, please note that the +# PLATFORM_OPTIMIZATION_CFLAGS defined in your platform specific configuration +# file will be applied by default and further optimization flags here may not +# be needed. +# +# Note: Leave a leading space when adding list items with the += operator +################################################################################ +# PROJECT_OPTIMIZATION_CFLAGS_RELEASE = +# PROJECT_OPTIMIZATION_CFLAGS_DEBUG = + +################################################################################ +# PROJECT COMPILERS +# Custom compilers can be set for CC and CXX +# (default) PROJECT_CXX = (blank) +# (default) PROJECT_CC = (blank) +# Note: Leave a leading space when adding list items with the += operator +################################################################################ +# PROJECT_CXX = +# PROJECT_CC = diff --git a/artool5example/openFrameworks-Info.plist b/artool5example/openFrameworks-Info.plist new file mode 100644 index 0000000..8d64d2b --- /dev/null +++ b/artool5example/openFrameworks-Info.plist @@ -0,0 +1,22 @@ + + + + + CFBundleDevelopmentRegion + English + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + cc.openFrameworks.ofapp + CFBundleInfoDictionaryVersion + 6.0 + CFBundlePackageType + APPL + CFBundleSignature + ???? + CFBundleVersion + 1.0 + CFBundleIconFile + ${ICON} + + diff --git a/artool5example/src/main.cpp b/artool5example/src/main.cpp new file mode 100644 index 0000000..f60bd1b --- /dev/null +++ b/artool5example/src/main.cpp @@ -0,0 +1,13 @@ +#include "ofMain.h" +#include "ofApp.h" + +//======================================================================== +int main( ){ + ofSetupOpenGL(1280,720,OF_WINDOW); // <-------- setup the GL context + + // this kicks off the running of my app + // can be OF_WINDOW or OF_FULLSCREEN + // pass in width and height too: + ofRunApp(new ofApp()); + +} diff --git a/artool5example/src/ofApp.cpp b/artool5example/src/ofApp.cpp new file mode 100644 index 0000000..72acf24 --- /dev/null +++ b/artool5example/src/ofApp.cpp @@ -0,0 +1,86 @@ +#include "ofApp.h" + +//-------------------------------------------------------------- +void ofApp::setup(){ + ofBackground(0, 0, 0); + ofSetFrameRate(60); + + cam.initGrabber(1280, 720); + art.setup(ofVec2f(1280,720), ofVec2f(1280,720)); +} + +//-------------------------------------------------------------- +void ofApp::update(){ + cam.update(); + if(cam.isFrameNew()){ + art.update(cam); + } +} + +//-------------------------------------------------------------- +void ofApp::draw(){ + cam.draw(0, 0); + + if(art.isFound()){ + art.beginAR(); + ofDrawBox(0, 0, 0, 50, 50, 50); + art.endAR(); + } + + art.drawDebug(); +} + +//-------------------------------------------------------------- +void ofApp::keyPressed(int key){ + +} + +//-------------------------------------------------------------- +void ofApp::keyReleased(int key){ + +} + +//-------------------------------------------------------------- +void ofApp::mouseMoved(int x, int y ){ + +} + +//-------------------------------------------------------------- +void ofApp::mouseDragged(int x, int y, int button){ + +} + +//-------------------------------------------------------------- +void ofApp::mousePressed(int x, int y, int button){ + +} + +//-------------------------------------------------------------- +void ofApp::mouseReleased(int x, int y, int button){ + +} + +//-------------------------------------------------------------- +void ofApp::mouseEntered(int x, int y){ + +} + +//-------------------------------------------------------------- +void ofApp::mouseExited(int x, int y){ + +} + +//-------------------------------------------------------------- +void ofApp::windowResized(int w, int h){ + +} + +//-------------------------------------------------------------- +void ofApp::gotMessage(ofMessage msg){ + +} + +//-------------------------------------------------------------- +void ofApp::dragEvent(ofDragInfo dragInfo){ + +} diff --git a/artool5example/src/ofApp.h b/artool5example/src/ofApp.h new file mode 100644 index 0000000..465c2ce --- /dev/null +++ b/artool5example/src/ofApp.h @@ -0,0 +1,28 @@ +#pragma once + +#include "ofMain.h" +#include "ofxARTPattern.h" + +class ofApp : public ofBaseApp{ + + public: + void setup(); + void update(); + void draw(); + + void keyPressed(int key); + void keyReleased(int key); + void mouseMoved(int x, int y ); + void mouseDragged(int x, int y, int button); + void mousePressed(int x, int y, int button); + void mouseReleased(int x, int y, int button); + void mouseEntered(int x, int y); + void mouseExited(int x, int y); + void windowResized(int w, int h); + void dragEvent(ofDragInfo dragInfo); + void gotMessage(ofMessage msg); + + //ofxArtool5 art; + ofxArtool5::PatternTracker art; + ofVideoGrabber cam; +}; diff --git a/libs/include/AR/ar.h b/libs/include/AR/ar.h new file mode 100755 index 0000000..70f2f0d --- /dev/null +++ b/libs/include/AR/ar.h @@ -0,0 +1,1897 @@ +/* + * ar.h + * ARToolKit5 + * + * This file is part of ARToolKit. + * + * ARToolKit is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ARToolKit is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ARToolKit. If not, see . + * + * As a special exception, the copyright holders of this library give you + * permission to link this library with independent modules to produce an + * executable, regardless of the license terms of these independent modules, and to + * copy and distribute the resulting executable under terms of your choice, + * provided that you also meet, for each linked independent module, the terms and + * conditions of the license of that module. An independent module is a module + * which is neither derived from nor based on this library. If you modify this + * library, you may extend this exception to your version of the library, but you + * are not obligated to do so. If you do not wish to do so, delete this exception + * statement from your version. + * + * Copyright 2015 Daqri, LLC. + * Copyright 2002-2015 ARToolworks, Inc. + * + * Author(s): Hirokazu Kato, Philip Lamb + * + */ +/******************************************************* + * + * Author: Hirokazu Kato + * + * kato@sys.im.hiroshima-cu.ac.jp + * + * Revision: 4.01 + * Date: 2003/11/07 + * + *******************************************************/ + +/*! + @header ar + @abstract ARToolKit core routines. + @discussion + This header declares essential types and API for the entire + ARToolKit SDK. + + For compile-time per-machine configuration, see <AR/config.h>.
+ For compile-time ARToolKit configuration, see <AR/arConfig.h>. + @copyright 2015 Daqri, LLC. + */ + +#ifndef AR_H +#define AR_H + +#include +#include +#include +#ifndef _WIN32 // errno is defined in stdlib.h on Windows. +# include +#endif +#include +#include +#ifdef __ANDROID__ +# include +# include +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +// +// Logging. +// + +#ifdef __ANDROID__ +# define ARLOG(...) __android_log_print(ANDROID_LOG_INFO, "libar", __VA_ARGS__) +#else +# define ARLOG(...) printf(__VA_ARGS__) +#endif + +/*! + @var + @abstract Sets the severity level. Log messages below the set severity level are not logged. + @discussion + All calls to ARToolKit's logging facility include a "log level" parameter, which specifies + the severity of the log message. (The severities are defined in %lt;ar/config.h>.) + Setting this global allows for filtering of log messages. All log messages lower than + the set level will not be logged by arLog(). + @seealso arLog arLog +*/ +extern int arLogLevel; + +/*! + @function + @abstract Write a string to the current logging facility. + @discussion + The default logging facility varies by platform, but on Unix-like platforms is typically + the standard error file descriptor. However, logging may be redirected to some other + facility by arLogSetLogger. + + Newlines are not automatically appended to log output. + @param logLevel The severity of the log message. Defined in %lt;ar/config.h>. + Log output is written to the logging facility provided the logLevel meets or + exceeds the minimum level specified in global arLogLevel. + @param format Log format string, in the form of printf(). + @seealso arLogLevel arLogLevel + @seealso arLogSetLogger arLogSetLogger +*/ + +void arLog(const int logLevel, const char *format, ...); + +typedef void (AR_CALLBACK *AR_LOG_LOGGER_CALLBACK)(const char *logMessage); + + +/*! + @function + @abstract Divert logging to a callback, or revert to default logging. + @discussion + The default logging facility varies by platform, but on Unix-like platforms is typically + the standard error file descriptor. However, logging may be redirected to some other + facility by this function. + @param callback The function which will be called with the log output, or NULL to + cancel redirection. + @param callBackOnlyIfOnSameThread If non-zero, then the callback will only be called + if the call to arLog is made on the same thread as the thread which called this function, + and if the arLog call is made on a different thread, log output will be buffered until + the next call to arLog on the original thread. + + The purpose of this is to prevent logging from secondary threads in cases where the + callback model of the target platform precludes this. + @seealso arLog arLog +*/ +void arLogSetLogger(AR_LOG_LOGGER_CALLBACK callback, int callBackOnlyIfOnSameThread); + +// FN(x) allows for a function-like macro x which expands to a single statement. +#define FN(x) do {x} while (0) + +#ifdef DEBUG +# define ARLOGd(...) arLog(AR_LOG_LEVEL_DEBUG, __VA_ARGS__) +#else +# define ARLOGd(...) +#endif +#define ARLOGi(...) arLog(AR_LOG_LEVEL_INFO, __VA_ARGS__) +#define ARLOGw(...) arLog(AR_LOG_LEVEL_WARN, __VA_ARGS__) +#define ARLOGe(...) arLog(AR_LOG_LEVEL_ERROR, __VA_ARGS__) +#define ARLOGperror(s) arLog(AR_LOG_LEVEL_ERROR, (s ? "%s: %s\n" : "%s%s\n"), (s ? s : ""), strerror(errno)) + + +#define arMalloc(V,T,S) \ +{ if( ((V) = (T *)malloc( sizeof(T) * (S) )) == NULL ) \ +{ARLOGe("Out of memory!!\n"); exit(1);} } + +#define arMallocClear(V,T,S) \ +{ if( ((V) = (T *)calloc( (S), sizeof(T) )) == NULL ) \ +{ARLOGe("Out of memory!!\n"); exit(1);} } + +typedef char ARInt8; +typedef short ARInt16; +typedef int ARInt32; +typedef unsigned char ARUint8; +typedef unsigned short ARUint16; +typedef unsigned int ARUint32; +typedef float ARfloat; +#ifdef ARDOUBLE_IS_FLOAT +typedef float ARdouble; +#else +typedef double ARdouble; +#endif + +#ifndef TRUE +# define TRUE 1 +#endif +#ifndef FALSE +# define FALSE 0 +#endif + +#ifdef __cplusplus +} +#endif + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* --------------------------------------------------*/ + +typedef enum { + AR_LABELING_THRESH_MODE_MANUAL = 0, + AR_LABELING_THRESH_MODE_AUTO_MEDIAN, + AR_LABELING_THRESH_MODE_AUTO_OTSU, + AR_LABELING_THRESH_MODE_AUTO_ADAPTIVE, + AR_LABELING_THRESH_MODE_AUTO_BRACKETING +} AR_LABELING_THRESH_MODE; + +/*! + @typedef ARMarkerInfo2 + @abstract (description) + @discussion (description) + @field area (description) + @field pos (description) + @field coord_num (description) + @field x_coord (description) + @field y_coord (description) + @field vertex (description) +*/ +typedef struct { + int area; + ARdouble pos[2]; + int coord_num; + int x_coord[AR_CHAIN_MAX]; + int y_coord[AR_CHAIN_MAX]; + int vertex[5]; +} ARMarkerInfo2; + +/*! + @typedef + @abstract Result codes returned by arDetectMarker to report state of individual detected trapezoidal regions. + @discussion + When detecting markers, all trapezoidal regions in the incoming image are considered for + marker matching. Various heuristics are used to reject regions judged to be non-markers. + The code will, as far as possible, report rejection by placing one of these constants + into the ARMarkerInfo.cutoffPhase field of regions rejected during the arDetectMarker() call. + Note that the ARMarkerInfo.id of such rejected regions will be -1. + @constant AR_MARKER_INFO_CUTOFF_PHASE_NONE Marker OK. + @constant AR_MARKER_INFO_CUTOFF_PHASE_PATTERN_EXTRACTION Failure during pattern extraction. + @constant AR_MARKER_INFO_CUTOFF_PHASE_MATCH_GENERIC Generic error during matching phase. + @constant AR_MARKER_INFO_CUTOFF_PHASE_MATCH_CONTRAST Insufficient contrast during matching. + @constant AR_MARKER_INFO_CUTOFF_PHASE_MATCH_BARCODE_NOT_FOUND Barcode matching could not find correct barcode locator pattern. + @constant AR_MARKER_INFO_CUTOFF_PHASE_MATCH_BARCODE_EDC_FAIL Barcode matching error detection/correction found unrecoverable error. + @constant AR_MARKER_INFO_CUTOFF_PHASE_MATCH_CONFIDENCE Matching confidence cutoff value not reached. + @constant AR_MARKER_INFO_CUTOFF_PHASE_POSE_ERROR Maximum allowable pose error exceeded. + @constant AR_MARKER_INFO_CUTOFF_PHASE_POSE_ERROR_MULTI Multi-marker pose error value exceeded. + @constant AR_MARKER_INFO_CUTOFF_PHASE_HEURISTIC_TROUBLESOME_MATRIX_CODES Heuristic-based rejection of troublesome matrix code which is often generated in error. + */ +typedef enum { + AR_MARKER_INFO_CUTOFF_PHASE_NONE, + AR_MARKER_INFO_CUTOFF_PHASE_PATTERN_EXTRACTION, + AR_MARKER_INFO_CUTOFF_PHASE_MATCH_GENERIC, + AR_MARKER_INFO_CUTOFF_PHASE_MATCH_CONTRAST, + AR_MARKER_INFO_CUTOFF_PHASE_MATCH_BARCODE_NOT_FOUND, + AR_MARKER_INFO_CUTOFF_PHASE_MATCH_BARCODE_EDC_FAIL, + AR_MARKER_INFO_CUTOFF_PHASE_MATCH_CONFIDENCE, + AR_MARKER_INFO_CUTOFF_PHASE_POSE_ERROR, + AR_MARKER_INFO_CUTOFF_PHASE_POSE_ERROR_MULTI, + AR_MARKER_INFO_CUTOFF_PHASE_HEURISTIC_TROUBLESOME_MATRIX_CODES +} AR_MARKER_INFO_CUTOFF_PHASE; + +#define AR_MARKER_INFO_CUTOFF_PHASE_DESCRIPTION_COUNT 10 +extern const char *arMarkerInfoCutoffPhaseDescriptions[AR_MARKER_INFO_CUTOFF_PHASE_DESCRIPTION_COUNT]; + +/*! + @typedef ARMarkerInfo + @abstract Describes a detected trapezoidal area (a candidate for a marker match). + @discussion + After marker detection, a number of trapezoidal areas in the camera image will have been identified. An + ARMarkerInfo struct is returned for each area so matched. Trapezoidal areas which have been matched + with marker images (in pattern mode) or barcodes (in matrix mode) will have valid values assigned to the + appropriate id field. + @field area Area in pixels of the largest connected region, comprising the marker border and regions connected to it. Note that this is + not the same as the actual onscreen area inside the marker border. + @field id If pattern detection mode is either pattern mode OR matrix but not both, will be marker ID (>= 0) if marker is valid, or -1 if invalid. + @field idPatt If pattern detection mode includes a pattern mode, will be marker ID (>= 0) if marker is valid, or -1 if invalid. + @field idMatrix If pattern detection mode includes a matrix mode, will be marker ID (>= 0) if marker is valid, or -1 if invalid. + @field dir If pattern detection mode is either pattern mode OR matrix but not both, and id != -1, will be marker direction (range 0 to 3, inclusive). + @field dirPatt If pattern detection mode includes a pattern mode, and id != -1, will be marker direction (range 0 to 3, inclusive). + @field dirMatrix If pattern detection mode includes a matrix mode, and id != -1, will be marker direction (range 0 to 3, inclusive). + @field cf If pattern detection mode is either pattern mode OR matrix but not both, will be marker matching confidence (range 0.0 to 1.0 inclusive) if marker is valid, or -1.0 if marker is invalid. + @field cfPatt If pattern detection mode includes a pattern mode, will be marker matching confidence (range 0.0 to 1.0 inclusive) if marker is valid, or -1.0 if marker is invalid. + @field cfMatrix If pattern detection mode includes a matrix mode, will be marker matching confidence (range 0.0 to 1.0 inclusive) if marker is valid, or -1.0 if marker is invalid. + @field pos 2D position (in camera image coordinates, origin at top-left) of the centre of the marker. + @field line Line equations for the 4 sides of the marker. + @field vertex 2D positions (in camera image coordinates, origin at top-left) of the corners of the marker. vertex[(4 - dir)%4][] is the top-left corner of the marker. Other vertices proceed clockwise from this. These are idealised coordinates (i.e. the onscreen position aligns correctly with the undistorted camera image.) + @field markerInfo2Ptr (description) + @field cutoffPhase If a trapezoidal region is detected, but is eliminated from the candidates for tracking, + this field is filled out with the tracking phase at which the marker was cut off. An English-language + description of the phase can be obtained by indexing into the C-string array arMarkerInfoCutoffPhaseDescriptions[]. + @field globalID If arPattDetectionMode is a matrix mode, matrixCodeType is AR_MATRIX_CODE_GLOBAL_ID, and idMatrix >= 0, will contain the globalID. +*/ +typedef struct { + int area; + int id; + int idPatt; + int idMatrix; + int dir; + int dirPatt; + int dirMatrix; + ARdouble cf; + ARdouble cfPatt; + ARdouble cfMatrix; + ARdouble pos[2]; + ARdouble line[4][3]; + ARdouble vertex[4][2]; + ARMarkerInfo2 *markerInfo2Ptr; + AR_MARKER_INFO_CUTOFF_PHASE cutoffPhase; + int errorCorrected; + uint64_t globalID; +} ARMarkerInfo; + +/*! + @typedef ARTrackingHistory + @abstract (description) + @discussion (description) + @field marker (description) + @field count (description) + */ +typedef struct { + ARMarkerInfo marker; + int count; +} ARTrackingHistory; + +/*! + @typedef ARLabelInfo + @abstract (description) + @discussion (description) + @field labelImage (description) + @field bwImage (description) + @field label_num (description) + @field area (description) + @field clip (description) + @field pos (description) + @field work (description) + @field work2 (description) + */ +typedef struct { + AR_LABELING_LABEL_TYPE *labelImage; +#if !AR_DISABLE_LABELING_DEBUG_MODE + ARUint8 *bwImage; +#endif + int label_num; + int area[AR_LABELING_WORK_SIZE]; + int clip[AR_LABELING_WORK_SIZE][4]; + ARdouble pos[AR_LABELING_WORK_SIZE][2]; + int work[AR_LABELING_WORK_SIZE]; + int work2[AR_LABELING_WORK_SIZE*7]; // area, pos[2], clip[4]. +} ARLabelInfo; + +/* --------------------------------------------------*/ + +/*! + @typedef ARPattHandle + @abstract A structure which holds descriptions of trained patterns for template matching. + @discussion Template (picture)-based pattern matching requires details of the pattern + to be supplied to the matching functions. This structure holds such details. It is + generally setup by loading pattern files from disk. + @field patt_num Number of valid patterns in the structure. + @field pattf Flag: 0 = no pattern loaded at this position. 1 = pattern loaded and activated. 2 = pattern loaded but deactivated. + @field patt Array of 4 different orientations of each pattern's colour values, in 1-byte per component BGR order. + @field pattpow Root-mean-square of the pattern intensities. + @field pattBW Array of 4 different orientations of each pattern's 1-byte luminosity values. + @field pattpowBW Root-mean-square of the pattern intensities. +*/ +typedef struct { + int patt_num; + int patt_num_max; + int *pattf; + int **patt; + ARdouble *pattpow; + int **pattBW; + ARdouble *pattpowBW; + //ARdouble pattRatio; + int pattSize; +} ARPattHandle; + +/*! + @typedef ARPattRectInfo + @abstract Defines a pattern rectangle as a sub-portion of a marker image. + @discussion A complete marker image has coordinates {0.0f, 0.0f, 1.0f, 1.0f}. + A standard ARToolKit marker with a pattern ratio of 0.5 has coordinates + {0.25f, 0.25f, 0.75f, 0.75f}. + @field topLeftX Horizontal coordinate of the top left corner of the pattern space, in range 0.0f-1.0f. + @field topLeftY Vertical coordinate of the top left corner of the pattern space, in range 0.0f-1.0f. + @field bottomRightX Horizontal coordinate of the bottom right corner of the pattern space, in range 0.0f-1.0f. + @field bottomRightY Vertical coordinate of the bottom right corner of the pattern space, in range 0.0f-1.0f. + */ +typedef struct { + float topLeftX; + float topLeftY; + float bottomRightX; + float bottomRightY; +} ARPattRectInfo; + +/* --------------------------------------------------*/ + +#ifdef __cplusplus +} +#endif + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define AR_MATRIX_CODE_TYPE_SIZE_MASK 0x000000ff +#define AR_MATRIX_CODE_TYPE_ECC_NONE 0x00000000 +#define AR_MATRIX_CODE_TYPE_ECC_PARITY 0x00000100 // Single-bit parity. +#define AR_MATRIX_CODE_TYPE_ECC_HAMMING 0x00000200 // Hamming code with Hamming distance of 3. +#define AR_MATRIX_CODE_TYPE_ECC_BCH___3 0x00000300 // BCH code with Hamming distance of 3. +#define AR_MATRIX_CODE_TYPE_ECC_BCH___5 0x00000400 // BCH code with Hamming distance of 5. +#define AR_MATRIX_CODE_TYPE_ECC_BCH___7 0x00000500 // BCH code with Hamming distance of 7. +#define AR_MATRIX_CODE_TYPE_ECC_BCH___9 0x00000600 // BCH code with Hamming distance of 9. +#define AR_MATRIX_CODE_TYPE_ECC_BCH___11 0x00000700 // BCH code with Hamming distance of 11. +#define AR_MATRIX_CODE_TYPE_ECC_BCH___19 0x00000b00 // BCH code with Hamming distance of 19. + +typedef enum { + AR_MATRIX_CODE_3x3 = 0x03, // Matrix code in range 0-63. + AR_MATRIX_CODE_3x3_PARITY65 = 0x03 | AR_MATRIX_CODE_TYPE_ECC_PARITY, // Matrix code in range 0-31. + AR_MATRIX_CODE_3x3_HAMMING63 = 0x03 | AR_MATRIX_CODE_TYPE_ECC_HAMMING, // Matrix code in range 0-7. + AR_MATRIX_CODE_4x4 = 0x04, // Matrix code in range 0-8191. + AR_MATRIX_CODE_4x4_BCH_13_9_3 = 0x04 | AR_MATRIX_CODE_TYPE_ECC_BCH___3, // Matrix code in range 0-511. + AR_MATRIX_CODE_4x4_BCH_13_5_5 = 0x04 | AR_MATRIX_CODE_TYPE_ECC_BCH___5, // Matrix code in range 0-31. + AR_MATRIX_CODE_5x5_BCH_22_12_5 = 0x05 | AR_MATRIX_CODE_TYPE_ECC_BCH___5, // Matrix code in range 0-4095. + AR_MATRIX_CODE_5x5_BCH_22_7_7 = 0x05 | AR_MATRIX_CODE_TYPE_ECC_BCH___7, // Matrix code in range 0-127. + AR_MATRIX_CODE_5x5 = 0x05, // Matrix code in range 0-4194303. + AR_MATRIX_CODE_6x6 = 0x06, // Matrix code in range 0-8589934591. + AR_MATRIX_CODE_GLOBAL_ID = 0x0e | AR_MATRIX_CODE_TYPE_ECC_BCH___19 +} AR_MATRIX_CODE_TYPE; + +/*! + @typedef ARHandle + @abstract (description) + @discussion (description) + @field arDebug (description) + @field arPixelFormat (description) + @field arPixelSize (description) + @field arLabelingMode (description) + @field arLabelingThresh (description) + @field arImageProcMode + To query this value, call arGetImageProcMode(). To set this value, call arSetImageProcMode(). + @field arPatternDetectionMode (description) + @field arMarkerExtractionMode (description) + @field arParamLT (description) + @field marker_num (description) + @field markerInfo (description) + @field marker2_num (description) + @field markerInfo2 (description) + @field history_num (description) + @field history (description) + @field labelInfo (description) + @field pattHandle (description) + @field pattRatio A value between 0.0 and 1.0, representing the proportion of the marker width which constitutes the pattern. In earlier versions, this value was fixed at 0.5. + @field matrixCodeType When matrix code pattern detection mode is active, indicates the type of matrix code to detect. + */ +typedef struct { + int arDebug; + AR_PIXEL_FORMAT arPixelFormat; + int arPixelSize; + int arLabelingMode; + int arLabelingThresh; + int arImageProcMode; + int arPatternDetectionMode; + int arMarkerExtractionMode; + ARParamLT *arParamLT; + int xsize; + int ysize; + int marker_num; + ARMarkerInfo markerInfo[AR_SQUARE_MAX]; + int marker2_num; + ARMarkerInfo2 markerInfo2[AR_SQUARE_MAX]; + int history_num; + ARTrackingHistory history[AR_SQUARE_MAX]; + ARLabelInfo labelInfo; + ARPattHandle *pattHandle; + AR_LABELING_THRESH_MODE arLabelingThreshMode; + int arLabelingThreshAutoInterval; + int arLabelingThreshAutoIntervalTTL; + int arLabelingThreshAutoBracketOver; + int arLabelingThreshAutoBracketUnder; + ARImageProcInfo *arImageProcInfo; + ARdouble pattRatio; + AR_MATRIX_CODE_TYPE matrixCodeType; +} ARHandle; + + +/* --------------------------------------------------*/ + +/*! + @typedef + @abstract (description) + @discussion (description) + @field icpHandle (description) +*/ +typedef struct { + ICPHandleT *icpHandle; +} AR3DHandle; + +#define AR_TRANS_MAT_IDENTITY ICP_TRANS_MAT_IDENTITY + +/*! + @typedef + @abstract (description) + @discussion (description) + @field icpStereoHandle (description) +*/ +typedef struct { + ICPStereoHandleT *icpStereoHandle; +} AR3DStereoHandle; + + +/***********************************/ +/* */ +/* For square detection */ +/* */ +/***********************************/ + +/*! + @functiongroup "Square detection". + */ +/*! + @function + @abstract Create a handle to hold settings for an ARToolKit tracker instance. + @discussion + ARHandle is the primary structure holding the settings for a single ARToolKit + square marker tracking instance. Settings include expected video stream image + size and pixel format, tracking modes, loaded markers and more. + + Expected video stream image size is taken directly from the supplied ARParamLT + structure's xsize and ysize fields. Video stream image pixel format defaults to + AR_DEFAULT_PIXEL_FORMAT, which is platform and video-module dependent. Usually + a call to arSetPixelFormat() is advisable to set the correct format. + + After creation of the ARHandle, tracking settings should be set via appropriate + calls to other arSet*() functions. + + The ARHandle should be disposed of via a call to arDeleteHandle when tracking + with this instance is complete. + @param paramLT The created handle will hold a pointer to the calibrated + camera parameters specified by this parameter. This parameter uses the new + lookup-table based form of the camera parameters introduced in ARToolKit v5. + An ARParamLT structure may be created from an ARParam structure via the + call: + ARParamLT *paramLT = arParamLTCreate(¶m, AR_PARAM_LT_DEFAULT_OFFSET); + Note that the pointer is only copied, and so the ARParamLT structure must remain + valid until the ARHandle is disposed of by calling arDeleteHandle. + @result An ARHandle which should be passed to other functions which + deal with the operations of the ARToolKit tracker. + @seealso arSetPixelFormat arSetPixelFormat + @seealso arDeleteHandle arDeleteHandle +*/ +ARHandle *arCreateHandle( ARParamLT *paramLT ); + +/*! + @function + @abstract Delete a handle which holds settings for an ARToolKit tracker instance. + @discussion The calibrated camera parameters pointed to by the handle are + NOT deleted by this operation. + @param handle The handle to delete, as created by arCreateHandle(); + @result 0 if no error occured. + @seealso arCreateHandle arCreateHandle +*/ +int arDeleteHandle( ARHandle *handle ); + +/*! + @function + @abstract Enable or disable ARToolKit's debug mode. + @discussion In debug mode, ARToolKit offers additional error reporting. Use + this function to enable or disable debug mode at runtime. + + Additionally, in debug mode, ARToolKit creates a mono (8-bit grayscale) + image of the thresholded video input, and makes this available + through the field ARHandle->labelInfo.bwImage. + @param handle An ARHandle referring to the current AR tracker + to be queried for its debug mode. + @param mode + Options for this field are: + AR_DEBUG_DISABLE + AR_DEBUG_ENABLE + The default mode is AR_DEBUG_DISABLE. + @result 0 if no error occured. +*/ +int arSetDebugMode( ARHandle *handle, int mode ); + +/*! + @function + @abstract Find out whether ARToolKit's debug mode is enabled. + @discussion See arSetDebugMode() for more info. + @param handle An ARHandle referring to the current AR tracker + to be queried for its mode. + @param mode Pointer into which will be placed the + value representing the mode. + @result 0 if no error occured. +*/ +int arGetDebugMode( ARHandle *handle, int *mode ); + +/*! + @function + @abstract Select between detection of black markers and white markers. + @discussion + ARToolKit's labelling algorithm can work with both black-bordered + markers on a white background (AR_LABELING_BLACK_REGION) or + white-bordered markers on a black background (AR_LABELING_WHITE_REGION). + This function allows you to specify the type of markers to look for. + Note that this does not affect the pattern-detection algorith + which works on the interior of the marker. + @param handle An ARHandle referring to the current AR tracker + to have its labeling mode set. + @param mode + Options for this field are: + AR_LABELING_WHITE_REGION + AR_LABELING_BLACK_REGION + The default mode is AR_LABELING_BLACK_REGION. + @result 0 if no error occured. + */ +int arSetLabelingMode( ARHandle *handle, int mode ); + +/*! + @function + @abstract Enquire whether detection is looking for black markers or white markers. + @discussion See discussion for arSetLabelingMode. + @param handle An ARHandle referring to the current AR tracker + to be queried for its labeling mode. + @param mode Pointer into which will be placed the + value representing the mode. + @result 0 if no error occured. +*/ +int arGetLabelingMode( ARHandle *handle, int *mode ); + +/*! + @function + @abstract Set the labeling threshhold. + @discussion + This function forces sets the threshold value. + The default value is AR_DEFAULT_LABELING_THRESH which is 100, + unless edited in arConfig.h. + + The current threshold mode is not affected by this call. + Typically, this function is used when labeling threshold mode + is AR_LABELING_THRESH_MODE_MANUAL. + + The threshold value is not relevant if threshold mode is + AR_LABELING_THRESH_MODE_AUTO_ADAPTIVE. + + Background: The labeling threshold is the value which + the AR library uses to differentiate between black and white + portions of an ARToolKit marker. Since the actual brightness, + contrast, and gamma of incoming images can vary signficantly + between different cameras and lighting conditions, this + value typically needs to be adjusted dynamically to a + suitable midpoint between the observed values for black + and white portions of the markers in the image. + @param handle An ARHandle referring to the current AR tracker + to have its labeling threshold value set. + @param thresh An integer in the range [0,255] (inclusive). + @result 0 if no error occured. +*/ +int arSetLabelingThresh( ARHandle *handle, int thresh ); + +/*! + @function + @abstract Get the current labeling threshold. + @discussion + This function queries the current labeling threshold. For, + AR_LABELING_THRESH_MODE_AUTO_MEDIAN, AR_LABELING_THRESH_MODE_AUTO_OTSU, + and AR_LABELING_THRESH_MODE_AUTO_BRACKETING + the threshold value is only valid until the next auto-update. + + The current threshold mode is not affected by this call. + + The threshold value is not relevant if threshold mode is + AR_LABELING_THRESH_MODE_AUTO_ADAPTIVE. + @param handle An ARHandle referring to the current AR tracker + to be queried for its labeling threshold value. + @param thresh Pointer into which will be placed the + value of the labeling threshhold. + An integer in the range [0,255] (inclusive) + @result 0 if no error occured. + @seealso arSetLabelingThresh arSetLabelingThresh +*/ +int arGetLabelingThresh( ARHandle *handle, int *thresh ); + +/*! + @function + @abstract Set the labeling threshold mode (auto/manual). + @discussion + @param handle An ARHandle referring to the current AR tracker + to be queried for its labeling threshold mode. + @param mode An integer specifying the mode. One of: + AR_LABELING_THRESH_MODE_MANUAL, + AR_LABELING_THRESH_MODE_AUTO_MEDIAN, + AR_LABELING_THRESH_MODE_AUTO_OTSU, + AR_LABELING_THRESH_MODE_AUTO_ADAPTIVE, + AR_LABELING_THRESH_MODE_AUTO_BRACKETING + @result 0 if no error occured. + @seealso arSetLabelingThresh arSetLabelingThresh + */ +int arSetLabelingThreshMode(ARHandle *handle, const AR_LABELING_THRESH_MODE mode); + +/*! + @function + @abstract Get the labeling threshold mode (auto/manual). + @discussion + @param handle An ARHandle referring to the current AR tracker + to be queried for its labeling threshold value. + @param mode_p Pointer into which will be placed the + value of the labeling threshold mode, one of: + AR_LABELING_THRESH_MODE_MANUAL, + AR_LABELING_THRESH_MODE_AUTO_MEDIAN, + AR_LABELING_THRESH_MODE_AUTO_OTSU, + AR_LABELING_THRESH_MODE_AUTO_ADAPTIVE, + AR_LABELING_THRESH_MODE_AUTO_BRACKETING + @result 0 if no error occured. + @seealso arSetLabelingThresh arSetLabelingThresh + */ +int arGetLabelingThreshMode(const ARHandle *handle, AR_LABELING_THRESH_MODE *mode_p); + +/*! + @function + @abstract Set the number of frames between auto-threshold calculations. + @discussion + This is the number of frames BETWEEN calculations, meaning that the + calculation occurs every (interval + 1) frames. + @param handle An ARHandle referring to the current AR tracker + for which the labeling threshold auto interval will be set. + @param interval The interval, specifying the number of frames between + automatic updates to the threshold. + An integer in the range [0,INT_MAX] (inclusive). Default + value is AR_LABELING_THRESH_AUTO_INTERVAL_DEFAULT. + @result 0 if no error occured. + @seealso arGetLabelingThreshModeAutoInterval arGetLabelingThreshModeAutoInterval + */ +int arSetLabelingThreshModeAutoInterval(ARHandle *handle, const int interval); + +/*! + @function + @abstract Get the number of frames between auto-threshold calculations. + @discussion + This is the number of frames BETWEEN calculations, meaning that the + calculation occurs every (interval + 1) frames. + @param handle An ARHandle referring to the current AR tracker + to be queried for its labeling threshold auto interval value. + @param interval_p Pointer into which will be placed the + value of the labeling threshhold auto interval. + An integer in the range [0,INT_MAX] (inclusive) + @result 0 if no error occured. + @seealso arSetLabelingThreshModeAutoInterval arSetLabelingThreshModeAutoInterval + */ +int arGetLabelingThreshModeAutoInterval(const ARHandle *handle, int *interval_p); + +/*! + @function + @abstract Set the image processing mode. + @discussion + When ARthe image processing mode is AR_IMAGE_PROC_FRAME_IMAGE, + ARToolKit processes all pixels in each incoming image + to locate markers. When the mode is AR_IMAGE_PROC_FIELD_IMAGE, + ARToolKit processes pixels in only every second pixel row and + column. This is useful both for handling images from interlaced + video sources (where alternate lines are assembled from alternate + fields and thus have one field time-difference, resulting in a + "comb" effect) such as Digital Video cameras. + The effective reduction by 75% in the pixels processed also + has utility in accelerating tracking by effectively reducing + the image size to one quarter size, at the cost of pose accuraccy. + @param handle An ARHandle referring to the current AR tracker + to have its mode set. + @param mode + Options for this field are: + AR_IMAGE_PROC_FRAME_IMAGE + AR_IMAGE_PROC_FIELD_IMAGE + The default mode is AR_IMAGE_PROC_FRAME_IMAGE. + @result 0 if no error occured. +*/ +int arSetImageProcMode( ARHandle *handle, int mode ); +/*! + @function + @abstract Get the image processing mode. + @discussion + See arSetImageProcMode() for a complete description. + @param handle An ARHandle referring to the current AR tracker + to be queried for its mode. + @param mode Pointer into which will be placed the + value representing the current image processing mode. + @result 0 if no error occured. +*/ +int arGetImageProcMode( ARHandle *handle, int *mode ); + +/*! + @function + @abstract Set the pattern detection mode + @discussion + The pattern detection determines the method by which ARToolKit + matches detected squares in the video image to marker templates + and/or IDs. ARToolKit v4.x can match against pictorial "template" markers, + whose pattern files are created with the mk_patt utility, in either colour + or mono, and additionally can match against 2D-barcode-type "matrix" + markers, which have an embedded marker ID. Two different two-pass modes + are also available, in which a matrix-detection pass is made first, + followed by a template-matching pass. + @param handle An ARHandle referring to the current AR tracker + to have its mode set. + @param mode + Options for this field are: + AR_TEMPLATE_MATCHING_COLOR + AR_TEMPLATE_MATCHING_MONO + AR_MATRIX_CODE_DETECTION + AR_TEMPLATE_MATCHING_COLOR_AND_MATRIX + AR_TEMPLATE_MATCHING_MONO_AND_MATRIX + The default mode is AR_TEMPLATE_MATCHING_COLOR. + @result 0 if no error occured. +*/ +int arSetPatternDetectionMode( ARHandle *handle, int mode ); + +/*! + @function + @abstract Get the pattern detection mode + @discussion + See arSetPatternDetectionMode() for a complete description. + @param handle An ARHandle referring to the current AR tracker + to be queried for its mode. + @param mode Pointer into which will be placed the + value representing the mode. + @result 0 if no error occured. +*/ +int arGetPatternDetectionMode( ARHandle *handle, int *mode ); + +/*! + @function + @abstract Set the size and ECC algorithm to be used for matrix code (2D barcode) marker detection. + @discussion + When matrix-code (2D barcode) marker detection is enabled (see arSetPatternDetectionMode) + then the size of the barcode pattern and the type of error checking and correction (ECC) + with which the markers were produced can be set via this function. + + This setting is global to a given ARHandle; It is not possible to have two different matrix + code types in use at once. + @param handle An ARHandle referring to the current AR tracker to have its mode set. + @param type The type of matrix code (2D barcode) in use. Options include: + AR_MATRIX_CODE_3x3 + AR_MATRIX_CODE_3x3_HAMMING63 + AR_MATRIX_CODE_3x3_PARITY65 + AR_MATRIX_CODE_4x4 + AR_MATRIX_CODE_4x4_BCH_13_9_3 + AR_MATRIX_CODE_4x4_BCH_13_5_5 + The default mode is AR_MATRIX_CODE_3x3. + @seealso arSetPatternDetectionMode arSetPatternDetectionMode + @seealso arGetMatrixCodeType arGetMatrixCodeType + @result 0 if no error occured. +*/ +int arSetMatrixCodeType(ARHandle *handle, const AR_MATRIX_CODE_TYPE type); + +/*! + @function + @abstract Get the size and ECC algorithm being used for matrix code (2D barcode) marker detection. + @discussion See the description for arSetMatrixCodeType(). + @param handle An ARHandle referring to the current AR tracker to be queried for its mode. + @param type_p Pointer into which will be placed the value representing the mode. + @seealso arGetPatternDetectionMode arGetPatternDetectionMode + @seealso arSetMatrixCodeType arSetMatrixCodeType + @result 0 if no error occured. +*/ +int arGetMatrixCodeType(ARHandle *handle, AR_MATRIX_CODE_TYPE *type_p); + +/*! + @function + @abstract Set the marker extraction mode + @discussion (description) + @param handle An ARHandle referring to the current AR tracker to have its mode set. + @param mode + Options for this field are: + AR_USE_TRACKING_HISTORY + AR_NOUSE_TRACKING_HISTORY + AR_USE_TRACKING_HISTORY_V2 + The default mode is AR_USE_TRACKING_HISTORY_V2. + @result 0 if no error occured. + */ +int arSetMarkerExtractionMode( ARHandle *handle, int mode ); + +/*! + @function + @abstract Get the marker extraction mode + @discussion (description) + @param handle An ARHandle referring to the current AR tracker to be queried for its mode. + @param mode Pointer into which will be placed the value representing the mode. + @result 0 if no error occured. + */ +int arGetMarkerExtractionMode( ARHandle *handle, int *mode ); + +/*! + @function + @abstract Set the border size. + @discussion N.B. Deprecated in favour of arSetPattRatio(), but retained for + backwards compatibility. + @param handle An ARHandle referring to the current AR tracker + to have its border size set. + @param borderSize The border size. To set the default, pass (1.0 - 2*AR_PATT_RATIO). + If compatibility with ARToolKit verions 1.0 through 4.4 is required, this value + must be 0.25. + @result 0 if no error occured. + */ +int arSetBorderSize( ARHandle *handle, const ARdouble borderSize ); + +/*! + @function + @abstract Get the border size. + @discussion N.B. Deprecated in favour of arGetPattRatio(), but retained for + backwards compatibility. + @param handle An ARHandle referring to the current AR tracker + to be queried for its border size. + @param borderSize Pointer into which will be placed the + value representing the border size. The default border size for newly-created + ARHandle structures is AR_BORDER_SIZE_DEFAULT. + @result 0 if no error occured. + */ +int arGetBorderSize( ARHandle *handle, ARdouble *borderSize ); + +/*! + @function + @abstract Set the width/height of the marker pattern space, as a proportion of marker width/height. + @discussion N.B. Supercedes arSetBorderSize(). + @param handle An ARHandle referring to the current AR tracker to be modified. + @param pattRatio The the width/height of the marker pattern space, as a proportion of marker + width/height. To set the default, pass AR_PATT_RATIO. + If compatibility with ARToolKit verions 1.0 through 4.4 is required, this value + must be 0.5. + @result 0 if no error occured. + */ +int arSetPattRatio( ARHandle *handle, const ARdouble pattRatio ); + +/*! + @function + @abstract Get the width/height of the marker pattern space, as a proportion of marker width/height. + @discussion N.B. Supercedes arGetBorderSize(). + @param handle An ARHandle referring to the current AR tracker to be queried. + @param pattRatio Pointer into which will be placed the + value representing the width/height of the marker pattern space, as a proportion of marker + width/height. The default border size for newly-created ARHandle structures is AR_PATT_RATIO. + @result 0 if no error occured. + */ +int arGetPattRatio( ARHandle *handle, ARdouble *pattRatio ); + +/*! + @function + @abstract Set the expected pixel format for video frames being passed to arDetectMarker + @discussion + This function should be used at least once after creation of an ARHandle, to set the pixel + format with which images will be passed to arDetectMarker(). If not called, the default value + AR_DEFAULT_PIXEL_FORMAT will be used. Note that AR_DEFAULT_PIXEL_FORMAT varies depending on + platform and video module. If the pixel format of incoming video images changes, this value + must also be changed. + @param handle Handle to settings structure in which to set the pixel format. + @param pixFormat Value representing the format of pixels to be + processed by the ARToolKit detection routines. See AR_PIXEL_FORMAT + reference for more information. + @result 0 if no error occured. + @seealso arGetPixelFormat arGetPixelFormat + @seealso arCreateHandle arCreateHandle + @seealso arDetectMarker arDetectMarker + */ +int arSetPixelFormat( ARHandle *handle, AR_PIXEL_FORMAT pixFormat ); + +/*! + @function + @abstract Get the expected pixel format for video frames being passed to arDetectMarker + @discussion + See discussion for arSetPixelFormat(). + @param handle Handle to AR settings structure from which to retrieve the pixel format. + @param pixFormat Pointer into which will be placed the + value representing the format of pixels being + processed by the ARToolKit detection routines. See AR_PIXEL_FORMAT + reference for more information. + @result 0 if no error occured. + @seealso arSetPixelFormat arSetPixelFormat + @seealso arCreateHandle arCreateHandle + @seealso arDetectMarker arDetectMarker + */ +int arGetPixelFormat( ARHandle *handle, AR_PIXEL_FORMAT *pixFormat ); + + +/*! + @function + @abstract Detect markers in a video frame. + @discussion + This is the core ARToolKit marker detection function. It calls through to a set of + internal functions to perform the key marker detection steps of binarization and + labelling, contour extraction, and template matching and/or matrix code extraction. + + Typically, the resulting set of detected markers is retrieved by calling arGetMarkerNum + to get the number of markers detected and arGetMarker to get an array of ARMarkerInfo + structures with information on each detected marker, followed by a step in which + detected markers are possibly examined for some measure of goodness of match (e.g. by + examining the match confidence value) and pose extraction. + + @param arHandle Handle to initialised settings, including camera parameters, + incoming video image size and pixel format, markers, detection modes and other information. + @param dataPtr Pointer to the first byte of a block of memory containing pixel + data for an image which is to be processed for marker detection. The format of + pixels in this image is specified by arSetPixelFormat(). The width and height of + the image are specified by the xsize and ysize parameters of the camera parameters + held in arHandle. + @result 0 if the function proceeded without error, or a value less than 0 in case of error. + A result of 0 does not however, imply any markers were detected. + @seealso arCreateHandle arCreateHandle + @seealso arGetMarkerNum arGetMarkerNum + @seealso arGetMarker arGetMarker + */ +int arDetectMarker( ARHandle *arHandle, ARUint8 *dataPtr ); + +/*! + @function + @abstract Get the number of markers detected in a video frame. + @discussion + + @result The number of detected markers in the most recent image passed to arDetectMarker. + Note that this is actually a count, not an index. A better name for this function would be + arGetDetectedMarkerCount, but the current name lives on for historical reasons. + @param arHandle Handle upon which arDetectMarker has been called. + @seealso arGetMarker arGetMarker + @seealso ARMarkerInfo ARMarkerInfo + @seealso arDetectMarker arDetectMarker + */ +int arGetMarkerNum( ARHandle *arHandle ); + +/*! + @function + @abstract Get information on the markers detected in a video frame. + @discussion + @result An array (of length arGetMarkerNum(arHandle)) of ARMarkerInfo structs. + A better name for this function would be arGetDetectedMarkerInfo, but the current name lives + on for historical reasons. + @param arHandle Handle upon which arDetectMarker has been called. + @seealso arGetMarkerNum arGetMarkerNum + @seealso ARMarkerInfo ARMarkerInfo + @seealso arDetectMarker arDetectMarker + */ +ARMarkerInfo *arGetMarker( ARHandle *arHandle ); + +/* ------------------------------ */ + +int arLabeling( ARUint8 *image, int xsize, int ysize, int pixelFormat, + int debugMode, int labelingMode, int labelingThresh, int imageProcMode, + ARLabelInfo *labelInfo, ARUint8 *image_thresh ); +int arDetectMarker2( int xsize, int ysize, ARLabelInfo *labelInfo, int imageProcMode, + int areaMax, int areaMin, ARdouble squareFitThresh, + ARMarkerInfo2 *markerInfo2, int *marker2_num ); +/*! + @function + @abstract Examine a set of detected squares for match with known markers. + @discussion + Performs the intermediate marker-detection stage of taking detected squares in a processed image, and + matching the interior of these squares against known marker templates, or extracting matrix codes from + the interior of the square. + @param image Image in which squares were detected. + @param xsize Horizontal dimension of image, in pixels. + @param ysize Vertical dimension of image, in pixels. + @param pixelFormat Format of pixels in image. See <AR/config.h> for values. + @param markerInfo2 Pointer to an array of ARMarkerInfo2 structures holding information on detected squares which are candidates for marker matching. + @param marker2_num Size of markerInfo2 array. + @param pattHandle Handle to loaded patterns for template matching against detected squares. + @param imageProcMode Indicates whether square detection was performed treating the image as a frame or a field. + @param pattDetectMode Whether to perform color/mono template matching, matrix code detection, or both. + @param arParamLTf Lookup table for the camera parameters for the optical source from which the image was acquired. See arParamLTCreate. + @param pattRatio A value between 0.0 and 1.0, representing the proportion of the marker width which constitutes the pattern. In earlier versions, this value was fixed at 0.5. + @param markerInfo Output: Pointer to an array of ARMarkerInfo structures holding information on successful matches. + @param marker_num Output: Size of markerInfo array. + @param matrixCodeType When matrix code pattern detection mode is active, indicates the type of matrix code to detect. + @result 0 in case of no error, or -1 otherwise. + @seealso arParamLTCreate arParamLTCreate + */ +int arGetMarkerInfo( ARUint8 *image, int xsize, int ysize, int pixelFormat, + ARMarkerInfo2 *markerInfo2, int marker2_num, + ARPattHandle *pattHandle, int imageProcMode, int pattDetectMode, ARParamLTf *arParamLTf, ARdouble pattRatio, + ARMarkerInfo *markerInfo, int *marker_num, + const AR_MATRIX_CODE_TYPE matrixCodeType ); + +int arGetContour( AR_LABELING_LABEL_TYPE *lImage, int xsize, int ysize, int *label_ref, int label, + int clip[4], ARMarkerInfo2 *marker_info2 ); +int arGetLine( int x_coord[], int y_coord[], int coord_num, int vertex[], ARParamLTf *paramLTf, + ARdouble line[4][3], ARdouble v[4][2] ); + + +/***********************************/ +/* */ +/* For pattern identification */ +/* */ +/***********************************/ + +/*! + @functiongroup "Pattern identification". + */ +/*! + @function + @abstract Allocate a pattern handle. + @discussion Allocates an empty pattern handle, into which patterns can + be loaded by calling arPattLoad(). + When the pattern handle is no longer needed, it should be + freed by calling arPattDeleteHandle(). + + Note that a pattern handle is NOT required when using only matrix- + code (2D barcode) markers. + @seealso arPattLoad arPattLoad + @seealso arPattDeleteHandle arPattDeleteHandle + @result The created pattern handle, or NULL in case of error. +*/ +ARPattHandle *arPattCreateHandle(void); + +/*! + @function + @abstract Allocate a pattern handle and set pattern template size and maximum number of patterns loadable. + @discussion Allocates an empty pattern handle, into which patterns can + be loaded by calling arPattLoad(). + When the pattern handle is no longer needed, it should be + freed by calling arPattDeleteHandle(). + + Note that a pattern handle is NOT required when using only matrix- + code (2D barcode) markers. + @param pattSize For any square template (pattern) markers, the number of rows and + columns in the template. May not be less than 16 or more than AR_PATT_SIZE1_MAX. + + Pass AR_PATT_SIZE1 for the same behaviour as arPattCreateHandle(). + @param patternCountMax For any square template (pattern) markers, the maximum number of + markers that may be loaded for a single matching pass. Must be > 0. + + Pass AR_PATT_NUM_MAX for the same behaviour as arPattCreateHandle(). + @seealso arPattLoad arPattLoad + @seealso arPattDeleteHandle arPattDeleteHandle + @result The created pattern handle, or NULL in case of error. +*/ + +ARPattHandle *arPattCreateHandle2(const int pattSize, const int patternCountMax); + +/*! + @function + @abstract Free all loaded patterns and pattern handle. + @discussion Frees a pattern handle, freeing (unloading) + any patterns loaded into the handle in the process. + @param pattHandle The handle to free. + @result 0 on success, or -1 if trying to free a NULL handle. +*/ +int arPattDeleteHandle(ARPattHandle *pattHandle); + +/*! + @function + @abstract Load a pattern file into a pattern handle. + @discussion + This function loads a pattern template from a file on disk, and attaches + it to the given ARPattHandle so making it available for future pattern-matching. + Additional patterns can be loaded by calling again with the same + ARPattHandle (however no more than AR_PATT_NUM_MAX patterns can be attached + to a single ARPattHandle). Patterns are initially loaded + in an active state. + + Note that matrix-code (2D barcode) markers do not have any associated + pattern file and do not need to be loaded. + @param pattHandle Pattern handle, as generated by arPattCreateHandle(), + into which the pattern file infomation will be loaded. + @param filename Pathname of pattern file to load. The pattern file + is typically generated by the make_patt program. The pathname is + relative to the current working directory, which is operating system- + specific. + @seealso arPattCreateHandle arPattCreateHandle + @seealso arPattActivate arPattActivate + @seealso arPattDeactivate arPattDeactivate + @seealso arPattFree arPattFree + @result Returns the index number of the loaded pattern, in the range + [0, AR_PATT_NUM_MAX - 1], or -1 if the pattern could not be loaded + because the maximum number of patterns (AR_PATT_NUM_MAX) has already been + loaded already into this handle. +*/ +int arPattLoad( ARPattHandle *pattHandle, const char *filename ); + +int arPattLoadFromBuffer(ARPattHandle *pattHandle, const char *buffer); + +/*! + @function + @abstract Save a pattern to a pattern file. + @discussion This function is used by the make_patt utility. See the + sourcecode to mk_patt for usage. + @param image (description) + @param xsize (description) + @param ysize (description) + @param pixelFormat (description) + @param paramLTf (description) + @param imageProcMode (description) + @param marker_info (description) + @param pattRatio A value between 0.0 and 1.0, representing the proportion of the marker width which constitutes the pattern. In earlier versions, this value was fixed at 0.5. + @param pattSize The number of rows and columns to create in the pattern. Normally AR_PATT_SIZE1. + @param filename (description) + @result (description) + */ +int arPattSave( ARUint8 *image, int xsize, int ysize, int pixelFormat, ARParamLTf *paramLTf, + int imageProcMode, ARMarkerInfo *marker_info, ARdouble pattRatio, int pattSize, const char *filename ); + +/*! + @function + @abstract Frees (unloads) a pattern file from memory. + @discussion Unloads a pattern from a pattern handle, freeing that + slot for another pattern to be loaded, if necessary. + @param pattHandle The pattern handle to unload from. + @param patno The index into the pattern handle's array of + patterns to the pattern to be unloaded. + @result 0 if the pattern was successfully unloaded, or -1 + if there was no pattern loaded. + @seealso arPattLoad arPattLoad + */ +int arPattFree( ARPattHandle *pattHandle, int patno ); + +/*! + @function + @abstract Activate a previously deactivated pattern. + @discussion When a pattern is activated, is becomes available + for recognition in a scene. This is the default state + for a loaded pattern. + @param pattHandle The handle holding the loaded pattern + which is to be reactivated. + @param patno The index into the pattern handle's array of + patterns to the pattern to be reactivated. + @result 0 on success, or -1 if the pattern was already + activated or no pattern was loaded. + @seealso arPattDeactivate arPattDeactivate +*/ +int arPattActivate( ARPattHandle *pattHandle, int patno ); + +/*! + @function + @abstract Deactivate a previously activated pattern. + @discussion When a pattern is activated, is becomes unavailable + for recognition in a scene. Deactivating unused patterns + can speed up recognition time and accuracy when there are + multiple patterns in a scene, and it is also useful for + controlling interactivity in a scene. + @param pattHandle The handle holding the loaded pattern + which is to be deactivated. + @param patno The index into the pattern handle's array of + patterns to the pattern to be deactivated. + @result 0 on success, or -1 if the pattern was already + deactivated or no pattern was loaded. + @seealso arPattActivate arPattActivate +*/ +int arPattDeactivate(ARPattHandle *pattHandle, int patno); + +/*! + @function + @abstract Associate a set of patterns with an ARHandle. + @discussion Associating a set of patterns with an ARHandle makes + the patterns the set which will be searched when marker + identification is performed on an image associated with the + same ARHandle. + @param arHandle (description) + @param pattHandle (description) + @seealso arPattDetach arPattDetach + @result Returns 0 in the case of success, or -1 if the specified + ARHandle already has an ARPattHandle attached, or if arHandle is NULL. +*/ +int arPattAttach(ARHandle *arHandle, ARPattHandle *pattHandle); + +/*! + @function + @abstract Reset an ARHandle to no pattern association. + @discussion See arPattAttach() for more information. + @param arHandle (description) + @seealso arPattAttach arPattAttach + @result Returns 0 in the case of success, or -1 if the specified + ARHandle has no ARPattHandle attached, or if arHandle is NULL. +*/ +int arPattDetach(ARHandle *arHandle); + +//int arPattGetPattRatio( ARPattHandle *pattHandle, float *ratio ); +//int arPattSetPattRatio( ARPattHandle *pattHandle, float ratio ); + +/* ------------------------------ */ + +#if !AR_DISABLE_NON_CORE_FNS +int arPattGetID( ARPattHandle *pattHandle, int imageProcMode, int pattDetectMode, + ARUint8 *image, int xsize, int ysize, AR_PIXEL_FORMAT pixelFormat, + int *x_coord, int *y_coord, int *vertex, ARdouble pattRatio, + int *code, int *dir, ARdouble *cf, const AR_MATRIX_CODE_TYPE matrixCodeType ); +int arPattGetImage( int imageProcMode, int pattDetectMode, int patt_size, int sample_size, + ARUint8 *image, int xsize, int ysize, AR_PIXEL_FORMAT pixelFormat, + int *x_coord, int *y_coord, int *vertex, ARdouble pattRatio, + ARUint8 *ext_patt ); + +/*! + @function + @abstract Match the interior of a detected square against known patterns. + @discussion + @param pattHandle Handle contained details of known patterns, i.e. loaded templates, or valid barcode IDs. + @param imageProcMode See discussion of arSetImageProcMode(). + @param pattDetectMode See discussion of arSetPatternDetectionMode(). + @param image Pointer to packed raw image data. + @param xsize Horizontal pixel dimension of raw image data. + @param ysize Vertical pixel dimension of raw image data. + @param pixelFormat Pixel format of raw image data. + @param arParamLTf Lookup table for the camera parameters for the optical source from which the image was acquired. See arParamLTCreate. + @param vertex 4x2 array of points which correspond to the x and y locations of the corners of the detected marker square. + @param pattRatio A value between 0.0 and 1.0, representing the proportion of the marker width which constitutes the pattern. In earlier versions, this value was fixed at 0.5. + @param codePatt Where the pattern matching mode includes template (picture) matching, and a valid template is matched, the ID of the pattern from pattHandle, or -1 if not identified. + @param dirPatt Where the pattern matching mode includes template (picture) matching, and a valid template is matched, the direction (up, right, down, left) of the pattern from pattHandle. + @param cfPatt Where the pattern matching mode includes template (picture) matching, and a valid template is matched, the confidence factor of the match (range [0.0 - 1.0]). + @param codeMatrix Where the pattern matching mode includes matrix (barcode) matching, and a valid matrix is matched, the ID of the pattern, or -1 if not identified. + @param dirMatrix Where the pattern matching mode includes matrix (barcode) matching, and a valid matrix is matched, the direction (up, right, down, left) of the pattern. + @param cfMatrix Where the pattern matching mode includes matrix (barcode) matching, and a valid matrix is matched, the confidence factor of the match (range [0.0 - 1.0]). + @param matrixCodeType When matrix code pattern detection mode is active, indicates the type of matrix code to detect. + @result 0 if the function was able to correctly match, or -1 in case of error or no match. + @seealso arParamLTCreate arParamLTCreate + */ +int arPattGetID2( ARPattHandle *pattHandle, int imageProcMode, int pattDetectMode, + ARUint8 *image, int xsize, int ysize, AR_PIXEL_FORMAT pixelFormat, ARParamLTf *arParamLTf, ARdouble vertex[4][2], ARdouble pattRatio, + int *codePatt, int *dirPatt, ARdouble *cfPatt, int *codeMatrix, int *dirMatrix, ARdouble *cfMatrix, + const AR_MATRIX_CODE_TYPE matrixCodeType ); +#endif // !AR_DISABLE_NON_CORE_FNS + +/*! + @function + @abstract Match the interior of a detected square against known patterns with variable border width. + @discussion + @param pattHandle Handle contained details of known patterns, i.e. loaded templates, or valid barcode IDs. + @param imageProcMode See discussion of arSetImageProcMode(). + @param pattDetectMode See discussion of arSetPatternDetectionMode(). + @param image Pointer to packed raw image data. + @param xsize Horizontal pixel dimension of raw image data. + @param ysize Vertical pixel dimension of raw image data. + @param pixelFormat Pixel format of raw image data. + @param arParamLTf Lookup table for the camera parameters for the optical source from which the image was acquired. See arParamLTCreate. + @param vertex 4x2 array of points which correspond to the x and y locations of the corners of the detected marker square. + @param pattRatio A value between 0.0 and 1.0, representing the proportion of the marker width which constitutes the pattern. In earlier versions, this value was fixed at 0.5. + @param codePatt Where the pattern matching mode includes template (picture) matching, and a valid template is matched, the ID of the pattern from pattHandle, or -1 if not identified. + @param dirPatt Where the pattern matching mode includes template (picture) matching, and a valid template is matched, the direction (up, right, down, left) of the pattern from pattHandle. + @param cfPatt Where the pattern matching mode includes template (picture) matching, and a valid template is matched, the confidence factor of the match (range [0.0 - 1.0]). + @param codeMatrix Where the pattern matching mode includes matrix (barcode) matching, and a valid matrix is matched, the ID of the pattern, or -1 if not identified. + @param dirMatrix Where the pattern matching mode includes matrix (barcode) matching, and a valid matrix is matched, the direction (up, right, down, left) of the pattern. + @param cfMatrix Where the pattern matching mode includes matrix (barcode) matching, and a valid matrix is matched, the confidence factor of the match (range [0.0 - 1.0]). + @param matrixCodeType When matrix code pattern detection mode is active, indicates the type of matrix code to detect. + @param errorCorrected Pointer to an integer which will be filled out with the number of errors detected and corrected during marker identification, or NULL if this information is not required. + @param codeGlobalID_p Pointer to uint64_t which will be filled out with the global ID, or NULL if this value is not required. + @result 0 if the function was able to correctly match, or -1 in case of error or no match. + @seealso arParamLTCreate arParamLTCreate + */ +int arPattGetIDGlobal( ARPattHandle *pattHandle, int imageProcMode, int pattDetectMode, + ARUint8 *image, int xsize, int ysize, AR_PIXEL_FORMAT pixelFormat, ARParamLTf *arParamLTf, ARdouble vertex[4][2], ARdouble pattRatio, + int *codePatt, int *dirPatt, ARdouble *cfPatt, int *codeMatrix, int *dirMatrix, ARdouble *cfMatrix, + const AR_MATRIX_CODE_TYPE matrixCodeType, int *errorCorrected, uint64_t *codeGlobalID_p ); + +/*! + @function + @abstract Extract the image (i.e. locate and unwarp) of the pattern-space portion of a detected square. + @discussion + @param imageProcMode See discussion of arSetImageProcMode(). + @param pattDetectMode See discussion of arSetPatternDetectionMode(). + @param patt_size The number of horizontal and vertical units to subdivide the pattern-space into. + @param sample_size At present, must always be the square of patt_size. + @param image Pointer to packed raw image data. + @param xsize Horizontal pixel dimension of raw image data. + @param ysize Vertical pixel dimension of raw image data. + @param pixelFormat Pixel format of raw image data. + @param arParamLTf Lookup table for the camera parameters for the optical source from which the image was acquired. See arParamLTCreate. + @param vertex 4x2 array of points which correspond to the x and y locations of the corners of the detected marker square. + @param pattRatio A value between 0.0 and 1.0, representing the proportion of the marker width which constitutes the pattern. In earlier versions, this value was fixed at 0.5. + @param ext_patt Pointer to an array of appropriate size (i.e. patt_size*patt_size*3), which will be filled with the extracted image. Where a colour image is available, it will be supplied in BGR byte order. + @result 0 if the function was able to correctly get the image, or -1 in case of error or no match. + @seealso arParamLTCreate arParamLTCreate + */ +int arPattGetImage2( int imageProcMode, int pattDetectMode, int patt_size, int sample_size, + ARUint8 *image, int xsize, int ysize, AR_PIXEL_FORMAT pixelFormat, ARParamLTf *arParamLTf, + ARdouble vertex[4][2], ARdouble pattRatio, ARUint8 *ext_patt ); + +/*! + @function + @abstract Extract the image (i.e. locate and unwarp) of an arbitrary portion of a detected square. + @discussion Use this function to obtain an image of the marker pattern space for display to the user. + @param arHandle The ARHandle structure associated with the current tracking data. + @param markerNo The marker number (in range 0 to arHandle->marker_num - 1, inclusive) from which to extract the pattern. + @param image The source video image. + @param rect Pointer to an ARPattRectInfo structure which defines the portion of the marker image to extract. + @param xsize Width of the output image, in pixels. + @param ysize Height of the output image, in pixels. + @param overSampleScale Number of samples to acquire per destination pixel, e.g. 2. + @param outImage Pointer to a buffer, at least xsize*ysize*arUtilGetPixelSize(arHandle->arPixelFormat) bytes in size, which will be filled out with the marker image. + @result 0 if the function was able to correctly get the image, or -1 in case of error or no match. + @seealso ARPattRectInfo ARPattRectInfo + */ +int arPattGetImage3( ARHandle *arHandle, int markerNo, ARUint8 *image, ARPattRectInfo *rect, int xsize, int ysize, + int overSampleScale, ARUint8 *outImage ); + + +/***********************************/ +/* */ +/* For 3D calculation */ +/* */ +/***********************************/ + +/*! + @functiongroup "3D calculation". + */ + +/*! + @function + @abstract Create handle used for 3D calculation from calibrated camera parameters. + @discussion + An AR3DHandle holds data structures used in calculating the 3D pose of a + marker from the 2D location of its corners (i.e. pose estimation). + @param arParam (description) + @result The handle. When no more ar3D*() functions need be called, the handle should be deleted + by calling ar3DDeleteHandle(). + @seealso ar3DCreateHandle2 ar3DCreateHandle2 + @seealso ar3DDeleteHandle ar3DDeleteHandle +*/ +AR3DHandle *ar3DCreateHandle(ARParam *arParam); + +/*! + @function + @abstract Create handle used for 3D calculation from an intrinsic parameters matrix. + @discussion + An AR3DHandle holds data structures used in calculating the 3D pose of a + marker from the 2D location of its corners (i.e. pose estimation). + @param cpara (description) + @result The handle. When no more ar3D*() functions need be called, the handle should be deleted + by calling ar3DDeleteHandle(). + @seealso ar3DCreateHandle ar3DCreateHandle + @seealso ar3DDeleteHandle ar3DDeleteHandle +*/ +AR3DHandle *ar3DCreateHandle2(ARdouble cpara[3][4]); + +/*! + @function + @abstract Delete handle used for 3D calculation. + @discussion When no more ar3D*() functions need be called, the handle should be deleted + by calling ar3DDeleteHandle(). + @param handle A pointer to the 3D handle. On success, the contents of this location will be set to NULL. + @result 0 if the handle was successfully deleted, -1 otherwise. + @seealso ar3DDeleteHandle ar3DDeleteHandle +*/ +int ar3DDeleteHandle( AR3DHandle **handle ); + +/*! + @function + @abstract (description) + @discussion (description) + @param handle (description) + @param cpara (description) + @result (description) +*/ +int ar3DChangeCpara( AR3DHandle *handle, ARdouble cpara[3][4] ); + +/*! + @function + @abstract (description) + @discussion (description) + @param handle (description) + @param maxLoopCount (description) + @result (description) +*/ +int ar3DChangeMaxLoopCount( AR3DHandle *handle, int maxLoopCount ); + +/*! + @function + @abstract (description) + @discussion (description) + @param handle (description) + @param loopBreakThresh (description) + @result (description) +*/ +int ar3DChangeLoopBreakThresh( AR3DHandle *handle, ARdouble loopBreakThresh ); + +/*! + @function + @abstract (description) + @discussion (description) + @param handle (description) + @param loopBreakThreshRatio (description) + @result (description) +*/ +int ar3DChangeLoopBreakThreshRatio( AR3DHandle *handle, ARdouble loopBreakThreshRatio ); + +/*! + @function + @abstract (description) + @discussion (description) + @param handle (description) + @param marker_info (description) + @param width (description) + @param conv (description) + @result (description) +*/ +ARdouble arGetTransMatSquare( AR3DHandle *handle, ARMarkerInfo *marker_info, + ARdouble width, ARdouble conv[3][4] ); + +/*! + @function + @abstract (description) + @discussion (description) + @param handle (description) + @param marker_info (description) + @param initConv (description) + @param width (description) + @param conv (description) + @result (description) +*/ +ARdouble arGetTransMatSquareCont( AR3DHandle *handle, ARMarkerInfo *marker_info, + ARdouble initConv[3][4], + ARdouble width, ARdouble conv[3][4] ); + +/*! + @function + @abstract (description) + @discussion (description) + @param handle (description) + @param handle (description) + @param initConv (description) + @param pos2d (description) + @param pos3d (description) + @param num (description) + @param conv (description) + @result (description) +*/ +ARdouble arGetTransMat( AR3DHandle *handle, ARdouble initConv[3][4], + ARdouble pos2d[][2], ARdouble pos3d[][3], int num, + ARdouble conv[3][4] ); + +/*! + @function + @abstract (description) + @discussion (description) + @param handle (description) + @param initConv (description) + @param pos2d (description) + @param pos3d (description) + @param num (description) + @param conv (description) + @result (description) +*/ +ARdouble arGetTransMatRobust( AR3DHandle *handle, ARdouble initConv[3][4], + ARdouble pos2d[][2], ARdouble pos3d[][3], int num, + ARdouble conv[3][4] ); + + +/***********************************/ +/* */ +/* For 3D calculation by Stereo */ +/* */ +/***********************************/ + +/*! + @functiongroup "3D calculation by Stereo". + */ + +AR3DStereoHandle *ar3DStereoCreateHandle(ARParam *arParamL, ARParam *arParamR, ARdouble transL[3][4], ARdouble transR[3][4]); +AR3DStereoHandle *ar3DStereoCreateHandle2(ARdouble cparaL[3][4], ARdouble cparaR[3][4], ARdouble transL[3][4], ARdouble transR[3][4]); +int ar3DStereoDeleteHandle( AR3DStereoHandle **handle ); +int ar3DStereoChangeMaxLoopCount( AR3DStereoHandle *handle, int maxLoopCount ); +int ar3DStereoChangeLoopBreakThresh( AR3DStereoHandle *handle, ARdouble loopBreakThresh ); +int ar3DStereoChangeLoopBreakThreshRatio( AR3DStereoHandle *handle, ARdouble loopBreakThreshRatio ); +int ar3DStereoChangeCpara( AR3DStereoHandle *handle, ARdouble cparaL[3][4], ARdouble cparaR[3][4] ); +int ar3DStereoChangeTransMat( AR3DStereoHandle *handle, ARdouble transL[3][4], ARdouble transR[3][4] ); + +ARdouble arGetTransMatSquareStereo( AR3DStereoHandle *handle, + ARMarkerInfo *marker_infoL, ARMarkerInfo *marker_infoR, + ARdouble width, ARdouble conv[3][4] ); +ARdouble arGetTransMatSquareContStereo( AR3DStereoHandle *handle, + ARMarkerInfo *marker_infoL, ARMarkerInfo *marker_infoR, + ARdouble prev_conv[3][4], + ARdouble width, ARdouble conv[3][4] ); +ARdouble arGetTransMatStereo( AR3DStereoHandle *handle, ARdouble initConv[3][4], + ARdouble pos2dL[][2], ARdouble pos3dL[][3], int numL, + ARdouble pos2dR[][2], ARdouble pos3dR[][3], int numR, + ARdouble conv[3][4] ); +ARdouble arGetTransMatStereoRobust( AR3DStereoHandle *handle, ARdouble initConv[3][4], + ARdouble pos2dL[][2], ARdouble pos3dL[][3], int numL, + ARdouble pos2dR[][2], ARdouble pos3dR[][3], int numR, + ARdouble conv[3][4] ); + +ARdouble arGetStereoMatchingErrorSquare( AR3DStereoHandle *handle, + ARMarkerInfo *marker_infoL, + ARMarkerInfo *marker_infoR ); +ARdouble arGetStereoMatchingError( AR3DStereoHandle *handle, + ARdouble pos2dL[2], ARdouble pos2dR[2] ); +int arGetStereoMatching( AR3DStereoHandle *handle, + ARdouble pos2dL[2], ARdouble pos2dR[2], ARdouble pos3d[3] ); + + + +/***********************************/ +/* */ +/* Utility */ +/* */ +/***********************************/ + +/*! + @functiongroup "Utility". + */ + +/*! + @function + @abstract Get the ARToolKit version information in numberic and string format. + @discussion + As of version 2.72, ARToolKit now allows querying of the version number + of the toolkit available at runtime. It is highly recommended that + any calling program that depends on features in a certain + ARToolKit version, check at runtime that it is linked to a version + of ARToolKit that can supply those features. It is NOT sufficient + to check the ARToolKit SDK header versions, since with ARToolKit implemented + in dynamically-loaded libraries, there is no guarantee that the + version of ARToolKit installed on the machine at run-time will be as + recent as the version of the ARToolKit SDK which the host + program was compiled against. + + The version information is reported in binary-coded decimal format, + and optionally in an ASCII string. + + A increase in the major version number indicates the removal of functionality + previously provided in the API. An increase in the minor version number + indicates that new functionality has been added. A change in the tiny version + number indicates changes (e.g. bug fixes) which do not affect the API. See + the comments in the config.h header for more discussion of the definition of + major, minor, tiny and build version numbers. + + @param versionStringRef + If non-NULL, the location pointed to will be filled + with a pointer to a string containing the version information. + Fields in the version string are separated by spaces. As of version + 2.72.0, there is only one field implemented, and this field + contains the major, minor and tiny version numbers + in dotted-decimal format. The string is guaranteed to contain + at least this field in all future versions of the toolkit. + Later versions of the toolkit may add other fields to this string + to report other types of version information. The storage for the + string is malloc'ed inside the function. The caller is responsible + for free'ing the string. + @result + Returns the full version number of the ARToolKit in + binary coded decimal (BCD) format. + BCD format allows simple tests of version number in the caller + e.g. if ((arGetVersion(NULL) >> 16) > 0x0272) printf("This release is later than 2.72\n"); + The major version number is encoded in the most-significant byte + (bits 31-24), the minor version number in the second-most-significant + byte (bits 23-16), the tiny version number in the third-most-significant + byte (bits 15-8), and the build version number in the least-significant + byte (bits 7-0). + */ +ARUint32 arGetVersion(char **versionStringRef); + +int arUtilMatInv( ARdouble s[3][4], ARdouble d[3][4] ); +int arUtilMatMul( ARdouble s1[3][4], ARdouble s2[3][4], ARdouble d[3][4] ); + +#ifdef ARDOUBLE_IS_FLOAT +#define arUtilMatInvf arUtilMatInv +#define arUtilMatMulf arUtilMatMul +#define arUtilMatMuldff arUtilMatMul +#else +int arUtilMatInvf( float s[3][4], float d[3][4] ); +int arUtilMatMulf( float s1[3][4], float s2[3][4], float d[3][4] ); +int arUtilMatMuldff( ARdouble s1[3][4], float s2[3][4], float d[3][4] ); +#endif +int arUtilMat2QuatPos( ARdouble m[3][4], ARdouble q[4], ARdouble p[3] ); +int arUtilQuatPos2Mat( ARdouble q[4], ARdouble p[3], ARdouble m[3][4] ); +int arUtilQuatNorm(ARdouble q[4]); + +double arUtilTimer(void); +void arUtilTimerReset(void); + +#ifndef _WINRT +/*! + @function + @abstract Relinquish CPU to the system for specified number of milliseconds. + @discussion + This function calls the native system-provided sleep routine to relinquish + CPU control to the system for the specified time. + @param msec Sleep time in milliseconds (thousandths of a second). + @availability Not available on Windows Runtime (WinRT). + */ +void arUtilSleep( int msec ); +#endif // !_WINRT + +int arUtilReplaceExt( char *filename, int n, char *ext ); +int arUtilRemoveExt ( char *filename ); +int arUtilDivideExt ( const char *filename, char *s1, char *s2 ); + +int arUtilGetSquareCenter( ARdouble vertex[4][2], ARdouble *x, ARdouble *y ); + +int arUtilSortLabel( int mask[], int m, int n, + ARdouble pos[][2], int area[], int label_num, + int l1, int x1, int y1, + int l2, int x2, int y2, + int label[] ); + +/*! + @function + @abstract Get the size in bytes of a single pixel for a given pixel format. + @discussion + Different pixel formats have different sizes in bytes, and therefore + different storage requirements per row of pixels. Use this function + to calculate the number of bytes required to store a single pixel + of the given type. + @param arPixelFormat The pixel type whose size is to be measured. + @result Number of bytes required to store 1 pixel of the given type. +*/ +int arUtilGetPixelSize( const AR_PIXEL_FORMAT arPixelFormat ); + +/*! + @function + @abstract Get a string holding a descriptive name for a given pixel format enumeration. + @discussion + On occasions it can be useful to display to the user the format of the pixels + which ARToolKit is processing. This funtion converts a pixel-format number + into a human-readable string description. + @param arPixelFormat Enumerated pixel format number for which to retrieve a name. + @result A constant c-string holding a descriptive name for the pixel format. + The string returned matches the constants used in the definition of the type + AR_PIXEL_FORMAT, e.g. "AR_PIXEL_FORMAT_RGB". +*/ +const char *arUtilGetPixelFormatName(const AR_PIXEL_FORMAT arPixelFormat); + +char *arUtilGetMachineType(void); + +/* + @function + @abstract Get the filename portion of a full pathname. + @discussion + Given a full or partial pathname passed in string path, + returns a pointer to the first char of the filename + portion of path. + */ +const char *arUtilGetFileNameFromPath(const char *path); + + +/*! + @function + @abstract Get file base name from a path. + @discussion + Given a full or partial pathname passed in string path, + returns a string with the base name portion of path, + i.e. the text between the rightmost path separator and the + the rightmost '.' character, if any. + If the filename contains no '.', returns the filename. + @param path Full or partial pathname. + @param convertToLowercase If convertToLowercase is TRUE, uppercase + ASCII characters in the basename will be converted to lowercase. + @result A string with the basename portion of path. + NB: The returned string must be freed by the caller. + */ +char *arUtilGetFileBasenameFromPath(const char *path, const int convertToLowercase); + +/*! + @function + @abstract Get file extension from a path. + @discussion + Given a full or partial pathname passed in string path, + returns a string with the extension portion of path, + i.e. the text after the rightmost '.' character, if any. + If the filename contains no '.', NULL is returned. + @param path Full or partial pathname. + @param convertToLowercase If convertToLowercase is TRUE, uppercase + ASCII characters in the extension will be converted to lowercase. + @result A string with the extension portion of path. + NB: The returned string must be freed by the caller. + */ +char *arUtilGetFileExtensionFromPath(const char *path, const int convertToLowercase); + + /* + @function + @abstract Get the directory portion of a full pathname. + @discussion + Given a full or partial pathname passed in string path, + returns a string with the directory name portion of path. + The string is placed into the buffer of size n pointed to by dir. + If the string and its terminating null byte cannot be accomodated by the + buffer, NULL is returned, otherwise dir is returned. + The string is terminated by the directory separator if addSeparator != 0. + */ +char *arUtilGetDirectoryNameFromPath(char *dir, const char *path, const size_t n, const int addSeparator); + +/*! + @function + @abstract Get a path as a file URI. + @discussion + Given a full or partial pathname passed in string path, + returns a string with the file URI for that path. + + Partial pathnames are handled by concatening with the + process's current working directory. + @param path Full or partial pathname. + + On Windows, both partial pathnames, full pathnames including + the drive letter, or UNC pathnames (beginning with "\\" are + all OK. + @result A string with the the file URI for that path, or NULL + in the case of error. + NB: The returned string must be freed by the caller (by + calling free() once its use is complete). + */ +char *arUtilGetFileURI(const char *path); + +/*! + @typedef + @abstract Options for controlling the behavior of arUtilGetResourcesDirectoryPath and arUtilChangeToResourcesDirectory. + @constant AR_UTIL_RESOURCES_DIRECTORY_BEHAVIOR_BEST Use a platform-dependent recommended-best option. + Note the this behavior is subject to change in future versions of ARToolKit. + At present, on Mac OS X and iOS, this will change to the Apple-provided resources directory inside the application bundle. + At present, on other platforms, this will change to the same directory as the executable. + @constant AR_UTIL_RESOURCES_DIRECTORY_BEHAVIOR_USE_CWD Use the current working directory. For arUtilChangeToResourcesDirectory, this will leave the current working directory unchanged. + @constant AR_UTIL_RESOURCES_DIRECTORY_BEHAVIOR_USE_SUPPLIED_PATH Change to the working directory specified. + @constant AR_UTIL_RESOURCES_DIRECTORY_BEHAVIOR_USE_EXECUTABLE_DIR Change to the same directory as the executable. + On OS X and iOS, this corresponds to the directory of the binary executable inside the app bundle, not ythe directory containing the app bundle. + @constant AR_UTIL_RESOURCES_DIRECTORY_BEHAVIOR_USE_USER_ROOT Change to the root of the implementation-dependent user-writable root. + On OS X and Linux, this is equivalent to the "~" user home. On Android, this is the root of the "external" storage (e.g. an SD card). + On Windows, this is the user home directory, typically "C:\Documents and Settings\USERNAME". + @constant AR_UTIL_RESOURCES_DIRECTORY_BEHAVIOR_USE_APP_CACHE_DIR Change to a writable cache directory, i.e. a directory which is not normally shown to the user, in which files which may be subject to deletion by the system or the user. + On Android, change to the applications's (internal) cache directory, and a valid instance of Android/Context must be passed in the instanceofAndroidContext parameter. + @constant AR_UTIL_RESOURCES_DIRECTORY_BEHAVIOR_USE_APP_DATA_DIR Change to a writable data directory, i.e. a directory which is not normally shown to the user, but in which files are retained permanently. + @seealso arUtilGetResourcesDirectoryPath arUtilGetResourcesDirectoryPath + @seealso arUtilChangeToResourcesDirectory arUtilChangeToResourcesDirectory + */ +typedef enum { + AR_UTIL_RESOURCES_DIRECTORY_BEHAVIOR_BEST = 0, + AR_UTIL_RESOURCES_DIRECTORY_BEHAVIOR_USE_CWD, + AR_UTIL_RESOURCES_DIRECTORY_BEHAVIOR_USE_SUPPLIED_PATH, + AR_UTIL_RESOURCES_DIRECTORY_BEHAVIOR_USE_EXECUTABLE_DIR, + AR_UTIL_RESOURCES_DIRECTORY_BEHAVIOR_USE_BUNDLE_RESOURCES_DIR, + AR_UTIL_RESOURCES_DIRECTORY_BEHAVIOR_USE_USER_ROOT, + AR_UTIL_RESOURCES_DIRECTORY_BEHAVIOR_USE_APP_CACHE_DIR, + AR_UTIL_RESOURCES_DIRECTORY_BEHAVIOR_USE_APP_DATA_DIR +} AR_UTIL_RESOURCES_DIRECTORY_BEHAVIOR; + +/*! + @function + @abstract Get the path to the resources directory using the specified behavior. + @discussion + ARToolKit uses relative paths to locate several types of resources, including + camera parameter files, pattern files, multimarker files and others. + This function provides the convenience of finding an appropriate value for your + application. + + On Android only, the function has an optional parameter 'instanceOfAndroidContext'. + If behavior is AR_UTIL_RESOURCES_DIRECTORY_BEHAVIOR_USE_APP_CACHE_DIR, this + parameter must be an instance of a class derived from android/content/Context. + In all other cases, pass NULL for this parameter. + @param behavior See AR_UTIL_RESOURCES_DIRECTORY_BEHAVIOR type for allowed values. + @result NULL in the case of error, or the path otherwise. Must be free()d by the caller. + */ +#ifdef ANDROID +char *arUtilGetResourcesDirectoryPath(AR_UTIL_RESOURCES_DIRECTORY_BEHAVIOR behavior, jobject instanceOfAndroidContext); +#else +char *arUtilGetResourcesDirectoryPath(AR_UTIL_RESOURCES_DIRECTORY_BEHAVIOR behavior); +#endif + +#ifndef _WINRT +/*! + @function + @abstract Change to the resources directory using the specified behavior. + @discussion + ARToolKit uses relative paths to locate several types of resources, including + camera parameter files, pattern files, multimarker files and others. + This function provides the convenience of setting the current process + working directory to the appropriate value for your application. + + On Android only, the function has an optional parameter 'instanceOfAndroidContext'. + If behavior is AR_UTIL_RESOURCES_DIRECTORY_BEHAVIOR_USE_APP_CACHE_DIR, this + parameter must be an instance of a class derived from android/content/Context. + In all other cases, pass NULL for this parameter. + @param behavior See AR_UTIL_RESOURCES_DIRECTORY_BEHAVIOR type for allowed values. + @param path When behavior is AR_UTIL_RESOURCES_DIRECTORY_BEHAVIOR_USE_SUPPLIED_PATH, + the path to change to (absolute or relative to current working directory). In all + other cases, if this parameter is non-NULL, it will be taken as a subdirectory + of the desired path and to which the working directory should be changed. + @result -1 in the case of error, or 0 otherwise. + @availability Not available on Windows Runtime (WinRT). + */ +#ifdef ANDROID +int arUtilChangeToResourcesDirectory(AR_UTIL_RESOURCES_DIRECTORY_BEHAVIOR behavior, const char *path, jobject instanceOfAndroidContext); +#else +int arUtilChangeToResourcesDirectory(AR_UTIL_RESOURCES_DIRECTORY_BEHAVIOR behavior, const char *path); +#endif +#endif // !_WINRT + + +/*! + @function + @abstract Prints a transformation matrix via ARLOG(...). + @param trans The transformation matrix to print. + */ +void arUtilPrintTransMat(const ARdouble trans[3][4]); + +/*! + @function + @abstract Prints a 4x4 row-major matrix via ARLOG(...). + @param mtx16 The matrix to print. + */ +void arUtilPrintMtx16(const ARdouble mtx16[16]); +#ifdef __cplusplus +} +#endif +#endif + + + diff --git a/libs/include/AR/arConfig.h b/libs/include/AR/arConfig.h new file mode 100755 index 0000000..29ca21e --- /dev/null +++ b/libs/include/AR/arConfig.h @@ -0,0 +1,123 @@ +/* + * arConfig.h + * ARToolKit5 + * + * This file is part of ARToolKit. + * + * ARToolKit is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ARToolKit is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ARToolKit. If not, see . + * + * As a special exception, the copyright holders of this library give you + * permission to link this library with independent modules to produce an + * executable, regardless of the license terms of these independent modules, and to + * copy and distribute the resulting executable under terms of your choice, + * provided that you also meet, for each linked independent module, the terms and + * conditions of the license of that module. An independent module is a module + * which is neither derived from nor based on this library. If you modify this + * library, you may extend this exception to your version of the library, but you + * are not obligated to do so. If you do not wish to do so, delete this exception + * statement from your version. + * + * Copyright 2015 Daqri, LLC. + * Copyright 2002-2015 ARToolworks, Inc. + * + * Author(s): Hirokazu Kato, Philip Lamb + * + */ + +#ifndef AR_AR_CONFIG_H +#define AR_AR_CONFIG_H + + +/* for arDebug */ +#define AR_DEBUG_DISABLE 0 +#define AR_DEBUG_ENABLE 1 +#define AR_DEFAULT_DEBUG_MODE AR_DEBUG_DISABLE + +/* for arLabelingMode */ +#define AR_LABELING_WHITE_REGION 0 +#define AR_LABELING_BLACK_REGION 1 +#define AR_DEFAULT_LABELING_MODE AR_LABELING_BLACK_REGION + +/* for arlabelingThresh */ +#define AR_DEFAULT_LABELING_THRESH 100 + +/* for arImageProcMode */ +#define AR_IMAGE_PROC_FRAME_IMAGE 0 +#define AR_IMAGE_PROC_FIELD_IMAGE 1 +#define AR_DEFAULT_IMAGE_PROC_MODE AR_IMAGE_PROC_FRAME_IMAGE + +/* for arPatternDetectionMode */ +#define AR_TEMPLATE_MATCHING_COLOR 0 +#define AR_TEMPLATE_MATCHING_MONO 1 +#define AR_MATRIX_CODE_DETECTION 2 +#define AR_TEMPLATE_MATCHING_COLOR_AND_MATRIX 3 +#define AR_TEMPLATE_MATCHING_MONO_AND_MATRIX 4 +#define AR_DEFAULT_PATTERN_DETECTION_MODE AR_TEMPLATE_MATCHING_COLOR + +/* for arMarkerExtractionMode */ +#define AR_USE_TRACKING_HISTORY 0 +#define AR_NOUSE_TRACKING_HISTORY 1 +#define AR_USE_TRACKING_HISTORY_V2 2 +#define AR_DEFAULT_MARKER_EXTRACTION_MODE AR_USE_TRACKING_HISTORY_V2 + +/* for arGetTransMat */ +#define AR_MAX_LOOP_COUNT 5 +#define AR_LOOP_BREAK_THRESH 0.5 + +/* for arPatt** */ +#if AR_ENABLE_MINIMIZE_MEMORY_FOOTPRINT +#define AR_PATT_NUM_MAX 25 +#else +#define AR_PATT_NUM_MAX 50 +#endif +#define AR_PATT_SIZE1 16 // Default number of rows and columns in pattern when pattern detection mode is not AR_MATRIX_CODE_DETECTION. Must be 16 in order to be compatible with ARToolKit versions 1.0 to 5.1.6. +#define AR_PATT_SIZE1_MAX 64 // Maximum number of rows and columns allowed in pattern when pattern detection mode is not AR_MATRIX_CODE_DETECTION. +#define AR_PATT_SIZE2_MAX 32 // Maximum number of rows and columns allowed in pattern when pattern detection mode is AR_MATRIX_CODE_DETECTION. +#define AR_PATT_SAMPLE_FACTOR1 4 // Maximum number of samples per pattern pixel row / column when pattern detection mode is not AR_MATRIX_CODE_DETECTION. +#define AR_PATT_SAMPLE_FACTOR2 3 // Maximum number of samples per pattern pixel row / column when detection mode is AR_MATRIX_CODE_DETECTION. +#define AR_PATT_CONTRAST_THRESH1 15.0 // Required contrast over pattern space when pattern detection mode is AR_TEMPLATE_MATCHING_MONO or AR_TEMPLATE_MATCHING_COLOR. +#define AR_PATT_CONTRAST_THRESH2 30.0 // Required contrast between black and white barcode segments when pattern detection mode is AR_MATRIX_CODE_DETECTION. +#define AR_PATT_RATIO 0.5 // Default value for percentage of marker width or height considered to be pattern space. Equal to 1.0 - 2*borderSize. Must be 0.5 in order to be compatible with ARToolKit versions 1.0 to 4.4. + + + +#define AR_AREA_MAX 1000000 // Maximum area (in pixels) of connected regions considered valid candidate for marker detection. +#define AR_AREA_MIN 70 // Minimum area (in pixels) of connected regions considered valid candidate for marker detection. +#define AR_SQUARE_FIT_THRESH 1.0 + +#define AR_LABELING_32_BIT 0 // 0 = 16 bits per label, 1 = 32 bits per label. +#if AR_LABELING_32_BIT +# define AR_LABELING_WORK_SIZE 1024*32*16 +# define AR_LABELING_LABEL_TYPE ARInt32 +#else +# define AR_LABELING_WORK_SIZE 1024*32 // This number may not exceed 65535 when using 16-bits labels. +# define AR_LABELING_LABEL_TYPE ARInt16 +#endif + +#if AR_ENABLE_MINIMIZE_MEMORY_FOOTPRINT +#define AR_SQUARE_MAX 30 // Maxiumum number of marker squares per frame. +#else +#define AR_SQUARE_MAX 60 // Maxiumum number of marker squares per frame. +#endif +#define AR_CHAIN_MAX 10000 + +#define AR_LABELING_THRESH_AUTO_INTERVAL_DEFAULT 7 // Number of frames between auto-threshold calculations. +#define AR_LABELING_THRESH_MODE_DEFAULT AR_LABELING_THRESH_MODE_MANUAL +#define AR_LABELING_THRESH_ADAPTIVE_KERNEL_SIZE_DEFAULT 9 +#define AR_LABELING_THRESH_ADAPTIVE_BIAS_DEFAULT (-7) + +#define AR_CONFIDENCE_CUTOFF_DEFAULT 0.5 +#define AR_MATRIX_CODE_TYPE_DEFAULT AR_MATRIX_CODE_3x3 + +#endif diff --git a/libs/include/AR/arFilterTransMat.h b/libs/include/AR/arFilterTransMat.h new file mode 100755 index 0000000..731d21b --- /dev/null +++ b/libs/include/AR/arFilterTransMat.h @@ -0,0 +1,171 @@ +/* + * arFilterTransMat.h + * ARToolKit5 + * + * This file is part of ARToolKit. + * + * ARToolKit is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ARToolKit is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ARToolKit. If not, see . + * + * As a special exception, the copyright holders of this library give you + * permission to link this library with independent modules to produce an + * executable, regardless of the license terms of these independent modules, and to + * copy and distribute the resulting executable under terms of your choice, + * provided that you also meet, for each linked independent module, the terms and + * conditions of the license of that module. An independent module is a module + * which is neither derived from nor based on this library. If you modify this + * library, you may extend this exception to your version of the library, but you + * are not obligated to do so. If you do not wish to do so, delete this exception + * statement from your version. + * + * Copyright 2015 Daqri, LLC. + * Copyright 2010-2015 ARToolworks, Inc. + * + * Author(s): Philip Lamb + * + */ + +/*! + @header arFilterTransMat + @abstract Provides filtering of transformation matrices (pose estimates). + @discussion + High frequency noise ("jitter") can be an undesirable property in + optical tracking systems like ARToolKit. These functions implement a + first-order low-pass filter for both the position and orientation + components of the pose estimate transformation matrices. + + Usage:
+ For each pose estimate which is to be filtered, an ARFilterTransMatInfo + structure should be allocated by calling arFilterTransMatInit(). Samples + are then added to the filter and the filtered value returned by calling + arFilterTransMat(). At the end of operations, the filter should be + disposed of by calling arFilterTransMatFinal(). +*/ + +#ifndef AR_FILTERTRANSMAT_H +#define AR_FILTERTRANSMAT_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + + +typedef struct _ARFilterTransMatInfo ARFilterTransMatInfo; + +/*! + @defined + @abstract Default sample rate (in Hertz). + @discussion This value provides a default value for the + sampleRate parameter in arFilterTransMatInit(). +*/ +#define AR_FILTER_TRANS_MAT_SAMPLE_RATE_DEFAULT 30.0 + +/*! + @defined + @abstract Default cutoff frequency (in Hertz). + @discussion This value provides a default value for the + cutoffFreq parameter in arFilterTransMatInit(). + */ +#define AR_FILTER_TRANS_MAT_CUTOFF_FREQ_DEFAULT 15.0 + +/*! + @function + @abstract Initialise a filter for a single transformation matrix (pose estimate). + @discussion + In order to filter a pose estimate, this function should be called to setup + filter data structures. + + Each ARFilterTransMatInfo structure should be used only with a single transformation + matrix. For example, if you have 5 pose estimates to filter, you would call this + function 5 times, once for each pose, and keep the pose data and filter data paired. + + The structure produced should be passed to other filter functions dealing with + the same transformation matrix. + @param sampleRate This value partially determines the filter properties. + It should be as close as possible to the rate at which pose estimates arrive, + which is usually the camera frame rate. If you are unsure what value to use, + use the constant AR_FILTER_TRANS_MAT_SAMPLE_RATE_DEFAULT. This value may not be 0.0. + @param cutoffFreq This value partially determines the filter properties. + It should be as close as possible to the rate above which you do not wish + changes to the incoming transformation matrix pose estimate to be observed. + This would usually be the maximum rate at which you imagine to-and-fro rotiational + or positional motion of a marker to occur. If you are unsure what value to use, + use the constant AR_FILTER_TRANS_MAT_CUTOFF_FREQ_DEFAULT. This value may not be 0.0. + @result Pointer to an ARFilterTransMatInfo structure, which should be passed + to other filter functions dealing with the same transformation matrix, or NULL + in case of error. +*/ +ARFilterTransMatInfo *arFilterTransMatInit(const ARdouble sampleRate, const ARdouble cutoffFreq); + +/*! + @function + @abstract Set the filter parameters. + @discussion + This convenience function allows adjustment of the initial filter parameters. + @param ftmi Filter settings of which the parameters should be set. + @param sampleRate This value partially determines the filter properties. + It should be as close as possible to the rate at which pose estimates arrive, + which is usually the camera frame rate. If you are unsure what value to use, + use the constant AR_FILTER_TRANS_MAT_SAMPLE_RATE_DEFAULT. This value may not be 0.0. + @param cutoffFreq This value partially determines the filter properties. + It should be as close as possible to the rate above which you do not wish + changes to the incoming transformation matrix pose estimate to be observed. + This would usually be the maximum rate at which you imagine to-and-fro rotiational + or positional motion of a marker to occur. If you are unsure what value to use, + use the constant AR_FILTER_TRANS_MAT_CUTOFF_FREQ_DEFAULT. This value may not be 0.0. + @result + 0 The filter parameters were set without error.
+ -1 Invalid parameter.
+ -2 One of the parameters was 0.0. +*/ +int arFilterTransMatSetParams(ARFilterTransMatInfo *ftmi, const ARdouble sampleRate, const ARdouble cutoffFreq); + +/*! + @function + @abstract Filters the supplied pose estimate transformation matrix in-place. + @discussion + This performs the filter function for a single transformation matrix. + @param ftmi Filter settings to be used with this transformation matrix. + @param m Transformation matrix representing the current pose estimate. + @param reset + If a discontinuity in transformation matrix pose estimates has occured + (e.g. when a marker is first acquired, or is reacquired after a period of not being + visible) the filter initial state or "memory" should be set to the + same value as the current sample by setting this parameter to 1. If + transformation matrix pose estimates have occured continuously, set this + parameter to 0. + @result + 0 No error.
+ -1 Invalid parameter.
+ -2 Invalid transformation matrix. +*/ +int arFilterTransMat(ARFilterTransMatInfo *ftmi, ARdouble m[3][4], const int reset); + +/*! + @function + @abstract Finalise a filter. + @discussion + When all filter use has completed, this function should be called to dispose + of the filter structure. + @param ftmi Filter settings to dispose of. +*/ +void arFilterTransMatFinal(ARFilterTransMatInfo *ftmi); + + +#ifdef __cplusplus +} +#endif + +#endif // !AR_FILTERTRANSMAT_H \ No newline at end of file diff --git a/libs/include/AR/arImageProc.h b/libs/include/AR/arImageProc.h new file mode 100755 index 0000000..b2223ad --- /dev/null +++ b/libs/include/AR/arImageProc.h @@ -0,0 +1,109 @@ +/* + * arImageProc.h + * ARToolKit5 + * + * This file is part of ARToolKit. + * + * ARToolKit is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ARToolKit is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ARToolKit. If not, see . + * + * As a special exception, the copyright holders of this library give you + * permission to link this library with independent modules to produce an + * executable, regardless of the license terms of these independent modules, and to + * copy and distribute the resulting executable under terms of your choice, + * provided that you also meet, for each linked independent module, the terms and + * conditions of the license of that module. An independent module is a module + * which is neither derived from nor based on this library. If you modify this + * library, you may extend this exception to your version of the library, but you + * are not obligated to do so. If you do not wish to do so, delete this exception + * statement from your version. + * + * Copyright 2015 Daqri, LLC. + * Copyright 2010-2015 ARToolworks, Inc. + * + * Author(s): Philip Lamb + * + */ + +#ifndef AR_IMAGEPROC_H +#define AR_IMAGEPROC_H + +#ifndef TRUE +# define TRUE 1 +#endif +#ifndef FALSE +# define FALSE 0 +#endif + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef __APPLE__ +# if !AR_DISABLE_THRESH_MODE_AUTO_ADAPTIVE +# define AR_IMAGEPROC_USE_VIMAGE 1 +# endif +#endif + +struct _ARImageProcInfo { + unsigned char *__restrict image; // Buffer holds result of conversion to luminance image (8 bit grayscale). + unsigned char *__restrict image2; // Extra buffer, allocated as required. + int imageX; // Width of image buffer. + int imageY; // Height of image buffer. + unsigned long histBins[256]; // Luminance histogram. + unsigned long cdfBins[256]; // Luminance cumulative density function. + unsigned char min; // Minimum luminance. + unsigned char max; // Maximum luminance. +#if AR_IMAGEPROC_USE_VIMAGE + void *tempBuffer; +#endif + AR_PIXEL_FORMAT pixFormat; // Expected pixel format of incoming images. + int alwaysCopy; + int imageWasAllocated; +#ifdef HAVE_ARM_NEON + int fastPath; +#endif +}; +typedef struct _ARImageProcInfo ARImageProcInfo; + +#ifdef __cplusplus +} +#endif + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +ARImageProcInfo *arImageProcInit(const int xsize, const int ysize, const AR_PIXEL_FORMAT pixFormat, int alwaysCopy); +void arImageProcFinal(ARImageProcInfo *ipi); +int arImageProcLuma(ARImageProcInfo *ipi, const ARUint8 *__restrict dataPtr); +int arImageProcLumaHist(ARImageProcInfo *ipi, const ARUint8 *__restrict dataPtr); +unsigned char *arImageProcGetHistImage(ARImageProcInfo *ipi); +int arImageProcLumaHistAndCDF(ARImageProcInfo *ipi, const ARUint8 *__restrict dataPtr); +int arImageProcLumaHistAndCDFAndPercentile(ARImageProcInfo *ipi, const ARUint8 *__restrict dataPtr, const float percentile, unsigned char *value_p); +int arImageProcLumaHistAndCDFAndMedian(ARImageProcInfo *ipi, const ARUint8 *__restrict dataPtr, unsigned char *value_p); +int arImageProcLumaHistAndOtsu(ARImageProcInfo *ipi, const ARUint8 *__restrict dataPtr, unsigned char *value_p); +#if !AR_DISABLE_THRESH_MODE_AUTO_ADAPTIVE +int arImageProcLumaHistAndBoxFilterWithBias(ARImageProcInfo *ipi, const ARUint8 *__restrict dataPtr, const int boxSize, const int bias); +#endif +int arImageProcLumaHistAndCDFAndLevels(ARImageProcInfo *ipi, const ARUint8 *__restrict dataPtr); + +#ifdef __cplusplus +} +#endif + +#endif // !AR_IMAGEPROC_H \ No newline at end of file diff --git a/libs/include/AR/arMulti.h b/libs/include/AR/arMulti.h new file mode 100755 index 0000000..9d2d232 --- /dev/null +++ b/libs/include/AR/arMulti.h @@ -0,0 +1,117 @@ +/* + * arMulti.h + * ARToolKit5 + * + * This file is part of ARToolKit. + * + * ARToolKit is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ARToolKit is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ARToolKit. If not, see . + * + * As a special exception, the copyright holders of this library give you + * permission to link this library with independent modules to produce an + * executable, regardless of the license terms of these independent modules, and to + * copy and distribute the resulting executable under terms of your choice, + * provided that you also meet, for each linked independent module, the terms and + * conditions of the license of that module. An independent module is a module + * which is neither derived from nor based on this library. If you modify this + * library, you may extend this exception to your version of the library, but you + * are not obligated to do so. If you do not wish to do so, delete this exception + * statement from your version. + * + * Copyright 2015 Daqri, LLC. + * Copyright 2002-2015 ARToolworks, Inc. + * + * Author(s): Hirokazu Kato, Philip Lamb + * + */ +/******************************************************* + * + * Author: Hirokazu Kato + * + * kato@sys.im.hiroshima-cu.ac.jp + * + * Revision: 1.0 + * Date: 01/09/05 + * + *******************************************************/ + +#ifndef AR_MULTI_H +#define AR_MULTI_H + +#include + + +#ifdef __cplusplus +extern "C" { +#endif + +#define AR_MULTI_PATTERN_TYPE_TEMPLATE 0 +#define AR_MULTI_PATTERN_TYPE_MATRIX 1 + +#define AR_MULTI_PATTERN_DETECTION_MODE_TEMPLATE 0 +#define AR_MULTI_PATTERN_DETECTION_MODE_MATRIX 1 +#define AR_MULTI_PATTERN_DETECTION_MODE_TEMPLATE_AND_MATRIX 2 + +#define AR_MULTI_CONFIDENCE_PATTERN_CUTOFF_DEFAULT 0.5 +#define AR_MULTI_CONFIDENCE_MATRIX_CUTOFF_DEFAULT 0.5 +#define AR_MULTI_POSE_ERROR_CUTOFF_EACH_DEFAULT 4.0 // Maximum allowable pose estimation error for each marker. +#define AR_MULTI_POSE_ERROR_CUTOFF_COMBINED_DEFAULT 20.0 // Maximum allowable pose estimation error for combined marker set. + + +typedef struct { + int patt_id; + int patt_type; // Either AR_MULTI_PATTERN_TYPE_TEMPLATE or AR_MULTI_PATTERN_TYPE_MATRIX. + ARdouble width; + ARdouble trans[3][4]; + ARdouble itrans[3][4]; + ARdouble pos3d[4][3]; + int visible; + int visibleR; + uint64_t globalID; +} ARMultiEachMarkerInfoT; + +typedef struct { + ARMultiEachMarkerInfoT *marker; + int marker_num; + ARdouble trans[3][4]; + int prevF; + int patt_type; + ARdouble cfPattCutoff; + ARdouble cfMatrixCutoff; +} ARMultiMarkerInfoT; + +ARMultiMarkerInfoT *arMultiReadConfigFile( const char *filename, ARPattHandle *pattHandle ); + +int arMultiFreeConfig( ARMultiMarkerInfoT *config ); + +ARdouble arGetTransMatMultiSquare(AR3DHandle *handle, ARMarkerInfo *marker_info, int marker_num, + ARMultiMarkerInfoT *config); + +ARdouble arGetTransMatMultiSquareRobust(AR3DHandle *handle, ARMarkerInfo *marker_info, int marker_num, + ARMultiMarkerInfoT *config); + +ARdouble arGetTransMatMultiSquareStereo(AR3DStereoHandle *handle, + ARMarkerInfo *marker_infoL, int marker_numL, + ARMarkerInfo *marker_infoR, int marker_numR, + ARMultiMarkerInfoT *config); + +ARdouble arGetTransMatMultiSquareStereoRobust(AR3DStereoHandle *handle, + ARMarkerInfo *marker_infoL, int marker_numL, + ARMarkerInfo *marker_infoR, int marker_numR, + ARMultiMarkerInfoT *config); + + +#ifdef __cplusplus +} +#endif +#endif diff --git a/libs/include/AR/arosg.h b/libs/include/AR/arosg.h new file mode 100755 index 0000000..7b28230 --- /dev/null +++ b/libs/include/AR/arosg.h @@ -0,0 +1,563 @@ +/* + * arosg.h + * ARToolKit5 + * + * This file is part of ARToolKit. + * + * ARToolKit is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ARToolKit is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ARToolKit. If not, see . + * + * As a special exception, the copyright holders of this library give you + * permission to link this library with independent modules to produce an + * executable, regardless of the license terms of these independent modules, and to + * copy and distribute the resulting executable under terms of your choice, + * provided that you also meet, for each linked independent module, the terms and + * conditions of the license of that module. An independent module is a module + * which is neither derived from nor based on this library. If you modify this + * library, you may extend this exception to your version of the library, but you + * are not obligated to do so. If you do not wish to do so, delete this exception + * statement from your version. + * + * Copyright 2015 Daqri, LLC. + * Copyright 2009-2015 ARToolworks, Inc. + * + * Author(s): Philip Lamb + * + */ + +/*! + @header arosg + @abstract C-interface to OpenSceneGraph for augmented reality applications. + @discussion + arosg is intended to provide access to the modern plugin-based scene graph + OpenSceneGraph, and its attendant model formats and graphical capabilities. + + arosg provides a C-based interface to a limited subset of the + functionality of OpenSceneGraph. As of version 1.0 of arosg, the + supported functionality is primarily 3D model loading and drawing. + @availability Available ARToolKit v4.4.2 and later. +*/ + +#ifndef AR_OSG_H +#define AR_OSG_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef _WIN32 +# ifdef LIBAROSG_EXPORTS +# define AR_DLL_API __declspec(dllexport) +# else +# ifdef _DLL +# define AR_DLL_API __declspec(dllimport) +# else +# define AR_DLL_API extern +# endif +# endif +#else +# define AR_DLL_API +#endif + + +#if AR_ENABLE_MINIMIZE_MEMORY_FOOTPRINT +#define AR_OSG_MODELS_MAX 64 +#else +#define AR_OSG_MODELS_MAX 1024 +#endif + +typedef struct _AROSG AROSG; // (Forward definition of opaque structure). + +/*! + @function + @abstract Get the version of ARToolKit with which the arOSG library was built. + @discussion + It is highly recommended that + any calling program that depends on features in a certain + ARToolKit version, check at runtime that it is linked to a version + of ARToolKit that can supply those features. It is NOT sufficient + to check the ARToolKit SDK header versions, since with ARToolKit implemented + in dynamically-loaded libraries, there is no guarantee that the + version of ARToolKit installed on the machine at run-time will be as + recent as the version of the ARToolKit SDK which the host + program was compiled against. + @result + Returns the full version number of the ARToolKit version corresponding + to this OSG library, in binary coded decimal (BCD) format. + + BCD format allows simple tests of version number in the caller + e.g. if ((arGetVersion() >> 16) > 0x0272) printf("This release is later than 2.72\n"); + + The major version number is encoded in the most-significant byte + (bits 31-24), the minor version number in the second-most-significant + byte (bits 23-16), the tiny version number in the third-most-significant + byte (bits 15-8), and the build version number in the least-significant + byte (bits 7-0). + @availability Available in ARToolKit v4.4.2 and later. + */ +AR_DLL_API unsigned int arOSGGetVersion(); + +/*! + @function + @abstract Create a settings structure for use with all other arOSG functions. + @discussion + All other arOSG functions require a reference to settings and global data. + Use this function to create and initialise such a structure. + @result Pointer to the new AROSG settings structure. +*/ +AR_DLL_API AROSG *arOSGInit(); + +/*! + @function + @abstract Load an OSG model using a "model description file". + @discussion - + The format of this file is a simple text file. Comments may be + included by prefixing the line with a "#" character. + The object definition consists of the following: +
    +
  • A line with the path to the object's data file, relative to the + objects file. (This path may include spaces.) +
  • A line with the position of the object's origin, relative to the + parent coordinate system's origin, expressed as 3 floating point + numbers separated by spaces, representing the offset in x, y, and z. + This is the same format used by the glTranslate() function. +
  • A line with the orientation of the object's coordinate system, + relative to the parent coordinate system, expressed as 4 floating + point numbers separated by spaces, representing an angle and an + axis of a rotation from the parent. This is the same format used + by the glRotate() function. +
  • A line with the scale factor to apply to the object, expressed + as 3 floating point numbers separated by spaces, representing the + scale factor to apply in x, y, and z. + This is the same format used by the glScale() function. +
  • Zero or more lines with optional tokens representing additional + information about the object. The following tokens are defined: +
      +
    • LIGHTING f: Enables or disables lighting calculations for this + object. Note that disabling lighting will result in the + object being drawn fully lit but without shading. + f = 0 to disable, f = 1 to enable. Default is enabled. +
    • TRANSPARENT: Provides a hint that this object includes transparent + portions, and should be drawn alpha-blended. Default is + that no transparency hint is provided. +
    +
+ @param arOsg Pointer to the AROSG settings structure into which the model should be loaded. (See arOSGInit().) + @param modelDescriptionFilePath + A string holding the path to a "model description file". This file must contain a structured list of + the following data: the relative path to the actual OSG model to be loaded, the translation (in x,y,z axes) + to be applied to the model, the rotation (in angle/axis form, as degrees, angle of rotation x,y,z), and + the scale factor to be applied to the model (in the x,y,z axes). See the sample files included + in the ARToolKit distribution in the directory bin/OSG for examples. + @result An index value with which the loaded model can be referred to, in the range [0, AR_OSG_MODELS_MAX - 1], + or, in case of error, a value less than 0. +*/ +AR_DLL_API int arOSGLoadModel(AROSG *arOsg, const char *modelDescriptionFilePath); + +/*! + @function + @abstract Load an OSG model. + @discussion - + @param arOsg Pointer to the AROSG settings structure into which the model should be loaded. (See arOSGInit().) + @param modelFilePath A string holding the path to a file readable by OSG (as a node, e.g. an .ive or .osg file). + @param translation The translation (in x,y,z axes) to be applied to the model, or NULL to apply no translation. + @param rotation The rotation (in angle/axis form, as degrees, angle of rotation x,y,z) to be applied to the model, or NULL to apply no rotation. + @param scale The scale factor to be applied to the model (in the x,y,z axes) or NULL to retain the scale at 1.0. + @result An index value with which the loaded model can be referred to, in the range [0, AR_OSG_MODELS_MAX - 1], + or, in case of error, a value less than 0. + @availability Available in ARToolKit v4.5.1 and later. + */ +AR_DLL_API int arOSGLoadModel2(AROSG *arOsg, const char *modelFilePath, const ARdouble translation[3], const ARdouble rotation[4], const ARdouble scale[3]); + +/*! + @function + @abstract Unload an OSG model. + @discussion + Frees the memory associated with an OSG model. + @param arOsg Pointer to the AROSG settings structure from which the model should be unloaded. (See arOSGInit().) + @result 0, or in case of error, a value less than 0. +*/ +AR_DLL_API int arOSGUnloadModel(AROSG *arOsg, const int index); + +/*! + @function + @abstract Show or hide an OSG-based model. + @discussion + Models are visible by default. + @param arOsg Pointer to the AROSG settings structure. (See arOSGInit().) + @param index The index of the model to adjust the visibility of. See arOSGLoadModel(). + @param visible 0 to hide, or non-zero to show. + @result 0, or in case of error, a value less than 0. +*/ +AR_DLL_API int arOSGSetModelVisibility(AROSG *arOsg, const int index, const int visible); + +/*! + @function + @abstract Find out if an OSG-based model is shown or hidden. + @discussion + Models are visible by default. + @param arOsg Pointer to the AROSG settings structure. (See arOSGInit().) + @param index The index of the model to request the visibility of. See arOSGLoadModel(). + @param visible Pointer to a location, which on return will contain 0 if hidden, or 1 if shown. + @result 0, or in case of error, a value less than 0. + @availability Available in ARToolKit v4.5.1 and later. +*/ +AR_DLL_API int arOSGGetModelVisibility(AROSG *arOsg, const int index, int *visible); + +/*! + @function + @abstract Set lighting for a model on or off. + @discussion + By default, lighting is enabled for models. + @param arOsg Pointer to the AROSG settings structure. (See arOSGInit().) + @param index The index of the model to adjust the lighting of. See arOSGLoadModel(). + @param lit 0 to disable lighting, or non-zero to enable. + @result 0, or in case of error, a value less than 0. + @availability Available in ARToolKit v4.5.1 and later. +*/ +AR_DLL_API int arOSGSetModelLighting(AROSG *arOsg, const int index, const int lit); + +/*! + @function + @abstract Find out if lighting for model is on or off. + @discussion + By default, lighting is enabled for models. + @param arOsg Pointer to the AROSG settings structure. (See arOSGInit().) + @param index The index of the model to request the lighting state of. See arOSGLoadModel(). + @param lit Pointer to a location, which on return will contain 0 if lighting disable, or 1 if enabled. + @result 0, or in case of error, a value less than 0. + @availability Available in ARToolKit v4.5.1 and later. +*/ +AR_DLL_API int arOSGGetModelLighting(AROSG *arOsg, const int index, int *lit); + +/*! + @function + @abstract Set transparency for a model on or off. + @discussion + By default, transparency for models depends on the state with which the model was created. + However, this setting allows overriding of the transparency settings. One example usage + would be to force an image texture containing an alpha channel to draw with transparency, + or alternately without. + @param arOsg Pointer to the AROSG settings structure. (See arOSGInit().) + @param index The index of the model to adjust the transparency of. See arOSGLoadModel(). + @param transparent 0 to disable transparency, or non-zero to enable. + @result 0, or in case of error, a value less than 0. + @availability Available in ARToolKit v4.6. and later. +*/ +AR_DLL_API int arOSGSetModelTransparency(AROSG *arOsg, const int index, const int transparent); + +/*! + @function + @abstract For a model with animation, pause or resume the animation. + @discussion + Models with animations may have the animation paused and later resumed. + @param arOsg Pointer to the AROSG settings structure. (See arOSGInit().) + @param index The index of the model of which the animation should be paused or resumed. See arOSGLoadModel(). + @param pause 0 to resume the animation, 1 to pause it. + @result 0, or in case of error, a value less than 0. + @availability Available in ARToolKit v4.6.7 and later. +*/ +AR_DLL_API int arOSGSetModelAnimationPause(AROSG *arOsg, const int index, const int pause); + +/*! + @function + @abstract For a model with animation, discover the animation time. + @discussion + You may query the animation time of models with animations. + @param arOsg Pointer to the AROSG settings structure. (See arOSGInit().) + @param index The index of the model of which the animation time should be queried. See arOSGLoadModel(). + @result 0, or in case of error, a value less than 0. + @param animationTime A pointer to a double, which will be filled with the animation time (should one be available), or 0 if no animation time is defined. + @availability Available in ARToolKit v4.6.7 and later. +*/ +AR_DLL_API int arOSGGetModelAnimationTime(AROSG *arOsg, const int index, double *animationTime); + +/*! + @function + @abstract For a model with animation, reset the animation. + @discussion + Models with animations may have the animation reset to the initial state. + @param arOsg Pointer to the AROSG settings structure. (See arOSGInit().) + @param index The index of the model of which the animation should be reset. See arOSGLoadModel(). + @result 0, or in case of error, a value less than 0. + @availability Available in ARToolKit v4.6.7 and later. +*/ +AR_DLL_API int arOSGSetModelAnimationReset(AROSG *arOsg, const int index); + +/*! + @function + @abstract For a model with animation, override the animation loop mode. + @discussion + Models with animations have a default mode set at time of creation. To + override the mode at runtime, use this function. + @param arOsg Pointer to the AROSG settings structure. (See arOSGInit().) + @param index The index of the model of which the animation loop mode should be overridden. See arOSGLoadModel(). + @param mode 0 to disable looping, 1 to enable looping (where at the end of the animation sequence, animation continues from the beginning again), or 2 to enable + swinging animation (where at the end of animation, animation proceeds in reverse + until the beginning is reached, at which point animation proceeds forward again, + ad infinitum. + @result 0, or in case of error, a value less than 0. + @availability Available in ARToolKit v4.6.7 and later. +*/ +AR_DLL_API int arOSGSetModelAnimationLoopModeOverride(AROSG *arOsg, const int index, const int mode); + +/*! + @function + @abstract Set the projection matrix used in OSG drawing. + @discussion - + @param arOsg Pointer to the AROSG settings structure. (See arOSGInit().) + @param p A 4x4 OpenGL transform matrix (column-major order) representing the projection transform. + @result 0, or in case of error, a value less than 0. +*/ +AR_DLL_API int arOSGSetProjection(AROSG *arOsg, ARdouble p[16]); + +/*! + @function + @abstract Get the projection matrix used in OSG drawing. + @discussion - + @param arOsg Pointer to the AROSG settings structure. (See arOSGInit().) + @param p A 4x4 OpenGL transform matrix (column-major order) representing the projection transform. + @result 0, or in case of error, a value less than 0. + @availability Available in ARToolKit v4.5.1 and later. + */ +AR_DLL_API int arOSGGetProjection(AROSG *arOsg, ARdouble *p); + +/*! + @function + @abstract Set the polygon winding for front-facing polygons. + @discussion - + @param arOsg Pointer to the AROSG settings structure. (See arOSGInit().) + @param winding 0 to set counter-clockwise (the default), or 1 to set clockwise. + @result 0, or in case of error, a value less than 0. + @availability Available in ARToolKit v5.0 and later. + */ +AR_DLL_API int arOSGSetFrontFace(AROSG *arOsg, int winding); + +/*! + @function + @abstract Get the polygon winding for front-facing polygons. + @discussion - + @param arOsg Pointer to the AROSG settings structure. (See arOSGInit().) + @param winding Pointer to a location, which on return will be 0 if counter-clockwise (the default), or 1 if clockwise. + @result 0, or in case of error, a value less than 0. + @availability Available in ARToolKit v5.0 and later. + */ +AR_DLL_API int arOSGGetFrontFace(AROSG *arOsg, int *winding); + +/*! + @function + @abstract Set the pose (position and orientation) of an OSG-based model. + @discussion - + @param arOsg Pointer to the AROSG settings structure. (See arOSGInit().) + @param index The index of the model to adjust the pose of. See arOSGLoadModel(). + @param modelview A 4x4 OpenGL transform matrix (column-major order) representing the modelview transform of the model. + @result 0, or in case of error, a value less than 0. +*/ +AR_DLL_API int arOSGSetModelPose(AROSG *arOsg, const int index, const ARdouble modelview[16]); + +/*! + @function + @abstract Get the pose (position and orientation) of an OSG-based model. + @discussion - + @param arOsg Pointer to the AROSG settings structure. (See arOSGInit().) + @param index The index of the model to retrieve the pose of. See arOSGLoadModel(). + @param modelview A 4x4 OpenGL transform matrix (column-major order) representing the modelview transform of the model. + @result 0, or in case of error, a value less than 0. + @availability Available in ARToolKit v4.5.1 and later. + */ +AR_DLL_API int arOSGGetModelPose(AROSG *arOsg, const int index, ARdouble *modelview); + +/*! + @function + @abstract Set the local pose (position and orientation) of an OSG-based model. + @discussion - + @param arOsg Pointer to the AROSG settings structure. (See arOSGInit().) + @param index The index of the model to adjust the pose of. See arOSGLoadModel(). + @param model A 4x4 OpenGL transform matrix (column-major order) representing the local transform of the model. + @result 0, or in case of error, a value less than 0. + @availability Available in ARToolKit v4.5.5 and later. +*/ +AR_DLL_API int arOSGSetModelLocalPose(AROSG *arOsg, const int index, const ARdouble model[16]); + +/*! + @function + @abstract Get the local pose (position and orientation) of an OSG-based model. + @discussion - + @param arOsg Pointer to the AROSG settings structure. (See arOSGInit().) + @param index The index of the model to retrieve the pose of. See arOSGLoadModel(). + @param model A 4x4 OpenGL transform matrix (column-major order) representing the local transform of the model. + @result 0, or in case of error, a value less than 0. + @availability Available in ARToolKit v4.5.5 and later. + */ +AR_DLL_API int arOSGGetModelLocalPose(AROSG *arOsg, const int index, ARdouble *model); + +/*! + @function + @abstract Turn on or off 2D outlining of a model's boundary. + @discussion + Outlining allows a model to be highlighted by drawing a 2D outline of the models extreme boundary. + Outlining is not currently supported by OSG on platforms using OpenGL ES, and calling this function + will produce erroneous visual results if used on an OpenGL ES platform. + @param arOsg Pointer to the AROSG settings structure. (See arOSGInit().) + @param index The index of the model to retrieve the pose of. See arOSGLoadModel(). + @param width The width, in pixels, of the outline to place around the model. To disable outlining, pass 0. + Outlining is initially disabled. + @param rgba The colour of the outline, as an array of unsigned bytes in order red, green, blue, alpha. + An opaque outline can be generated by passing 255 for the alpha value. Values less than 255 will result in a transparent outline. + @result 0, or in case of error, a value less than 0. + @availability Available in ARToolKit v4.6.3 and later. + */ +AR_DLL_API int arOSGSetModelOutline(AROSG *arOsg, const int index, const int width, const unsigned char rgba[4]); + +/*! + @function + @abstract Determine if a model is intersected by a line segment. + @discussion + This calculates the intersection between a line segment (defined by two points in world coordinates) + and a model (actually an OSG node and subnodes). If an intersection is found, different data types + can be returned by providing pointers in parameters nodeType, nodeName, and intersectionCoords. + @param arOsg Pointer to the AROSG settings structure. (See arOSGInit().) + @param index The index of the model to calculate the intersection of. See arOSGLoadModel(). + @param p1 Required; a vector specifying the location of one end of the line segment, in world coordinates. + @param p2 Required; a vector specifying the location of the other end of the line segment, in world coordinates. + @result 1 if an intersection was found, 0 if no intersection was found, or in case of error, a value less than 0. + @availability Available in ARToolKit v4.5.1 and later. +*/ +AR_DLL_API int arOSGGetModelIntersection(AROSG *arOsg, const int index, const ARdouble p1[3], const ARdouble p2[3]); + +/*! + @constant + @abstract Variable to supply to arOSGSetDrawTime to direct OpenSceneGraph to use its internal reference time. + @discussion + OSG maintains its own internal reference time for animation and simulation + rendering. If you wish to render using OSG's reference time, supply this + value to arOSGSetDrawTime. + @seealso arOSGSetDrawTime arOSGSetDrawTime +*/ +extern const double AR_OSG_TIME_USE_REFERENCE_TIME; + +/*! + @function + @abstract Process scenegraph-related events, including drawing all visible models. + @discussion + OSG maintains its own internal reference time for animation and simulation + rendering. If you wish to render at particular time instants or at non-unit + timescales, you can manipulate the timeline for following arOSGDraw calls by + calling this function with the time (in decimal seconds) supplied in the + parameter. To revert to OSG's internal reference time, pass the value + AR_OSG_TIME_USE_REFERENCE_TIME. + @param arOsg Pointer to the AROSG settings structure. (See arOSGInit().) + @param time Decimal seconds value at which to render the next arOSGDraw call. + @result 0, or in case of error, a value less than 0. + @seealso AR_OSG_TIME_USE_REFERENCE_TIME AR_OSG_TIME_USE_REFERENCE_TIME + @seealso arOSGDraw arOSGDraw +*/ +AR_DLL_API int arOSGSetDrawTime(AROSG *arOsg, double time); + +/*! + @function + @abstract Process scenegraph-related events, including drawing all visible models. + @discussion + This function leaves the values of the OpenGL machine in an indeterminate state, including + clobbering the OpenGL viewport, projection and modelview matrices. The user + should save any sensitive state prior to calling this function, and restore that state upon return. + @param arOsg Pointer to the AROSG settings structure. (See arOSGInit().) + @result 0, or in case of error, a value less than 0. +*/ +AR_DLL_API int arOSGDraw(AROSG *arOsg); + +/*! + @function + @abstract Inform OpenSceneGraph that a window reshape has occured (i.e. changes to window size have occured). + @discussion + This function should be called when the window is first created, and then + whenever the operating system generates a notification + that the user has changed the window size. + @param arOsg Pointer to the AROSG settings structure. (See arOSGInit().) + @param w The new window width, in pixels. + @param h The new window height, in pixels. + */ +AR_DLL_API void arOSGHandleReshape(AROSG *arOsg, const int w, const int h); + +/*! + @function + @abstract Inform OpenSceneGraph that a window reshape has occured (i.e. changes to window size have occured). + @discussion + This function should be called when the window is first created, and then + whenever the operating system generates a notification + that the user has changed the window size. + @param arOsg Pointer to the AROSG settings structure. (See arOSGInit().) + @param left The new viewport origin left coordinate, in pixels. + @param bottom The new viewport origin bottom coordinate, in pixels. + @param width The new viewport width, in pixels. + @param height The new viewport height, in pixels. + */ +AR_DLL_API void arOSGHandleReshape2(AROSG *arOsg, const int left, const int bottom, const int width, const int height); + +/*! + @function + @abstract Pass mouse clicks to OpenSceneGraph. + @discussion - + @param arOsg Pointer to the AROSG settings structure. (See arOSGInit().) + @param button The values 0, 1 or 2 for the left, middle and right mouse buttons, respectively. + (For the convenience of users using GLUT, these values match the values of GLUT_LEFT_BUTTON, + GLUT_MIDDLE_BUTTON and GLUT_RIGHT_BUTTON.) + @param state 0 for a mouse-button-down event, and 1 for a mouse-button-up (button released) event. + @param x The mouse x location in window relative coordinates when the mouse button was pressed. + @param y The mouse y location in window relative coordinates. +*/ +AR_DLL_API void arOSGHandleMouseDownUp(AROSG *arOsg, const int button, const int state, const int x, const int y); + +/*! + @function + @abstract Pass mouse motion events to OpenSceneGraph + @discussion - + @param arOsg Pointer to the AROSG settings structure. (See arOSGInit().) + @param x The mouse x location in window relative coordinates. + @param y The mouse y location in window relative coordinates. +*/ +AR_DLL_API void arOSGHandleMouseMove(AROSG *arOsg, int x, int y); + +/*! + @function + @abstract Pass key press events to OpenSceneGraph. + @discussion - + @param arOsg Pointer to the AROSG settings structure. (See arOSGInit().) + @param key Key code. The handling of this is OSG-depdendent, but ASCII key codes (0x00 to 0x7f) at least + can be passed in directly. For the appropriate key code to use for + other keys, see the values defined in OpenSceneGraph. The values are listed in the OSG header file + <osgGA/GUIEventAdapter> under the enum "KeyCode". + @param x The mouse x location in window relative coordinates when the key was pressed -- presently ignored. + @param y The mouse y location in window relative coordinates when the key was pressed -- presently ignored. +*/ +AR_DLL_API void arOSGHandleKeyboard(AROSG *arOsg, int key, int x, int y); + +/*! + @function + @abstract Dispose of an AROSG settings structure. + @discussion + If you have finished with an AROSG settings structure in your running program, + you can unload its internal data by calling arOSGFinal. + @param arOsg Pointer to the AROSG settings structure to be disposed of. (See arOSGInit().) +*/ +AR_DLL_API void arOSGFinal(AROSG *arOsg); + +#ifdef __cplusplus +} +#endif + +#endif // !AR_OSG_H + + diff --git a/libs/include/AR/arvrml.h b/libs/include/AR/arvrml.h new file mode 100755 index 0000000..2380224 --- /dev/null +++ b/libs/include/AR/arvrml.h @@ -0,0 +1,68 @@ +/* + * arvrml.h + * ARToolKit5 + * + * This file is part of ARToolKit. + * + * ARToolKit is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ARToolKit is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ARToolKit. If not, see . + * + * As a special exception, the copyright holders of this library give you + * permission to link this library with independent modules to produce an + * executable, regardless of the license terms of these independent modules, and to + * copy and distribute the resulting executable under terms of your choice, + * provided that you also meet, for each linked independent module, the terms and + * conditions of the license of that module. An independent module is a module + * which is neither derived from nor based on this library. If you modify this + * library, you may extend this exception to your version of the library, but you + * are not obligated to do so. If you do not wish to do so, delete this exception + * statement from your version. + * + * Copyright 2015 Daqri, LLC. + * Copyright 2002-2015 ARToolworks, Inc. + * + * Author(s): Hirokazu Kato, Philip Lamb + * + */ +#ifndef AR_VRML_H +#define AR_VRML_H + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef _WIN32 +# ifdef LIBARVRML_EXPORTS +# define AR_DLL_API __declspec(dllexport) +# else +# ifdef _DLL +# define AR_DLL_API __declspec(dllimport) +# else +# define AR_DLL_API extern +# endif +# endif +#else +# define AR_DLL_API +#endif + +AR_DLL_API int arVrmlLoadFile(const char *file); +AR_DLL_API int arVrmlFree( int id ); +AR_DLL_API int arVrmlDraw( int id ); +AR_DLL_API int arVrmlTimerUpdate( void ); +AR_DLL_API int arVrmlSetInternalLight( int flag ); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/libs/include/AR/config.h b/libs/include/AR/config.h new file mode 100644 index 0000000..054e49e --- /dev/null +++ b/libs/include/AR/config.h @@ -0,0 +1,578 @@ +/* + * config.h + * ARToolKit5 + * + * This file is part of ARToolKit. + * + * ARToolKit is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ARToolKit is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ARToolKit. If not, see . + * + * As a special exception, the copyright holders of this library give you + * permission to link this library with independent modules to produce an + * executable, regardless of the license terms of these independent modules, and to + * copy and distribute the resulting executable under terms of your choice, + * provided that you also meet, for each linked independent module, the terms and + * conditions of the license of that module. An independent module is a module + * which is neither derived from nor based on this library. If you modify this + * library, you may extend this exception to your version of the library, but you + * are not obligated to do so. If you do not wish to do so, delete this exception + * statement from your version. + * + * Copyright 2015 Daqri, LLC. + * Copyright 2002-2015 ARToolworks, Inc. + * + * Author(s): Hirokazu Kato, Philip Lamb + * + */ +/*! + @header config.h + @abstract ARToolKit core configuration. + @version 5.3 + @discussion + @copyright 2015 Daqri, LLC. + */ + + +#ifndef AR_CONFIG0_H +#define AR_CONFIG0_H + +// +// As of version 2.72 and 4.1, ARToolKit supports an OpenGL-like +// versioning system, with both header versions (for the version +// of the ARToolKit SDK installed) and runtime version reporting +// via arGetVersion(). +// + +// The MAJOR version number defines non-backwards compatible +// changes in the ARToolKit API. Range: [0-99]. +#define AR_HEADER_VERSION_MAJOR 5 + +// The MINOR version number defines additions to the ARToolKit +// API, or (occsasionally) other significant backwards-compatible +// changes in runtime functionality. Range: [0-99]. +#define AR_HEADER_VERSION_MINOR 3 + +// The TINY version number defines bug-fixes to existing +// functionality. Range: [0-99]. +#define AR_HEADER_VERSION_TINY 1 + +// The BUILD version number will always be zero in releases, +// but may be non-zero in internal builds or in version-control +// repository-sourced code. Range: [0-99]. +#define AR_HEADER_VERSION_BUILD 0 + +// The string representation below must match the major, minor +// and tiny release numbers. +#define AR_HEADER_VERSION_STRING "5.3.1" + +// The macros below are convenience macros to enable use +// of certain ARToolKit header functionality by the release +// version in which it appeared. +// Each time the major version number is incremented, all +// existing macros must be removed, and just one new one +// added for the new major version. +// Each time the minor version number is incremented, a new +// AR_HAVE_HEADER_VERSION_ macro definition must be added. +// Tiny version numbers (being bug-fix releases, by definition) +// are NOT included in the AR_HAVE_HEADER_VERSION_ system. +#define AR_HAVE_HEADER_VERSION_5 +#define AR_HAVE_HEADER_VERSION_5_1 +#define AR_HAVE_HEADER_VERSION_5_2 +#define AR_HAVE_HEADER_VERSION_5_3 + +// +// End version definitions. +// + +/* +#undef AR_BIG_ENDIAN +#undef AR_LITTLE_ENDIAN +*/ + +/*! + @typedef AR_PIXEL_FORMAT + @abstract ARToolKit pixel-format specifiers. + @discussion + ARToolKit functions can accept pixel data in a variety of formats. + This enumerations provides a set of constants you can use to request + data in a particular pixel format from an ARToolKit function that + returns data to you, or to specify that data you are providing to an + ARToolKit function is in a particular pixel format. + @constant AR_PIXEL_FORMAT_RGB + Each pixel is represented by 24 bits. Eight bits per each Red, Green, + and Blue component. This is the native 24 bit format for the Mac platform. + @constant AR_PIXEL_FORMAT_BGR + Each pixel is represented by 24 bits. Eight bits per each Blue, Red, and + Green component. This is the native 24 bit format for the Win32 platform. + @constant AR_PIXEL_FORMAT_RGBA + Each pixel is represented by 32 bits. Eight bits per each Red, Green, + Blue, and Alpha component. + @constant AR_PIXEL_FORMAT_BGRA + Each pixel is represented by 32 bits. Eight bits per each Blue, Green, + Red, and Alpha component. This is the native 32 bit format for the Win32 + and Mac Intel platforms. + @constant AR_PIXEL_FORMAT_ABGR + Each pixel is represented by 32 bits. Eight bits per each Alpha, Blue, + Green, and Red component. This is the native 32 bit format for the SGI + platform. + @constant AR_PIXEL_FORMAT_MONO + Each pixel is represented by 8 bits of luminance information. + @constant AR_PIXEL_FORMAT_ARGB + Each pixel is represented by 32 bits. Eight bits per each Alpha, Red, + Green, and Blue component. This is the native 32 bit format for the Mac + PowerPC platform. + @constant AR_PIXEL_FORMAT_2vuy + 8-bit 4:2:2 Component Y'CbCr format. Each 16 bit pixel is represented + by an unsigned eight bit luminance component and two unsigned eight bit + chroma components. Each pair of pixels shares a common set of chroma + values. The components are ordered in memory; Cb, Y0, Cr, Y1. The + luminance components have a range of [16, 235], while the chroma value + has a range of [16, 240]. This is consistent with the CCIR601 spec. + This format is fairly prevalent on both Mac and Win32 platforms. + '2vuy' is the Apple QuickTime four-character code for this pixel format. + The equivalent Microsoft fourCC is 'UYVY'. + @constant AR_PIXEL_FORMAT_yuvs + 8-bit 4:2:2 Component Y'CbCr format. Identical to the AR_PIXEL_FORMAT_2vuy except + each 16 bit word has been byte swapped. This results in a component + ordering of; Y0, Cb, Y1, Cr. + This is most prevalent yuv 4:2:2 format on both Mac and Win32 platforms. + 'yuvs' is the Apple QuickTime four-character code for this pixel format. + The equivalent Microsoft fourCC is 'YUY2'. + @constant AR_PIXEL_FORMAT_RGB_565 + A packed-pixel format. Each 16 bit pixel consists of 5 bits of red color + information in bits 15-11, 6 bits of green color information in bits 10-5, + and 5 bits of blue color information in bits 4-0. Byte ordering is big-endian. + @constant AR_PIXEL_FORMAT_RGBA_5551 + A packed-pixel format. Each 16 bit pixel consists of 5 bits of red color + information in bits 15-11, 5 bits of green color information in bits 10-6, + 5 bits of blue color information in bits 5-1, and a single alpha bit in bit 0. + Byte ordering is big-endian. + @constant AR_PIXEL_FORMAT_RGBA_4444 + A packed-pixel format. Each 16 bit pixel consists of 4 bits of red color + information in bits 15-12, 6 bits of green color information in bits 11-8, + 4 bits of blue color information in bits 7-4, and 4 bits of alpha information + in bits 3-0. Byte ordering is big-endian. + @constant AR_PIXEL_FORMAT_420v + 8-bit 4:2:0 Component Y'CbCr format. Each 2x2 pixel block is represented + by 4 unsigned eight bit luminance values and two unsigned eight bit + chroma values. The chroma plane and luma plane are separated in memory. The + luminance components have a range of [16, 235], while the chroma value + has a range of [16, 240]. This is consistent with the CCIR601 spec. + '420v' is the Apple Core Video four-character code for this pixel format. + @constant AR_PIXEL_FORMAT_420f + 8-bit 4:2:0 Component Y'CbCr format. Each 2x2 pixel block is represented + by 4 unsigned eight bit luminance components and two unsigned eight bit + chroma components. The chroma plane and luma plane are separated in memory. The + luminance components have a range of [0, 255], while the chroma value + has a range of [1, 255]. + '420f' is the Apple Core Video four-character code for this pixel format. + The equivalent Microsoft fourCC is 'NV12'. + @constant AR_PIXEL_FORMAT_NV21 + 8-bit 4:2:0 Component Y'CbCr format. Each 2x2 pixel block is represented + by 4 unsigned eight bit luminance components and two unsigned eight bit + chroma components. The chroma plane and luma plane are separated in memory. The + luminance components have a range of [0, 255], while the chroma value + has a range of [1, 255]. + */ +typedef enum { + AR_PIXEL_FORMAT_INVALID = -1, + AR_PIXEL_FORMAT_RGB = 0, + AR_PIXEL_FORMAT_BGR, + AR_PIXEL_FORMAT_RGBA, + AR_PIXEL_FORMAT_BGRA, + AR_PIXEL_FORMAT_ABGR, + AR_PIXEL_FORMAT_MONO, + AR_PIXEL_FORMAT_ARGB, + AR_PIXEL_FORMAT_2vuy, + AR_PIXEL_FORMAT_yuvs, + AR_PIXEL_FORMAT_RGB_565, + AR_PIXEL_FORMAT_RGBA_5551, + AR_PIXEL_FORMAT_RGBA_4444, + AR_PIXEL_FORMAT_420v, + AR_PIXEL_FORMAT_420f, + AR_PIXEL_FORMAT_NV21 +} AR_PIXEL_FORMAT; +#define AR_PIXEL_FORMAT_UYVY AR_PIXEL_FORMAT_2vuy +#define AR_PIXEL_FORMAT_YUY2 AR_PIXEL_FORMAT_yuvs + +// Note if making changes to the above table: +// If the number of pixel formats supported changes, AR_PIXEL_FORMAT_MAX must too. +// The functions arVideoUtilGetPixelSize(), arVideoUtilGetPixelFormatName() +// and arUtilGetPixelSize() arUtilGetPixelFormatName() must also be edited. +#define AR_PIXEL_FORMAT_MAX AR_PIXEL_FORMAT_NV21 + +enum { + AR_LOG_LEVEL_DEBUG = 0, + AR_LOG_LEVEL_INFO, + AR_LOG_LEVEL_WARN, + AR_LOG_LEVEL_ERROR, + AR_LOG_LEVEL_REL_INFO +}; +#define AR_LOG_LEVEL_DEFAULT AR_LOG_LEVEL_INFO + +/*------------------------------------------------------------*/ +/* */ +/* For Linux */ +/* AR_INPUT_V4L: use of standard Video4Linux Library */ +/* AR_INPUT_DV: use of DV Camera */ +/* AR_INPUT_1394CAM: use of 1394 Digital Camara */ +/* AR_INPUT_GSTREAMER: use of GStreamer library */ +/* */ +/*------------------------------------------------------------*/ +#ifdef __linux + +#define AR_CALLBACK + +// Endianness. +# if defined(__BIG_ENDIAN__) // Check architecture endianess using gcc's macro, or assume little-endian by default. +# define AR_BIG_ENDIAN // Most Significant Byte has greatest address in memory (ppc). +# undef AR_LITTLE_ENDIAN +# elif defined (__LITTLE_ENDIAN__) +# undef AR_BIG_ENDIAN // Least significant Byte has greatest address in memory (i386). +# define AR_LITTLE_ENDIAN +# else +# define AR_LITTLE_ENDIAN +# endif + +// Input modules. This is edited by the configure script. +#undef AR_INPUT_V4L +#undef AR_INPUT_DV +#undef AR_INPUT_1394CAM +#undef AR_INPUT_GSTREAMER +#undef AR_INPUT_IMAGE +#define AR_INPUT_DUMMY + +// Default input module. This is edited by the configure script. +#undef AR_DEFAULT_INPUT_V4L +#undef AR_DEFAULT_INPUT_DV +#undef AR_DEFAULT_INPUT_1394CAM +#undef AR_DEFAULT_INPUT_GSTREAMER +#undef AR_DEFAULT_INPUT_IMAGE +#undef AR_DEFAULT_INPUT_DUMMY + +// Other Linux-only configuration. +#define HAVE_LIBJPEG 1 + +#endif // __linux + +// Default pixel formats. + +#ifdef AR_INPUT_V4L +/* #define AR_INPUT_V4L_DEFAULT_PIXEL_FORMAT AR_PIXEL_FORMAT_BGR */ +/* #define AR_INPUT_V4L_DEFAULT_PIXEL_FORMAT AR_PIXEL_FORMAT_BGRA */ +#define AR_INPUT_V4L_DEFAULT_PIXEL_FORMAT AR_PIXEL_FORMAT_BGR +#endif + +#ifdef AR_INPUT_DV +/* #define AR_INPUT_DV_DEFAULT_PIXEL_FORMAT AR_PIXEL_FORMAT_RGB */ +/* #define AR_INPUT_DV_DEFAULT_PIXEL_FORMAT AR_PIXEL_FORMAT_BGRA */ +#define AR_INPUT_DV_DEFAULT_PIXEL_FORMAT AR_PIXEL_FORMAT_RGB +#endif + +#ifdef AR_INPUT_1394CAM +#undef AR_INPUT_1394CAM_USE_LIBDC1394_V2 +/* #define AR_INPUT_1394CAM_DEFAULT_PIXEL_FORMAT AR_PIXEL_FORMAT_MONO */ +/* #define AR_INPUT_1394CAM_DEFAULT_PIXEL_FORMAT AR_PIXEL_FORMAT_RGB */ +#define AR_INPUT_1394CAM_DEFAULT_PIXEL_FORMAT AR_PIXEL_FORMAT_MONO +#undef AR_INPUT_1394CAM_USE_DRAGONFLY +#undef AR_INPUT_1394CAM_USE_DF_EXPRESS +#undef AR_INPUT_1394CAM_USE_FLEA +#undef AR_INPUT_1394CAM_USE_FLEA_XGA +#undef AR_INPUT_1394CAM_USE_DFK21AF04 +#endif + +#ifdef AR_INPUT_GSTREAMER +#define AR_INPUT_GSTREAMER_PIXEL_FORMAT AR_PIXEL_FORMAT_RGB +#endif + + + +/*------------------------------------------------------------*/ +/* For SGI */ +/*------------------------------------------------------------*/ +#ifdef __sgi +#define AR_CALLBACK +#define AR_BIG_ENDIAN +#undef AR_LITTLE_ENDIAN +#define AR_INPUT_SGI +#define AR_INPUT_DUMMY +#define AR_DEFAULT_INPUT_SGI */ +#undef AR_DEFAULT_INPUT_DUMMY +#endif // __sgi + +#ifdef AR_INPUT_SGI +#define AR_INPUT_SGI_PIXEL_FORMAT AR_PIXEL_FORMAT_ABGR +#endif + +/*------------------------------------------------------------*/ +/* For Windows */ +/*------------------------------------------------------------*/ +#ifdef _WIN32 + +// Include Windows API. +#ifndef WIN32_LEAN_AND_MEAN +# define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers +#endif +#include // Minimum supported version. See http://msdn.microsoft.com/en-us/library/windows/desktop/aa383745.aspx +#include + +#define AR_CALLBACK __stdcall +#define strdup _strdup + +// Define _WINRT for support Windows Runtime platforms. +#if defined(WINAPI_FAMILY) +# if (WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP) // Windows Phone 8.1 and later. +# if (_WIN32_WINNT >= 0x0603) // (_WIN32_WINNT_WINBLUE) +# define _WINRT +# define LIBARVIDEO_STATIC +# define ARDOUBLE_IS_FLOAT +# else +# error ARToolKit for Windows Phone requires Windows Phone 8.1 or later. Please compile with Visual Studio 2013 or later with Windows Phone 8.1 SDK installed and with _WIN32_WINNT=0x0603 in your project compiler settings (setting /D_WIN32_WINNT=0x0603). +# endif +# elif (WINAPI_FAMILY == WINAPI_FAMILY_PC_APP) // Windows Store 8.1 and later. +# if (_WIN32_WINNT >= 0x0603) // (_WIN32_WINNT_WINBLUE) +# define _WINRT +# define LIBARVIDEO_STATIC +# define ARDOUBLE_IS_FLOAT +# else +# error ARToolKit for Windows Store requires Windows 8.1 or later. Please compile with Visual Studio 2013 or later with Windows 8.1 SDK installed and with _WIN32_WINNT=0x0603 in your project compiler settings (setting /D_WIN32_WINNT=0x0603). +# endif +# endif +#endif + +// Endianness. +// Windows on x86, x86-64 and ARM all run little-endian. +#undef AR_BIG_ENDIAN +#define AR_LITTLE_ENDIAN + +// Input modules. This is edited by the configure script. +#define AR_INPUT_DUMMY +#undef AR_INPUT_IMAGE +#undef AR_INPUT_WINDOWS_DIRECTSHOW +#if !defined(_WIN64) || _MSC_VER >= 1800 // DSVideoLib 64-bit only on release for Visual Studio 2013 and later. +#undef AR_INPUT_WINDOWS_DSVIDEOLIB +#endif +#ifndef _WIN64 // QuickTime is not available for 64-bit. +#undef AR_INPUT_QUICKTIME +#endif +#undef AR_INPUT_WINDOWS_DRAGONFLY +#undef AR_INPUT_WINDOWS_MEDIA_FOUNDATION +#undef AR_INPUT_WINDOWS_MEDIA_CAPTURE + +// Default input module. This is edited by the configure script. +#undef AR_DEFAULT_INPUT_DUMMY +#undef AR_DEFAULT_INPUT_IMAGE +#undef AR_DEFAULT_INPUT_WINDOWS_DIRECTSHOW +#if !defined(_WIN64) || _MSC_VER >= 1800 // DSVideoLib 64-bit only on release for Visual Studio 2013 and later. +#undef AR_DEFAULT_INPUT_WINDOWS_DSVIDEOLIB +#endif +#ifndef _WIN64 // QuickTime is not available for 64-bit. +#undef AR_DEFAULT_INPUT_QUICKTIME +#endif +#undef AR_DEFAULT_INPUT_WINDOWS_DRAGONFLY +#undef AR_DEFAULT_INPUT_WINDOWS_MEDIA_FOUNDATION +#undef AR_DEFAULT_INPUT_WINDOWS_MEDIA_CAPTURE + +// Other Windows-only configuration. +#define HAVE_LIBJPEG 1 + +#endif // _WIN32 + +// Default pixel formats. + +#ifdef AR_INPUT_WINDOWS_DIRECTSHOW +#define AR_INPUT_WINDOWS_DIRECTSHOW_PIXEL_FORMAT AR_PIXEL_FORMAT_BGR +#endif + +#ifdef AR_INPUT_WINDOWS_DSVIDEOLIB +#define AR_INPUT_WINDOWS_DSVIDEOLIB_PIXEL_FORMAT AR_PIXEL_FORMAT_BGRA +#endif + +#ifdef AR_INPUT_WINDOWS_DRAGONFLY +#define AR_INPUT_WINDOWS_DRAGONFLY_PIXEL_FORMAT AR_PIXEL_FORMAT_BGR +#endif + +#ifdef AR_INPUT_WINDOWS_MEDIA_FOUNDATION +#define AR_INPUT_WINDOWS_MEDIA_FOUNDATION_PIXEL_FORMAT AR_PIXEL_FORMAT_BGRA +#endif + +#ifdef AR_INPUT_WINDOWS_MEDIA_CAPTURE +#define AR_INPUT_WINDOWS_MEDIA_CAPTURE_PIXEL_FORMAT AR_PIXEL_FORMAT_BGRA +#endif + +/*------------------------------------------------------------*/ +/* For Android */ +/*------------------------------------------------------------*/ + +#if defined ANDROID +#define AR_CALLBACK +#define ARDOUBLE_IS_FLOAT +#undef AR_INPUT_DUMMY +#define AR_INPUT_ANDROID +#undef AR_INPUT_IMAGE +#undef AR_DEFAULT_INPUT_DUMMY +#define AR_DEFAULT_INPUT_ANDROID +#undef AR_DEFAULT_INPUT_IMAGE +#define HAVE_LIBJPEG 1 +#define USE_OPENGL_ES 1 +#endif // _ANDROID + +// Default pixel formats. + +#ifdef AR_INPUT_ANDROID +#define AR_INPUT_ANDROID_PIXEL_FORMAT AR_PIXEL_FORMAT_NV21 +#endif + +/*------------------------------------------------------------*/ +/* For Mac OS X */ +/*------------------------------------------------------------*/ +#if __APPLE__ + +# include +# include + +# define AR_CALLBACK + +// Endianness. +# if TARGET_RT_BIG_ENDIAN +# define AR_BIG_ENDIAN // Most Significant Byte has greatest address in memory (ppc). +# undef AR_LITTLE_ENDIAN +# elif TARGET_RT_LITTLE_ENDIAN +# undef AR_BIG_ENDIAN +# define AR_LITTLE_ENDIAN +# else +# error +# endif + +#if TARGET_IPHONE_SIMULATOR + +#error This release does not support the simulator. Please target an iOS device. +#define ARDOUBLE_IS_FLOAT +#define AR_INPUT_DUMMY +#define AR_DEFAULT_INPUT_DUMMY + +#elif TARGET_OS_IPHONE + +#define ARDOUBLE_IS_FLOAT +#undef AR_INPUT_DUMMY +#define AR_INPUT_IPHONE +#undef AR_INPUT_IMAGE +#undef AR_DEFAULT_INPUT_DUMMY +#define AR_DEFAULT_INPUT_IPHONE +#undef AR_DEFAULT_INPUT_IMAGE +#define HAVE_LIBJPEG 1 +#define USE_OPENGL_ES 1 +#ifdef __LP64__ +# define HAVE_ARM64_NEON 1 +#else +# define HAVE_ARM_NEON 1 +#endif + +#elif TARGET_OS_MAC + +#if !defined(__LP64__) // QuickTime not available on 64-bit system. +#define AR_INPUT_QUICKTIME +#define AR_DEFAULT_INPUT_QUICKTIME +#endif +#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4 || QTKIT_VERSION_MAX_ALLOWED >= QTKIT_VERSION_7_2 // QTKit not available until OS X 10.4. +#define AR_INPUT_QUICKTIME7 +#undef AR_DEFAULT_INPUT_QUICKTIME +#define AR_DEFAULT_INPUT_QUICKTIME7 +#endif +#define AR_INPUT_DUMMY +#define AR_INPUT_IMAGE +#undef AR_DEFAULT_INPUT_DUMMY +#undef AR_DEFAULT_INPUT_IMAGE +#define HAVE_LIBJPEG 1 + +#endif + +#endif // __APPLE__ + +// Default pixel formats. + +#ifdef AR_INPUT_QUICKTIME7 +#define AR_INPUT_QUICKTIME7_DEFAULT_PIXEL_FORMAT AR_PIXEL_FORMAT_ARGB +#endif + +#ifdef AR_INPUT_IPHONE +#define AR_INPUT_IPHONE_DEFAULT_PIXEL_FORMAT AR_PIXEL_FORMAT_BGRA +#endif + +/*------------------------------------------------------------*/ +/* Multi-platform inputs */ +/*------------------------------------------------------------*/ + +#ifdef AR_INPUT_DUMMY +#define AR_INPUT_DUMMY_DEFAULT_PIXEL_FORMAT AR_PIXEL_FORMAT_RGB +#endif + +#ifdef AR_INPUT_QUICKTIME +#define AR_INPUT_QUICKTIME_DEFAULT_PIXEL_FORMAT AR_PIXEL_FORMAT_ARGB +#endif + +#ifdef AR_INPUT_IMAGE +#define AR_INPUT_IMAGE_DEFAULT_PIXEL_FORMAT AR_PIXEL_FORMAT_RGB +#endif + +// +// Setup AR_DEFAULT_PIXEL_FORMAT. +// + +#if defined(AR_DEFAULT_INPUT_DUMMY) +# define AR_DEFAULT_PIXEL_FORMAT AR_INPUT_DUMMY_DEFAULT_PIXEL_FORMAT +#elif defined(AR_DEFAULT_INPUT_V4L) +# define AR_DEFAULT_PIXEL_FORMAT AR_INPUT_V4L_DEFAULT_PIXEL_FORMAT +#elif defined(AR_DEFAULT_INPUT_DV) +# define AR_DEFAULT_PIXEL_FORMAT AR_INPUT_DV_DEFAULT_PIXEL_FORMAT +#elif defined(AR_DEFAULT_INPUT_1394CAM) +# define AR_DEFAULT_PIXEL_FORMAT AR_INPUT_1394CAM_DEFAULT_PIXEL_FORMAT +#elif defined(AR_DEFAULT_INPUT_SGI) +# define AR_DEFAULT_PIXEL_FORMAT AR_INPUT_SGI_PIXEL_FORMAT +#elif defined(AR_DEFAULT_INPUT_WINDOWS_DIRECTSHOW) +# define AR_DEFAULT_PIXEL_FORMAT AR_INPUT_WINDOWS_DIRECTSHOW_PIXEL_FORMAT +#elif defined(AR_DEFAULT_INPUT_WINDOWS_DRAGONFLY) +# define AR_DEFAULT_PIXEL_FORMAT AR_INPUT_WINDOWS_DRAGONFLY_PIXEL_FORMAT +#elif defined(AR_DEFAULT_INPUT_QUICKTIME) +# define AR_DEFAULT_PIXEL_FORMAT AR_INPUT_QUICKTIME_DEFAULT_PIXEL_FORMAT +#elif defined(AR_DEFAULT_INPUT_WINDOWS_DSVIDEOLIB) +# define AR_DEFAULT_PIXEL_FORMAT AR_INPUT_WINDOWS_DSVIDEOLIB_PIXEL_FORMAT +#elif defined(AR_DEFAULT_INPUT_GSTREAMER) +# define AR_DEFAULT_PIXEL_FORMAT AR_INPUT_GSTREAMER_PIXEL_FORMAT +#elif defined(AR_DEFAULT_INPUT_IPHONE) +# define AR_DEFAULT_PIXEL_FORMAT AR_INPUT_IPHONE_DEFAULT_PIXEL_FORMAT +#elif defined(AR_DEFAULT_INPUT_QUICKTIME7) +# define AR_DEFAULT_PIXEL_FORMAT AR_INPUT_QUICKTIME7_DEFAULT_PIXEL_FORMAT +#elif defined(AR_DEFAULT_INPUT_ANDROID) +# define AR_DEFAULT_PIXEL_FORMAT AR_INPUT_ANDROID_PIXEL_FORMAT +#elif defined(AR_DEFAULT_INPUT_IMAGE) +# define AR_DEFAULT_PIXEL_FORMAT AR_INPUT_IMAGE_DEFAULT_PIXEL_FORMAT +#elif defined(AR_DEFAULT_INPUT_WINDOWS_MEDIA_FOUNDATION) +# define AR_DEFAULT_PIXEL_FORMAT AR_INPUT_WINDOWS_MEDIA_FOUNDATION_PIXEL_FORMAT +#elif defined(AR_DEFAULT_INPUT_WINDOWS_MEDIA_CAPTURE) +# define AR_DEFAULT_PIXEL_FORMAT AR_INPUT_WINDOWS_MEDIA_CAPTURE_PIXEL_FORMAT +#else +# error +#endif + +// +// If trying to minimize memory footprint, disable a few things. +// + +#if AR_ENABLE_MINIMIZE_MEMORY_FOOTPRINT +#define AR_DISABLE_THRESH_MODE_AUTO_ADAPTIVE 1 +#define AR_DISABLE_NON_CORE_FNS 1 +#define AR_DISABLE_LABELING_DEBUG_MODE 1 +#endif + +#endif // !AR_CONFIG0_H diff --git a/libs/include/AR/config.h.in b/libs/include/AR/config.h.in new file mode 100755 index 0000000..054e49e --- /dev/null +++ b/libs/include/AR/config.h.in @@ -0,0 +1,578 @@ +/* + * config.h + * ARToolKit5 + * + * This file is part of ARToolKit. + * + * ARToolKit is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ARToolKit is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ARToolKit. If not, see . + * + * As a special exception, the copyright holders of this library give you + * permission to link this library with independent modules to produce an + * executable, regardless of the license terms of these independent modules, and to + * copy and distribute the resulting executable under terms of your choice, + * provided that you also meet, for each linked independent module, the terms and + * conditions of the license of that module. An independent module is a module + * which is neither derived from nor based on this library. If you modify this + * library, you may extend this exception to your version of the library, but you + * are not obligated to do so. If you do not wish to do so, delete this exception + * statement from your version. + * + * Copyright 2015 Daqri, LLC. + * Copyright 2002-2015 ARToolworks, Inc. + * + * Author(s): Hirokazu Kato, Philip Lamb + * + */ +/*! + @header config.h + @abstract ARToolKit core configuration. + @version 5.3 + @discussion + @copyright 2015 Daqri, LLC. + */ + + +#ifndef AR_CONFIG0_H +#define AR_CONFIG0_H + +// +// As of version 2.72 and 4.1, ARToolKit supports an OpenGL-like +// versioning system, with both header versions (for the version +// of the ARToolKit SDK installed) and runtime version reporting +// via arGetVersion(). +// + +// The MAJOR version number defines non-backwards compatible +// changes in the ARToolKit API. Range: [0-99]. +#define AR_HEADER_VERSION_MAJOR 5 + +// The MINOR version number defines additions to the ARToolKit +// API, or (occsasionally) other significant backwards-compatible +// changes in runtime functionality. Range: [0-99]. +#define AR_HEADER_VERSION_MINOR 3 + +// The TINY version number defines bug-fixes to existing +// functionality. Range: [0-99]. +#define AR_HEADER_VERSION_TINY 1 + +// The BUILD version number will always be zero in releases, +// but may be non-zero in internal builds or in version-control +// repository-sourced code. Range: [0-99]. +#define AR_HEADER_VERSION_BUILD 0 + +// The string representation below must match the major, minor +// and tiny release numbers. +#define AR_HEADER_VERSION_STRING "5.3.1" + +// The macros below are convenience macros to enable use +// of certain ARToolKit header functionality by the release +// version in which it appeared. +// Each time the major version number is incremented, all +// existing macros must be removed, and just one new one +// added for the new major version. +// Each time the minor version number is incremented, a new +// AR_HAVE_HEADER_VERSION_ macro definition must be added. +// Tiny version numbers (being bug-fix releases, by definition) +// are NOT included in the AR_HAVE_HEADER_VERSION_ system. +#define AR_HAVE_HEADER_VERSION_5 +#define AR_HAVE_HEADER_VERSION_5_1 +#define AR_HAVE_HEADER_VERSION_5_2 +#define AR_HAVE_HEADER_VERSION_5_3 + +// +// End version definitions. +// + +/* +#undef AR_BIG_ENDIAN +#undef AR_LITTLE_ENDIAN +*/ + +/*! + @typedef AR_PIXEL_FORMAT + @abstract ARToolKit pixel-format specifiers. + @discussion + ARToolKit functions can accept pixel data in a variety of formats. + This enumerations provides a set of constants you can use to request + data in a particular pixel format from an ARToolKit function that + returns data to you, or to specify that data you are providing to an + ARToolKit function is in a particular pixel format. + @constant AR_PIXEL_FORMAT_RGB + Each pixel is represented by 24 bits. Eight bits per each Red, Green, + and Blue component. This is the native 24 bit format for the Mac platform. + @constant AR_PIXEL_FORMAT_BGR + Each pixel is represented by 24 bits. Eight bits per each Blue, Red, and + Green component. This is the native 24 bit format for the Win32 platform. + @constant AR_PIXEL_FORMAT_RGBA + Each pixel is represented by 32 bits. Eight bits per each Red, Green, + Blue, and Alpha component. + @constant AR_PIXEL_FORMAT_BGRA + Each pixel is represented by 32 bits. Eight bits per each Blue, Green, + Red, and Alpha component. This is the native 32 bit format for the Win32 + and Mac Intel platforms. + @constant AR_PIXEL_FORMAT_ABGR + Each pixel is represented by 32 bits. Eight bits per each Alpha, Blue, + Green, and Red component. This is the native 32 bit format for the SGI + platform. + @constant AR_PIXEL_FORMAT_MONO + Each pixel is represented by 8 bits of luminance information. + @constant AR_PIXEL_FORMAT_ARGB + Each pixel is represented by 32 bits. Eight bits per each Alpha, Red, + Green, and Blue component. This is the native 32 bit format for the Mac + PowerPC platform. + @constant AR_PIXEL_FORMAT_2vuy + 8-bit 4:2:2 Component Y'CbCr format. Each 16 bit pixel is represented + by an unsigned eight bit luminance component and two unsigned eight bit + chroma components. Each pair of pixels shares a common set of chroma + values. The components are ordered in memory; Cb, Y0, Cr, Y1. The + luminance components have a range of [16, 235], while the chroma value + has a range of [16, 240]. This is consistent with the CCIR601 spec. + This format is fairly prevalent on both Mac and Win32 platforms. + '2vuy' is the Apple QuickTime four-character code for this pixel format. + The equivalent Microsoft fourCC is 'UYVY'. + @constant AR_PIXEL_FORMAT_yuvs + 8-bit 4:2:2 Component Y'CbCr format. Identical to the AR_PIXEL_FORMAT_2vuy except + each 16 bit word has been byte swapped. This results in a component + ordering of; Y0, Cb, Y1, Cr. + This is most prevalent yuv 4:2:2 format on both Mac and Win32 platforms. + 'yuvs' is the Apple QuickTime four-character code for this pixel format. + The equivalent Microsoft fourCC is 'YUY2'. + @constant AR_PIXEL_FORMAT_RGB_565 + A packed-pixel format. Each 16 bit pixel consists of 5 bits of red color + information in bits 15-11, 6 bits of green color information in bits 10-5, + and 5 bits of blue color information in bits 4-0. Byte ordering is big-endian. + @constant AR_PIXEL_FORMAT_RGBA_5551 + A packed-pixel format. Each 16 bit pixel consists of 5 bits of red color + information in bits 15-11, 5 bits of green color information in bits 10-6, + 5 bits of blue color information in bits 5-1, and a single alpha bit in bit 0. + Byte ordering is big-endian. + @constant AR_PIXEL_FORMAT_RGBA_4444 + A packed-pixel format. Each 16 bit pixel consists of 4 bits of red color + information in bits 15-12, 6 bits of green color information in bits 11-8, + 4 bits of blue color information in bits 7-4, and 4 bits of alpha information + in bits 3-0. Byte ordering is big-endian. + @constant AR_PIXEL_FORMAT_420v + 8-bit 4:2:0 Component Y'CbCr format. Each 2x2 pixel block is represented + by 4 unsigned eight bit luminance values and two unsigned eight bit + chroma values. The chroma plane and luma plane are separated in memory. The + luminance components have a range of [16, 235], while the chroma value + has a range of [16, 240]. This is consistent with the CCIR601 spec. + '420v' is the Apple Core Video four-character code for this pixel format. + @constant AR_PIXEL_FORMAT_420f + 8-bit 4:2:0 Component Y'CbCr format. Each 2x2 pixel block is represented + by 4 unsigned eight bit luminance components and two unsigned eight bit + chroma components. The chroma plane and luma plane are separated in memory. The + luminance components have a range of [0, 255], while the chroma value + has a range of [1, 255]. + '420f' is the Apple Core Video four-character code for this pixel format. + The equivalent Microsoft fourCC is 'NV12'. + @constant AR_PIXEL_FORMAT_NV21 + 8-bit 4:2:0 Component Y'CbCr format. Each 2x2 pixel block is represented + by 4 unsigned eight bit luminance components and two unsigned eight bit + chroma components. The chroma plane and luma plane are separated in memory. The + luminance components have a range of [0, 255], while the chroma value + has a range of [1, 255]. + */ +typedef enum { + AR_PIXEL_FORMAT_INVALID = -1, + AR_PIXEL_FORMAT_RGB = 0, + AR_PIXEL_FORMAT_BGR, + AR_PIXEL_FORMAT_RGBA, + AR_PIXEL_FORMAT_BGRA, + AR_PIXEL_FORMAT_ABGR, + AR_PIXEL_FORMAT_MONO, + AR_PIXEL_FORMAT_ARGB, + AR_PIXEL_FORMAT_2vuy, + AR_PIXEL_FORMAT_yuvs, + AR_PIXEL_FORMAT_RGB_565, + AR_PIXEL_FORMAT_RGBA_5551, + AR_PIXEL_FORMAT_RGBA_4444, + AR_PIXEL_FORMAT_420v, + AR_PIXEL_FORMAT_420f, + AR_PIXEL_FORMAT_NV21 +} AR_PIXEL_FORMAT; +#define AR_PIXEL_FORMAT_UYVY AR_PIXEL_FORMAT_2vuy +#define AR_PIXEL_FORMAT_YUY2 AR_PIXEL_FORMAT_yuvs + +// Note if making changes to the above table: +// If the number of pixel formats supported changes, AR_PIXEL_FORMAT_MAX must too. +// The functions arVideoUtilGetPixelSize(), arVideoUtilGetPixelFormatName() +// and arUtilGetPixelSize() arUtilGetPixelFormatName() must also be edited. +#define AR_PIXEL_FORMAT_MAX AR_PIXEL_FORMAT_NV21 + +enum { + AR_LOG_LEVEL_DEBUG = 0, + AR_LOG_LEVEL_INFO, + AR_LOG_LEVEL_WARN, + AR_LOG_LEVEL_ERROR, + AR_LOG_LEVEL_REL_INFO +}; +#define AR_LOG_LEVEL_DEFAULT AR_LOG_LEVEL_INFO + +/*------------------------------------------------------------*/ +/* */ +/* For Linux */ +/* AR_INPUT_V4L: use of standard Video4Linux Library */ +/* AR_INPUT_DV: use of DV Camera */ +/* AR_INPUT_1394CAM: use of 1394 Digital Camara */ +/* AR_INPUT_GSTREAMER: use of GStreamer library */ +/* */ +/*------------------------------------------------------------*/ +#ifdef __linux + +#define AR_CALLBACK + +// Endianness. +# if defined(__BIG_ENDIAN__) // Check architecture endianess using gcc's macro, or assume little-endian by default. +# define AR_BIG_ENDIAN // Most Significant Byte has greatest address in memory (ppc). +# undef AR_LITTLE_ENDIAN +# elif defined (__LITTLE_ENDIAN__) +# undef AR_BIG_ENDIAN // Least significant Byte has greatest address in memory (i386). +# define AR_LITTLE_ENDIAN +# else +# define AR_LITTLE_ENDIAN +# endif + +// Input modules. This is edited by the configure script. +#undef AR_INPUT_V4L +#undef AR_INPUT_DV +#undef AR_INPUT_1394CAM +#undef AR_INPUT_GSTREAMER +#undef AR_INPUT_IMAGE +#define AR_INPUT_DUMMY + +// Default input module. This is edited by the configure script. +#undef AR_DEFAULT_INPUT_V4L +#undef AR_DEFAULT_INPUT_DV +#undef AR_DEFAULT_INPUT_1394CAM +#undef AR_DEFAULT_INPUT_GSTREAMER +#undef AR_DEFAULT_INPUT_IMAGE +#undef AR_DEFAULT_INPUT_DUMMY + +// Other Linux-only configuration. +#define HAVE_LIBJPEG 1 + +#endif // __linux + +// Default pixel formats. + +#ifdef AR_INPUT_V4L +/* #define AR_INPUT_V4L_DEFAULT_PIXEL_FORMAT AR_PIXEL_FORMAT_BGR */ +/* #define AR_INPUT_V4L_DEFAULT_PIXEL_FORMAT AR_PIXEL_FORMAT_BGRA */ +#define AR_INPUT_V4L_DEFAULT_PIXEL_FORMAT AR_PIXEL_FORMAT_BGR +#endif + +#ifdef AR_INPUT_DV +/* #define AR_INPUT_DV_DEFAULT_PIXEL_FORMAT AR_PIXEL_FORMAT_RGB */ +/* #define AR_INPUT_DV_DEFAULT_PIXEL_FORMAT AR_PIXEL_FORMAT_BGRA */ +#define AR_INPUT_DV_DEFAULT_PIXEL_FORMAT AR_PIXEL_FORMAT_RGB +#endif + +#ifdef AR_INPUT_1394CAM +#undef AR_INPUT_1394CAM_USE_LIBDC1394_V2 +/* #define AR_INPUT_1394CAM_DEFAULT_PIXEL_FORMAT AR_PIXEL_FORMAT_MONO */ +/* #define AR_INPUT_1394CAM_DEFAULT_PIXEL_FORMAT AR_PIXEL_FORMAT_RGB */ +#define AR_INPUT_1394CAM_DEFAULT_PIXEL_FORMAT AR_PIXEL_FORMAT_MONO +#undef AR_INPUT_1394CAM_USE_DRAGONFLY +#undef AR_INPUT_1394CAM_USE_DF_EXPRESS +#undef AR_INPUT_1394CAM_USE_FLEA +#undef AR_INPUT_1394CAM_USE_FLEA_XGA +#undef AR_INPUT_1394CAM_USE_DFK21AF04 +#endif + +#ifdef AR_INPUT_GSTREAMER +#define AR_INPUT_GSTREAMER_PIXEL_FORMAT AR_PIXEL_FORMAT_RGB +#endif + + + +/*------------------------------------------------------------*/ +/* For SGI */ +/*------------------------------------------------------------*/ +#ifdef __sgi +#define AR_CALLBACK +#define AR_BIG_ENDIAN +#undef AR_LITTLE_ENDIAN +#define AR_INPUT_SGI +#define AR_INPUT_DUMMY +#define AR_DEFAULT_INPUT_SGI */ +#undef AR_DEFAULT_INPUT_DUMMY +#endif // __sgi + +#ifdef AR_INPUT_SGI +#define AR_INPUT_SGI_PIXEL_FORMAT AR_PIXEL_FORMAT_ABGR +#endif + +/*------------------------------------------------------------*/ +/* For Windows */ +/*------------------------------------------------------------*/ +#ifdef _WIN32 + +// Include Windows API. +#ifndef WIN32_LEAN_AND_MEAN +# define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers +#endif +#include // Minimum supported version. See http://msdn.microsoft.com/en-us/library/windows/desktop/aa383745.aspx +#include + +#define AR_CALLBACK __stdcall +#define strdup _strdup + +// Define _WINRT for support Windows Runtime platforms. +#if defined(WINAPI_FAMILY) +# if (WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP) // Windows Phone 8.1 and later. +# if (_WIN32_WINNT >= 0x0603) // (_WIN32_WINNT_WINBLUE) +# define _WINRT +# define LIBARVIDEO_STATIC +# define ARDOUBLE_IS_FLOAT +# else +# error ARToolKit for Windows Phone requires Windows Phone 8.1 or later. Please compile with Visual Studio 2013 or later with Windows Phone 8.1 SDK installed and with _WIN32_WINNT=0x0603 in your project compiler settings (setting /D_WIN32_WINNT=0x0603). +# endif +# elif (WINAPI_FAMILY == WINAPI_FAMILY_PC_APP) // Windows Store 8.1 and later. +# if (_WIN32_WINNT >= 0x0603) // (_WIN32_WINNT_WINBLUE) +# define _WINRT +# define LIBARVIDEO_STATIC +# define ARDOUBLE_IS_FLOAT +# else +# error ARToolKit for Windows Store requires Windows 8.1 or later. Please compile with Visual Studio 2013 or later with Windows 8.1 SDK installed and with _WIN32_WINNT=0x0603 in your project compiler settings (setting /D_WIN32_WINNT=0x0603). +# endif +# endif +#endif + +// Endianness. +// Windows on x86, x86-64 and ARM all run little-endian. +#undef AR_BIG_ENDIAN +#define AR_LITTLE_ENDIAN + +// Input modules. This is edited by the configure script. +#define AR_INPUT_DUMMY +#undef AR_INPUT_IMAGE +#undef AR_INPUT_WINDOWS_DIRECTSHOW +#if !defined(_WIN64) || _MSC_VER >= 1800 // DSVideoLib 64-bit only on release for Visual Studio 2013 and later. +#undef AR_INPUT_WINDOWS_DSVIDEOLIB +#endif +#ifndef _WIN64 // QuickTime is not available for 64-bit. +#undef AR_INPUT_QUICKTIME +#endif +#undef AR_INPUT_WINDOWS_DRAGONFLY +#undef AR_INPUT_WINDOWS_MEDIA_FOUNDATION +#undef AR_INPUT_WINDOWS_MEDIA_CAPTURE + +// Default input module. This is edited by the configure script. +#undef AR_DEFAULT_INPUT_DUMMY +#undef AR_DEFAULT_INPUT_IMAGE +#undef AR_DEFAULT_INPUT_WINDOWS_DIRECTSHOW +#if !defined(_WIN64) || _MSC_VER >= 1800 // DSVideoLib 64-bit only on release for Visual Studio 2013 and later. +#undef AR_DEFAULT_INPUT_WINDOWS_DSVIDEOLIB +#endif +#ifndef _WIN64 // QuickTime is not available for 64-bit. +#undef AR_DEFAULT_INPUT_QUICKTIME +#endif +#undef AR_DEFAULT_INPUT_WINDOWS_DRAGONFLY +#undef AR_DEFAULT_INPUT_WINDOWS_MEDIA_FOUNDATION +#undef AR_DEFAULT_INPUT_WINDOWS_MEDIA_CAPTURE + +// Other Windows-only configuration. +#define HAVE_LIBJPEG 1 + +#endif // _WIN32 + +// Default pixel formats. + +#ifdef AR_INPUT_WINDOWS_DIRECTSHOW +#define AR_INPUT_WINDOWS_DIRECTSHOW_PIXEL_FORMAT AR_PIXEL_FORMAT_BGR +#endif + +#ifdef AR_INPUT_WINDOWS_DSVIDEOLIB +#define AR_INPUT_WINDOWS_DSVIDEOLIB_PIXEL_FORMAT AR_PIXEL_FORMAT_BGRA +#endif + +#ifdef AR_INPUT_WINDOWS_DRAGONFLY +#define AR_INPUT_WINDOWS_DRAGONFLY_PIXEL_FORMAT AR_PIXEL_FORMAT_BGR +#endif + +#ifdef AR_INPUT_WINDOWS_MEDIA_FOUNDATION +#define AR_INPUT_WINDOWS_MEDIA_FOUNDATION_PIXEL_FORMAT AR_PIXEL_FORMAT_BGRA +#endif + +#ifdef AR_INPUT_WINDOWS_MEDIA_CAPTURE +#define AR_INPUT_WINDOWS_MEDIA_CAPTURE_PIXEL_FORMAT AR_PIXEL_FORMAT_BGRA +#endif + +/*------------------------------------------------------------*/ +/* For Android */ +/*------------------------------------------------------------*/ + +#if defined ANDROID +#define AR_CALLBACK +#define ARDOUBLE_IS_FLOAT +#undef AR_INPUT_DUMMY +#define AR_INPUT_ANDROID +#undef AR_INPUT_IMAGE +#undef AR_DEFAULT_INPUT_DUMMY +#define AR_DEFAULT_INPUT_ANDROID +#undef AR_DEFAULT_INPUT_IMAGE +#define HAVE_LIBJPEG 1 +#define USE_OPENGL_ES 1 +#endif // _ANDROID + +// Default pixel formats. + +#ifdef AR_INPUT_ANDROID +#define AR_INPUT_ANDROID_PIXEL_FORMAT AR_PIXEL_FORMAT_NV21 +#endif + +/*------------------------------------------------------------*/ +/* For Mac OS X */ +/*------------------------------------------------------------*/ +#if __APPLE__ + +# include +# include + +# define AR_CALLBACK + +// Endianness. +# if TARGET_RT_BIG_ENDIAN +# define AR_BIG_ENDIAN // Most Significant Byte has greatest address in memory (ppc). +# undef AR_LITTLE_ENDIAN +# elif TARGET_RT_LITTLE_ENDIAN +# undef AR_BIG_ENDIAN +# define AR_LITTLE_ENDIAN +# else +# error +# endif + +#if TARGET_IPHONE_SIMULATOR + +#error This release does not support the simulator. Please target an iOS device. +#define ARDOUBLE_IS_FLOAT +#define AR_INPUT_DUMMY +#define AR_DEFAULT_INPUT_DUMMY + +#elif TARGET_OS_IPHONE + +#define ARDOUBLE_IS_FLOAT +#undef AR_INPUT_DUMMY +#define AR_INPUT_IPHONE +#undef AR_INPUT_IMAGE +#undef AR_DEFAULT_INPUT_DUMMY +#define AR_DEFAULT_INPUT_IPHONE +#undef AR_DEFAULT_INPUT_IMAGE +#define HAVE_LIBJPEG 1 +#define USE_OPENGL_ES 1 +#ifdef __LP64__ +# define HAVE_ARM64_NEON 1 +#else +# define HAVE_ARM_NEON 1 +#endif + +#elif TARGET_OS_MAC + +#if !defined(__LP64__) // QuickTime not available on 64-bit system. +#define AR_INPUT_QUICKTIME +#define AR_DEFAULT_INPUT_QUICKTIME +#endif +#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4 || QTKIT_VERSION_MAX_ALLOWED >= QTKIT_VERSION_7_2 // QTKit not available until OS X 10.4. +#define AR_INPUT_QUICKTIME7 +#undef AR_DEFAULT_INPUT_QUICKTIME +#define AR_DEFAULT_INPUT_QUICKTIME7 +#endif +#define AR_INPUT_DUMMY +#define AR_INPUT_IMAGE +#undef AR_DEFAULT_INPUT_DUMMY +#undef AR_DEFAULT_INPUT_IMAGE +#define HAVE_LIBJPEG 1 + +#endif + +#endif // __APPLE__ + +// Default pixel formats. + +#ifdef AR_INPUT_QUICKTIME7 +#define AR_INPUT_QUICKTIME7_DEFAULT_PIXEL_FORMAT AR_PIXEL_FORMAT_ARGB +#endif + +#ifdef AR_INPUT_IPHONE +#define AR_INPUT_IPHONE_DEFAULT_PIXEL_FORMAT AR_PIXEL_FORMAT_BGRA +#endif + +/*------------------------------------------------------------*/ +/* Multi-platform inputs */ +/*------------------------------------------------------------*/ + +#ifdef AR_INPUT_DUMMY +#define AR_INPUT_DUMMY_DEFAULT_PIXEL_FORMAT AR_PIXEL_FORMAT_RGB +#endif + +#ifdef AR_INPUT_QUICKTIME +#define AR_INPUT_QUICKTIME_DEFAULT_PIXEL_FORMAT AR_PIXEL_FORMAT_ARGB +#endif + +#ifdef AR_INPUT_IMAGE +#define AR_INPUT_IMAGE_DEFAULT_PIXEL_FORMAT AR_PIXEL_FORMAT_RGB +#endif + +// +// Setup AR_DEFAULT_PIXEL_FORMAT. +// + +#if defined(AR_DEFAULT_INPUT_DUMMY) +# define AR_DEFAULT_PIXEL_FORMAT AR_INPUT_DUMMY_DEFAULT_PIXEL_FORMAT +#elif defined(AR_DEFAULT_INPUT_V4L) +# define AR_DEFAULT_PIXEL_FORMAT AR_INPUT_V4L_DEFAULT_PIXEL_FORMAT +#elif defined(AR_DEFAULT_INPUT_DV) +# define AR_DEFAULT_PIXEL_FORMAT AR_INPUT_DV_DEFAULT_PIXEL_FORMAT +#elif defined(AR_DEFAULT_INPUT_1394CAM) +# define AR_DEFAULT_PIXEL_FORMAT AR_INPUT_1394CAM_DEFAULT_PIXEL_FORMAT +#elif defined(AR_DEFAULT_INPUT_SGI) +# define AR_DEFAULT_PIXEL_FORMAT AR_INPUT_SGI_PIXEL_FORMAT +#elif defined(AR_DEFAULT_INPUT_WINDOWS_DIRECTSHOW) +# define AR_DEFAULT_PIXEL_FORMAT AR_INPUT_WINDOWS_DIRECTSHOW_PIXEL_FORMAT +#elif defined(AR_DEFAULT_INPUT_WINDOWS_DRAGONFLY) +# define AR_DEFAULT_PIXEL_FORMAT AR_INPUT_WINDOWS_DRAGONFLY_PIXEL_FORMAT +#elif defined(AR_DEFAULT_INPUT_QUICKTIME) +# define AR_DEFAULT_PIXEL_FORMAT AR_INPUT_QUICKTIME_DEFAULT_PIXEL_FORMAT +#elif defined(AR_DEFAULT_INPUT_WINDOWS_DSVIDEOLIB) +# define AR_DEFAULT_PIXEL_FORMAT AR_INPUT_WINDOWS_DSVIDEOLIB_PIXEL_FORMAT +#elif defined(AR_DEFAULT_INPUT_GSTREAMER) +# define AR_DEFAULT_PIXEL_FORMAT AR_INPUT_GSTREAMER_PIXEL_FORMAT +#elif defined(AR_DEFAULT_INPUT_IPHONE) +# define AR_DEFAULT_PIXEL_FORMAT AR_INPUT_IPHONE_DEFAULT_PIXEL_FORMAT +#elif defined(AR_DEFAULT_INPUT_QUICKTIME7) +# define AR_DEFAULT_PIXEL_FORMAT AR_INPUT_QUICKTIME7_DEFAULT_PIXEL_FORMAT +#elif defined(AR_DEFAULT_INPUT_ANDROID) +# define AR_DEFAULT_PIXEL_FORMAT AR_INPUT_ANDROID_PIXEL_FORMAT +#elif defined(AR_DEFAULT_INPUT_IMAGE) +# define AR_DEFAULT_PIXEL_FORMAT AR_INPUT_IMAGE_DEFAULT_PIXEL_FORMAT +#elif defined(AR_DEFAULT_INPUT_WINDOWS_MEDIA_FOUNDATION) +# define AR_DEFAULT_PIXEL_FORMAT AR_INPUT_WINDOWS_MEDIA_FOUNDATION_PIXEL_FORMAT +#elif defined(AR_DEFAULT_INPUT_WINDOWS_MEDIA_CAPTURE) +# define AR_DEFAULT_PIXEL_FORMAT AR_INPUT_WINDOWS_MEDIA_CAPTURE_PIXEL_FORMAT +#else +# error +#endif + +// +// If trying to minimize memory footprint, disable a few things. +// + +#if AR_ENABLE_MINIMIZE_MEMORY_FOOTPRINT +#define AR_DISABLE_THRESH_MODE_AUTO_ADAPTIVE 1 +#define AR_DISABLE_NON_CORE_FNS 1 +#define AR_DISABLE_LABELING_DEBUG_MODE 1 +#endif + +#endif // !AR_CONFIG0_H diff --git a/libs/include/AR/gsub.h b/libs/include/AR/gsub.h new file mode 100755 index 0000000..17f2215 --- /dev/null +++ b/libs/include/AR/gsub.h @@ -0,0 +1,197 @@ +/* + * gsub.h + * ARToolKit5 + * + * This file is part of ARToolKit. + * + * ARToolKit is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ARToolKit is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ARToolKit. If not, see . + * + * As a special exception, the copyright holders of this library give you + * permission to link this library with independent modules to produce an + * executable, regardless of the license terms of these independent modules, and to + * copy and distribute the resulting executable under terms of your choice, + * provided that you also meet, for each linked independent module, the terms and + * conditions of the license of that module. An independent module is a module + * which is neither derived from nor based on this library. If you modify this + * library, you may extend this exception to your version of the library, but you + * are not obligated to do so. If you do not wish to do so, delete this exception + * statement from your version. + * + * Copyright 2015 Daqri, LLC. + * Copyright 2003-2015 ARToolworks, Inc. + * + * Author(s): Hirokazu Kato + * + */ + +#ifndef AR_GSUB_H +#define AR_GSUB_H + +#ifndef __APPLE__ +# ifdef _WIN32 +# include +# endif +# include +# ifdef GL_VERSION_1_2 +# include +# endif +#else +# include +# include +#endif +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct { + int sx; + int sy; + int xsize; + int ysize; +} ARGViewport; + +typedef struct { + int clipSx; + int clipSy; + int clipWidth; + int clipHeight; +} ARGImageClip; + +typedef struct { + ARdouble nearClip; + ARdouble farClip; +} ARGClipPlane; + +typedef struct { +#ifdef AR_IOS + int imageVBOFlag; + GLuint imageVBO; + GLuint imageTBO; + GLuint imageIBO; + int texIdFlag; + GLuint texId; + int texIdYUVFlag; + GLuint texIdYUV1; + GLuint texIdYUV2; + GLuint texIdYUV3; + ARUint8 *imageUV1; + ARUint8 *imageUV2; +#else + int texId; + int listIndex; +#endif +} ARGDisplayList; + +typedef struct { + ARGViewport viewport; + ARParam *cparam; + ARGClipPlane clipPlane; + int dispMethod; + int dispMode; +#ifndef AR_IOS + int flipMode; +#endif + int distortionMode; + int pixFormat; + ARdouble scale; + ARGImageClip imageClip; + ARGDisplayList dispList; + ARGDisplayList dispListHalf; +} ARGViewportHandle; + + +#ifndef AR_IOS +typedef struct { + int winID; + int xsize; + int ysize; + int possibleTextureRectangle; + GLint maxTextureRectangleSize; +} ARGWindowHandle; +#endif + + +#ifndef AR_IOS +int argSetWindow ( ARGWindowHandle *w ); +int argInitWindowPos ( int xpos, int ypos ); +ARGWindowHandle *argCreateWindow ( int xsize, int ysize ); +ARGWindowHandle *argCreateFullWindow ( void ); +int argGetScreenSize ( int *xsize, int *ysize ); +int argSetWindowSize ( int xsize, int ysize ); +#endif +int argGetWindowSize ( int *xsize, int *ysize ); + +ARGViewportHandle *argCreateViewport ( ARGViewport *pos ); +int argDeleteViewport ( ARGViewportHandle **argVPhandle ); +int argViewportSetViewport ( ARGViewportHandle *argVPhandle, ARGViewport *viewport ); +int argViewportSetCparam ( ARGViewportHandle *argVPhandle, ARParam *cparam ); +int argViewportSetImageSize ( ARGViewportHandle *argVPhandle, int xsize, int ysize ); +int argViewportSetClipPlane ( ARGViewportHandle *argVPhandle, ARGClipPlane *clipPlane ); +int argViewportSetDispMethod ( ARGViewportHandle *argVPhandle, int dispMethod ); +int argViewportSetDispMode ( ARGViewportHandle *argVPhandle, int dispMode ); +int argViewportSetFlipMode ( ARGViewportHandle *argVPhandle, int flipMode ); +int argViewportSetDistortionMode ( ARGViewportHandle *argVPhandle, int distortionMode ); +int argViewportSetPixFormat ( ARGViewportHandle *argVPhandle, int pixFormat ); +int argViewportSetDispScale ( ARGViewportHandle *argVPhandle, ARdouble scale ); +int argViewportSetImageClip ( ARGViewportHandle *argVPhandle, ARGImageClip *imageClip ); +int argViewportSetImageClip2 ( ARGViewportHandle *argVPhandle, int *centerX, int *centerY, ARdouble *scale ); + +#ifndef AR_IOS +int argCleanup ( void ); +int argSwapBuffers ( void ); + +int argSetDispFunc ( void (*mainFunc)(void), int idleFlag ); +int argSetKeyFunc ( void (*keyFunc)(unsigned char key, int x, int y) ); +int argSetMouseFunc ( void (*mouseFunc)(int button, int state, int x, int y) ); +int argSetMotionFunc ( void (*motionFunc)(int x, int y) ); +void argMainLoop ( void ); +void argDefaultKeyFunc ( unsigned char key, int x, int y ); +#endif + +void argConvGlpara ( ARdouble para[3][4], ARdouble gl_para[16] ); +int argDrawMode2D ( ARGViewportHandle *argVPhandle ); +int argDrawMode3D ( ARGViewportHandle *argVPhandle ); +int argDrawModeHomography ( ARGViewportHandle *vp, ARdouble z ); + + +int argDrawSquareByIdealPos ( ARdouble vertIdeal[4][2] ); +int argDrawSquareByObservedPos ( ARdouble vertObserved[4][2] ); +int argDrawSquare2ByIdealPos ( ARdouble vertIdeal[4][2] ); +int argDrawSquare2ByObservedPos ( ARdouble vertObserved[4][2] ); +int argDrawLineByIdealPos ( ARdouble x1, ARdouble y1, ARdouble x2, ARdouble y2 ); +int argDrawLineByObservedPos ( ARdouble x1, ARdouble y1, ARdouble x2, ARdouble y2 ); +int argDrawPointByIdealPos ( ARdouble x, ARdouble y ); +int argDrawPointByObservedPos ( ARdouble x, ARdouble y ); +int argDrawStringsByIdealPos ( char *string, ARdouble sx, ARdouble sy ); +int argDrawStringsByObservedPos( char *string, ARdouble sx, ARdouble sy ); + +int argDrawImage ( ARUint8 *image ); +int argDrawImageHalf ( ARUint8 *image ); +int argDrawImageYUV ( ARUint8 *image, ARUint8 *imageUV); + +#ifdef AR_IOS +ARGViewportHandle *argGetCurrentVPHandle ( void ); +int argSetCurrentVPHandle ( ARGViewportHandle *vp ); +int argClearDisplayList ( ARGDisplayList *dispList ); +int argGetCurrentScale ( ARGViewportHandle *vp, ARdouble *sx, ARdouble *sy, ARdouble *offx, ARdouble *offy ); +#endif + +#ifdef __cplusplus +} +#endif +#endif diff --git a/libs/include/AR/gsubConfig.h b/libs/include/AR/gsubConfig.h new file mode 100755 index 0000000..e5cbbbe --- /dev/null +++ b/libs/include/AR/gsubConfig.h @@ -0,0 +1,82 @@ +/* + * gsubConfig.h + * ARToolKit5 + * + * This file is part of ARToolKit. + * + * ARToolKit is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ARToolKit is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ARToolKit. If not, see . + * + * As a special exception, the copyright holders of this library give you + * permission to link this library with independent modules to produce an + * executable, regardless of the license terms of these independent modules, and to + * copy and distribute the resulting executable under terms of your choice, + * provided that you also meet, for each linked independent module, the terms and + * conditions of the license of that module. An independent module is a module + * which is neither derived from nor based on this library. If you modify this + * library, you may extend this exception to your version of the library, but you + * are not obligated to do so. If you do not wish to do so, delete this exception + * statement from your version. + * + * Copyright 2015 Daqri, LLC. + * Copyright 2003-2015 ARToolworks, Inc. + * + * Author(s): Hirokazu Kato + * + */ + +#ifndef AR_GSUB_CONFIG_H +#define AR_GSUB_CONFIG_H + +/* NUM of TEXTURE MESH */ +#define AR_GL_TEXTURE_MESH_NUM 40 + +/* MIN_LINE_SEGMENT */ +#define AR_GL_MIN_LINE_SEGMENT 10 + +/* dispMethod */ +#define AR_GL_DISP_METHOD_GL_DRAW_PIXELS 0 +#define AR_GL_DISP_METHOD_TEXTURE_MAPPING_FRAME 1 +#define AR_GL_DISP_METHOD_TEXTURE_MAPPING_FIELD 2 +#define AR_GL_DEFAULT_DISP_METHOD AR_GL_DISP_METHOD_TEXTURE_MAPPING_FRAME + +/* dispMode */ +#define AR_GL_DISP_MODE_FIT_TO_VIEWPORT 0 +#define AR_GL_DISP_MODE_FIT_TO_VIEWPORT_KEEP_ASPECT_RATIO 1 +#define AR_GL_DISP_MODE_FIT_TO_VIEWPORT_HEIGHT_KEEP_ASPECT_RATIO 2 +#define AR_GL_DISP_MODE_FIT_TO_VIEWPORT_WIDTH_KEEP_ASPECT_RATIO 3 +#define AR_GL_DISP_MODE_USE_SPECIFIED_SCALE 4 +#define AR_GL_DEFAULT_DISP_MODE AR_GL_DISP_MODE_FIT_TO_VIEWPORT + +#ifndef AR_IOS +/* flipMode */ +#define AR_GL_FLIP_H 1 +#define AR_GL_FLIP_V 2 +#define AR_GL_FLIP_DISABLE 0 +#define AR_GL_DEFAULT_FLIP_MODE AR_GL_FLIP_DISABLE +#endif + +/* distortionMode */ +#define AR_GL_DISTORTION_COMPENSATE_DISABLE 0 +#define AR_GL_DISTORTION_COMPENSATE_ENABLE 1 +#define AR_GL_DEFAULT_DISTORTION_MODE AR_GL_DISTORTION_COMPENSATE_ENABLE + +/* clipPlane */ +#define AR_GL_DEFAULT_CLIP_NEAR 50.0 +#define AR_GL_DEFAULT_CLIP_FAR 5000.0 + +/* scaleLimit */ +#define AR_GL_DISP_SCALE_MAX 5.0 +#define AR_GL_DISP_SCALE_MIN 0.3 + +#endif diff --git a/libs/include/AR/gsub_es.h b/libs/include/AR/gsub_es.h new file mode 100755 index 0000000..f62f28f --- /dev/null +++ b/libs/include/AR/gsub_es.h @@ -0,0 +1,612 @@ +/* + * gsub_es.h + * ARToolKit5 + * + * Graphics Subroutines (OpenGL ES 1.1) for ARToolKit. + * + * This file is part of ARToolKit. + * + * ARToolKit is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ARToolKit is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ARToolKit. If not, see . + * + * As a special exception, the copyright holders of this library give you + * permission to link this library with independent modules to produce an + * executable, regardless of the license terms of these independent modules, and to + * copy and distribute the resulting executable under terms of your choice, + * provided that you also meet, for each linked independent module, the terms and + * conditions of the license of that module. An independent module is a module + * which is neither derived from nor based on this library. If you modify this + * library, you may extend this exception to your version of the library, but you + * are not obligated to do so. If you do not wish to do so, delete this exception + * statement from your version. + * + * Copyright 2015 Daqri, LLC. + * Copyright 2008-2015 ARToolworks, Inc. + * + * Author(s): Philip Lamb + * + * Rev Date Who Changes + * 1.0.0 2008-03-30 PRL Rewrite of gsub_lite.c from ARToolKit v4.3.2 for OpenGL ES 1.1 capabilities. + * + */ + +/*! + @header gsub_es + @abstract A collection of useful OpenGL ES 1.1 routines for ARToolKit. + @discussion + gsub_es is the preferred means for drawing camera video + images acquired from ARToolKit's video libraries. It includes + optimized texture handling, and a variety of flexible drawing + options. + + gsub_es also provides utility functions for setting the + OpenGL viewing frustum and camera position based on ARToolKit- + camera parameters and marker positions. + + gsub_es does not depend on GLUT, or indeed, any particular + window or event handling system. It is therefore well suited + to use in applications which have their own window and event + handling code. + + @copyright 2008-2013 Philip Lamb + @version 1.0.0 + */ + +#ifndef __gsub_es_h__ +#define __gsub_es_h__ + +// ============================================================================ +// Public includes. +// ============================================================================ + +#if defined ANDROID +# include +# include +#else +# include +# include +#endif + +#include +#include // ARUint8, AR_PIXEL_FORMAT +#include // ARParam, arParamDecompMat(), arParamObserv2Ideal() +#include "glStateCache.h" + +#ifdef __cplusplus +extern "C" { +#endif + +// ============================================================================ +// Public types and definitions. +// ============================================================================ + +#define ARGL_DISABLE_DISP_IMAGE 0 + +#ifndef TRUE +# define TRUE 1 +#endif +#ifndef FALSE +# define FALSE 0 +#endif + +#if !ARGL_DISABLE_DISP_IMAGE + +/*! + @typedef ARGL_CONTEXT_SETTINGS_REF + @abstract Opaque type to hold ARGL settings for a given OpenGL context. + @discussion + An OpenGL context is an implementation-defined structure which + keeps track of OpenGL state, including textures and display lists. + Typically, individual OpenGL windows will have distinct OpenGL + contexts assigned to them by the host operating system. + + As gsub_lite uses textures and display lists, it must be able to + track which OpenGL context a given texture or display list it is using + belongs to. This is especially important when gsub_lite is being used to + draw into more than one window (and therefore more than one context.) + + Basically, functions which depend on OpenGL state, will require an + ARGL_CONTEXT_SETTINGS_REF to be passed to them. An ARGL_CONTEXT_SETTINGS_REF + is generated by setting the current OpenGL context (e.g. if using GLUT, + you might call glutSetWindow()) and then calling arglSetupForCurrentContext(). + When you have finished using ARGL in a given context, you should call + arglCleanup(), passing in an ARGL_CONTEXT_SETTINGS_REF, to free the + memory used by the settings structure. + @availability First appeared in ARToolKit 2.68. + */ +typedef struct _ARGL_CONTEXT_SETTINGS *ARGL_CONTEXT_SETTINGS_REF; + +#endif + +// ============================================================================ +// Public functions. +// ============================================================================ + +/*! + @function + @abstract Create an OpenGL perspective projection matrix. + @discussion + Use this function to create a matrix suitable for passing to OpenGL + to set the viewing projection. + @param cparam Pointer to a set of ARToolKit camera parameters for the + current video source. + @param focalmax The maximum distance at which geometry will be rendered. + Any geometry further away from the camera than this distance will be clipped + and will not be appear in a rendered frame. Thus, this value should be + set high enough to avoid clipping of any geometry you care about. However, + the precision of the depth buffer is correlated with the ratio of focalmin + to focalmax, thus you should not set focalmax any higher than it needs to be. + This value should be specified in the same units as your OpenGL drawing. + @param focalmin The minimum distance at which geometry will be rendered. + Any geometry closer to the camera than this distance will be clipped + and will not be appear in a rendered frame. Thus, this value should be + set low enough to avoid clipping of any geometry you care about. However, + the precision of the depth buffer is correlated with the ratio of focalmin + to focalmax, thus you should not set focalmin any lower than it needs to be. + Additionally, geometry viewed in a stereo projections that is too close to + camera is difficult and tiring to view, so if you are rendering stereo + perspectives you should set this value no lower than the near-point of + the eyes. The near point in humans varies, but usually lies between 0.1 m + 0.3 m. This value should be specified in the same units as your OpenGL drawing. + @param m_projection Pointer to a array of 16 GLdoubles, which will be filled + out with a projection matrix suitable for passing to OpenGL. The matrix + is specified in column major order. + @availability First appeared in ARToolKit 2.68. +*/ +void arglCameraFrustumf(const ARParam *cparam, const float focalmin, const float focalmax, GLfloat m_projection[16]); + +/*! + @function + @abstract Create an OpenGL perspective projection matrix. + @discussion + Use this function to create a matrix suitable for passing to OpenGL + to set the viewing projection. + @param cparam Pointer to a set of ARToolKit camera parameters for the + current video source. + @param focalmax The maximum distance at which geometry will be rendered. + Any geometry further away from the camera than this distance will be clipped + and will not be appear in a rendered frame. Thus, this value should be + set high enough to avoid clipping of any geometry you care about. However, + the precision of the depth buffer is correlated with the ratio of focalmin + to focalmax, thus you should not set focalmax any higher than it needs to be. + This value should be specified in the same units as your OpenGL drawing. + @param focalmin The minimum distance at which geometry will be rendered. + Any geometry closer to the camera than this distance will be clipped + and will not be appear in a rendered frame. Thus, this value should be + set low enough to avoid clipping of any geometry you care about. However, + the precision of the depth buffer is correlated with the ratio of focalmin + to focalmax, thus you should not set focalmin any lower than it needs to be. + Additionally, geometry viewed in a stereo projections that is too close to + camera is difficult and tiring to view, so if you are rendering stereo + perspectives you should set this value no lower than the near-point of + he eyes. The near point in humans varies, but usually lies between 0.1 m + 0.3 m. This value should be specified in the same units as your OpenGL drawing. + @param m_projection (description) +*/ +void arglCameraFrustumRHf(const ARParam *cparam, const float focalmin, const float focalmax, GLfloat m_projection[16]); + +/*! + @function + @abstract Create an OpenGL viewing transformation matrix. + @discussion + Use this function to create a matrix suitable for passing to OpenGL + to set the viewing transformation of the virtual camera. + + The matrix is formed so that the world coordinate system is placed + at the centre of the marker, with the marker lying in the x-y plane. + The positive x axis points to the right of the marker, the positive y + axis to the bottom of the marker, and the positive z axis into the marker. + Note that this orientation, while still a right-hand coordinate system, + is oriented differentky from the usual sense for OpenGL graphics, and + if drawing with OpenGL, you might wish to use arglCameraFrustumRHf() instead. + @param para Pointer to 3x4 matrix array of doubles which specify the + position of an ARToolKit marker, as returned by arGetTransMat(). + @param m_modelview Pointer to a array of 16 GLdoubles, which will be filled + out with a modelview matrix suitable for passing to OpenGL. The matrix + is specified in column major order. + @param scale Specifies a scaling between ARToolKit's + units (usually millimeters) and OpenGL's coordinate system units. + What you pass for the scalefactor parameter depends on what units you + want to do your OpenGL drawing in. If you use a scalefactor of 1.0, then + 1.0 OpenGL unit will equal 1.0 millimetre (ARToolKit's default units). + To use different OpenGL units, e.g. metres, then you would pass 0.001. + @availability First appeared in ARToolKit 2.68. +*/ +void arglCameraViewf(float para[3][4], GLfloat m_modelview[16], const float scale); + +/*! + @function + @abstract Create an OpenGL viewing transformation matrix. + @discussion + Use this function to create a matrix suitable for passing to OpenGL + to set the viewing transformation of the virtual camera. + + The matrix is formed so that the world coordinate system is placed + at the centre of the marker, with the marker lying in the x-y plane. + The positive x axis points to the right of the marker, the positive y + axis to the top of the marker, and the positive z axis out of the marker. + This is a right-hand coordinate system with the usual sense for OpenGL + graphics. + @param para Pointer to 3x4 matrix array of doubles which specify the + position of an ARToolKit marker, as returned by arGetTransMat(). + @param m_modelview Pointer to a array of 16 GLdoubles, which will be filled + out with a modelview matrix suitable for passing to OpenGL. The matrix + is specified in column major order. + @param scale Specifies a scaling between ARToolKit's + units (usually millimeters) and OpenGL's coordinate system units. + What you pass for the scalefactor parameter depends on what units you + want to do your OpenGL drawing in. If you use a scalefactor of 1.0, then + 1.0 OpenGL unit will equal 1.0 millimetre (ARToolKit's default units). + To use different OpenGL units, e.g. metres, then you would pass 0.001. +*/ +void arglCameraViewRHf(float para[3][4], GLfloat m_modelview[16], const float scale); + +#if !ARGL_DISABLE_DISP_IMAGE + +/*! + @function + @abstract Initialise the gsub_lite library for the current OpenGL context. + @discussion + This function performs required setup of the gsub_lite library + for the current OpenGL context and must be called before any other argl*() + functions are called for this context. + + An OpenGL context holds all of the state of the OpenGL machine, including + textures and display lists etc. There will usually be one OpenGL context + for each window displaying OpenGL content. + + Other argl*() functions whose operation depends on OpenGL state will + require an ARGL_CONTEXT_SETTINGS_REF. This is just so that + they can keep track of per-context variables. + + You should call arglCleanup() passing in the ARGL_CONTEXT_SETTINGS_REF + when you have finished with the library for this context. + @param cparam Pointer to a set of ARToolKit camera parameters for the + current video source. The size of the source image is taken from the + fields xsize and ysize of the ARParam structure pointed to. Also, when + the draw mode is AR_DRAW_BY_TEXTURE_MAPPING (see the documentation for + the global variable arglDrawMode) the field dist_factor of the ARParam + structure pointed to will be taken as the amount to un-warp the supplied + image. + + Prior to ARToolKit v5.0.5, the ARParam structure pointed to had to remain + valid in memory for the duration of the ARGL_CONTEXT_SETTINGS_REF's usage. + As of ARToolKit v5.0.5, the ARParam structure pointed to is copied, and + no longer need be maintained. + @param pixelFormat The type and format of pixels of the images to be drawn by the + gsub library. This value can be changed later by using arglPixelFormatSet() + @result An ARGL_CONTEXT_SETTINGS_REF. See the documentation for this type for more info. + @availability First appeared in ARToolKit 2.68. +*/ +ARGL_CONTEXT_SETTINGS_REF arglSetupForCurrentContext(ARParam *cparam, AR_PIXEL_FORMAT pixelFormat); + +/*! + @function + @abstract Free memory used by gsub_lite associated with the specified context. + @discussion + Should be called after no more argl* functions are needed, in order + to prevent memory leaks etc. + + The library can be setup again for the context at a later time by calling + arglSetupForCurrentContext() again. + @param contextSettings A reference to ARGL's settings for an OpenGL + context, as returned by arglSetupForCurrentContext(). + @availability First appeared in ARToolKit 2.68. +*/ +void arglCleanup(ARGL_CONTEXT_SETTINGS_REF contextSettings); + +/*! + @function + @abstract Display an ARVideo image, by drawing it using OpenGL. + @discussion + This function draws an image from an ARVideo source to the current + OpenGL context. This operation is most useful in video see-through + augmented reality applications for drawing the camera view as a + background image, but can also be used in other ways. + + An undistorted image is drawn with the lower-left corner of the + bottom-left-most pixel at OpenGL screen coordinates (0,0), and the + upper-right corner of the top-right-most pixel at OpenGL screen + coodinates (x * zoom, y * zoom), where x and y are the values of the + fields cparam->xsize and cparam->ysize (see below) and zoom is the + value of the parameter zoom (also see below). If cparam->dist_factor + indicates that an un-warping correction should be applied, the actual + coordinates will differ from the values specified here. + + OpenGL state: Drawing is performed with depth testing and lighting + disabled, and thus leaves the the depth buffer (if any) unmodified. If + pixel transfer is by texturing (see documentation for arglDrawMode), + the drawing is done in replacement texture environment mode. + The depth test enable and lighting enable state and the texture + environment mode are restored before the function returns. + @param contextSettings A reference to ARGL's settings for the current OpenGL + context, as returned by arglSetupForCurrentContext() for this context. It + is the callers responsibility to make sure that the current context at the + time arglDisplayImage() is called matches that under which contextSettings + was created. + @availability First appeared in ARToolKit 2.68. +*/ +void arglDispImage(ARGL_CONTEXT_SETTINGS_REF contextSettings); + +/*! + @function + @abstract Display an ARVideo image, by drawing it using OpenGL, using and modifying current OpenGL state. + @discussion + This function is identical to arglDispImage except that whereas + arglDispImage sets an orthographic 2D projection and the OpenGL state + prior to drawing, this function does not. It also does not restore any + changes made to OpenGL state. + + This allows you to do effects with your image, other than just drawing it + 2D and with the lower-left corner of the bottom-left-most pixel attached + to the bottom-left (0,0) of the window. For example, you might use a + perspective projection instead of an orthographic projection with a + glLoadIdentity() / glTranslate() on the modelview matrix to place the + lower-left corner of the bottom-left-most pixel somewhere other than 0,0 + and leave depth-testing enabled. + + See the documentation for arglDispImage() for more information. + @availability First appeared in ARToolKit 2.68.2. + */ +void arglDispImageStateful(ARGL_CONTEXT_SETTINGS_REF contextSettings); + +/*! + @function + @abstract Set compensation for camera lens distortion in arglDispImage to off or on. + @discussion + By default, arglDispImage compensates for the distortion of the camera's + acquired image caused by the lens when it draws. By calling this function + with enabled = FALSE, this compensation will be disabled in the specified + drawing context. It may be re-enabled at any time. + This function is useful if you need to draw an image, but do not know the + extent of the camera's lens distortion (such as during distortion calibration). + While distortion compensation is disabled, the dist_factor[] array in a + the camera cparam structure passed to arglDispImage is ignored. + @param contextSettings A reference to ARGL's settings for the current OpenGL + context, as returned by arglSetupForCurrentContext() for this context. + @param enable TRUE to enabled distortion compensation, FALSE to disable it. + The default state for new contexts is enable = TRUE. + @result TRUE if the distortion value was set, FALSE if an error occurred. + @availability First appeared in ARToolKit 2.71. +*/ +char arglDistortionCompensationSet(ARGL_CONTEXT_SETTINGS_REF contextSettings, char enable); + +/*! + @function + @abstract Enquire as to the enable state of camera lens distortion compensation in arglDispImage. + @discussion + By default, arglDispImage compensates for the distortion of the camera's + acquired image caused by the lens when it draws. This function enquires + as to whether arglDispImage is currently doing compensation or not. + @param contextSettings A reference to ARGL's settings for the current OpenGL + context, as returned by arglSetupForCurrentContext() for this context. + @param enable Pointer to an integer value which will be set to TRUE if distortion + compensation is enabled in the specified context, or FALSE if it is disabled. + @result TRUE if the distortion value was retreived, FALSE if an error occurred. + @availability First appeared in ARToolKit 2.71. + */ +char arglDistortionCompensationGet(ARGL_CONTEXT_SETTINGS_REF contextSettings, char *enable); + +/*! + @function + @abstract Set the current video image drawing scalefactor. + @param zoom The amount to scale the video image up or down. To draw the video + image double size, use a zoom value of 2.0. To draw the video image + half size use a zoom value of 0.5. + */ +char arglSetPixelZoom(ARGL_CONTEXT_SETTINGS_REF contextSettings, float zoom); + +/*! + @function + @abstract Retrieve the current video image drawing scalefactor. + @param zoom The amount to scale the video image up or down. To draw the video + image double size, use a zoom value of 2.0. To draw the video image + half size use a zoom value of 0.5. + */ +char arglGetPixelZoom(ARGL_CONTEXT_SETTINGS_REF contextSettings, float *zoom); + +/*! + @function + @abstract Set the format of pixel data which will be passed to arglDispImage*() + @discussion (description) + In gsub_lite, the format of the pixels (i.e. the arrangement of components + within each pixel) can be changed at runtime. Use this function to inform + gsub_lite the format the pixels being passed to arglDispImage*() functions + are in. This setting applies only to the context passed in parameter + contextSettings. The default format is determined by + the value of AR_DEFAULT_PIXEL_FORMAT at the time the library was built. + Usually, image data is passed in directly from images generated by ARVideo, + and so you should ensure that ARVideo is generating pixels of the same format. + @param contextSettings A reference to ARGL's settings for the current OpenGL + context, as returned by arglSetupForCurrentContext() for this context. + @param format A symbolic constant for the pixel format being set. See + AR_PIXEL_FORMAT in ar.h for a list of all possible formats. + @result TRUE if the pixel format value was set, FALSE if an error occurred. + @availability First appeared in ARToolKit 2.71. +*/ +char arglPixelFormatSet(ARGL_CONTEXT_SETTINGS_REF contextSettings, AR_PIXEL_FORMAT format); + +/*! + @function + @abstract Get the format of pixel data in which arglDispImage*() is expecting data to be passed. + @discussion This function enquires as to the current format of pixel data being + expected by the arglDispImage*() functions. The default format is determined by + the value of AR_DEFAULT_PIXEL_FORMAT at the time the library was built. + @param contextSettings A reference to ARGL's settings for the current OpenGL + context, as returned by arglSetupForCurrentContext() for this context. + @param format A symbolic constant for the pixel format in use. See + AR_PIXEL_FORMAT in ar.h for a list of all possible formats. + @param size The number of bytes of memory occupied per pixel, for the given format. + @result TRUE if the pixel format and size values were retreived, FALSE if an error occurred. + @availability First appeared in ARToolKit 2.71. +*/ +char arglPixelFormatGet(ARGL_CONTEXT_SETTINGS_REF contextSettings, AR_PIXEL_FORMAT *format, int *size); + +/*! + @function + @abstract Find out whether ARGL is rotating all OpenGL drawing by 90 degrees. + @discussion + On some OpenGL ES devices, it may be desirable to rotate all OpenGL drawing by 90 + degrees in the window coordinate system, in order to swap the horizontal and + vertical axes of the device. This may be a higher performance solution than + manually swapping rows and columns of submitted data. + + This function queries the current state of whether such a rotation is being performed by ARGL or not. + @param contextSettings A reference to ARGL's settings for the current OpenGL + context, as returned by arglSetupForCurrentContext() for this context. + @result TRUE if a 90 degree rotation is enabled, FALSE if it is disabled. +*/ +char arglGetRotate90(ARGL_CONTEXT_SETTINGS_REF contextSettings); + +/*! + @function + @abstract Set or unset a 90 degree rotation in all OpenGL drawing performed by ARGL. + @discussion + On some OpenGL ES devices, it may be desirable to rotate all OpenGL drawing by 90 + degrees in the window coordinate system, in order to swap the horizontal and + vertical axes of the device. This may be a higher performance solution than + manually swapping rows and columns of submitted data. + + This function enables or disables such an axis swap in ARGL with very little + performance cost, by introducing a 90-degree rotation into the OpenGL projection matrix. + + By default, 90 degree rotation is DISABLED. + @param contextSettings A reference to ARGL's settings for the current OpenGL. + context, as returned by arglSetupForCurrentContext() for this context. + @param rotate90 Set to TRUE or 1 to enable 90 degree rotation, FALSE to disable. +*/ +void arglSetRotate90(ARGL_CONTEXT_SETTINGS_REF contextSettings, char rotate90); + +char arglGetFlipH(ARGL_CONTEXT_SETTINGS_REF contextSettings); +void arglSetFlipH(ARGL_CONTEXT_SETTINGS_REF contextSettings, char flipH); +char arglGetFlipV(ARGL_CONTEXT_SETTINGS_REF contextSettings); +void arglSetFlipV(ARGL_CONTEXT_SETTINGS_REF contextSettings, char flipV); + +/*! + @function + @abstract Specify a desired pixel buffer size larger than the camera image size. + @discussion + By default, the pixel buffer accepted by function arglPixelBufferDataUpload() + is assumed to be tightly packed, row-major array of dimensions + equal to the calibrated camera image size (as passed in the fields arParam.xsize and arParam.ysize + of the ARHandle submitted to arglSetupForCurrentContext(). + + The pixel data buffer submitted may, under some circumstances be allowed to be larger than the + values of the calibrated camera image size (i.e. padded). This may only occur when the + underlying OpenGL ES impementation does not support non-power-of-two textures. For the Apple + iPhone family, this applies to the iPhone, the iPhone 3G, the iPod Touch 1st and 2nd Generation. + The iPhone 3GS and the iPod Touch 3rd Generation support non-power-of-two textures, and thus + padding of the pixel data buffer is not supported on these devices. If padding is desired, + the desired buffer size must be submitted using this function. Check that the + result from this function is TRUE before attempting to upload such a padded buffer. + @param contextSettings A reference to ARGL's settings for the current OpenGL + context, as returned by arglSetupForCurrentContext() for this context. + @param bufWidth The desired buffer width, in pixels. + @param bufHeight The desired buffer height, in pixels. + @result TRUE if the desired buffer size is supported, FALSE otherwise. +*/ +char arglPixelBufferSizeSet(ARGL_CONTEXT_SETTINGS_REF contextSettings, int bufWidth, int bufHeight); + +/*! + @function + @abstract Query the size of pixel data buffers expected by arglPixelBufferDataUpload(). + @discussion + See function arglPixelBufferSizeSet() for a full discussion. + @param contextSettings A reference to ARGL's settings for the current OpenGL + context, as returned by arglSetupForCurrentContext() for this context. + @param bufWidth A pointer to int, which will be filled out with the buffer width, in pixels, or NULL if this value is not required. + @param bufHeight A pointer to int, which will be filled out with the buffer height, in pixels, or NULL if this value is not required.. + @result TRUE if the buffer size was successfully queried, FALSE otherwise. + */ +char arglPixelBufferSizeGet(ARGL_CONTEXT_SETTINGS_REF contextSettings, int *bufWidth, int *bufHeight); + +/*! + @function + @abstract Upload a buffer of pixel data to an OpenGL texture for later use by arglDispImage(). + @discussion + ARGL provides the ability to perform distortion-compensated texturing of a camera video image + into the OpenGL context, for the purpose of video-see through augmented reality. This function + uploads the camera image data to an OpenGL texture, ready for later drawing using the function + arglDispImage(). + @param contextSettings A reference to ARGL's settings for the current OpenGL + context, as returned by arglSetupForCurrentContext() for this context. + @param bufDataPtr0 A pointer to the pixel buffer, which is a block of memory from which texture + data will be read. + + The layout of pixel data in the memory pointed to by bufDataPtr is assumed to be + specified by the value of pixelFormat in the ARHandle submitted to arglSetupForCurrentContext(), + but can be changed by calling arglPixelFormatSet() and/or arglPixelBufferSizeSet(). + + By default, the pixel buffer is assumed to be tightly packed, row-major array of dimensions + equal to the calibrated camera image size (as passed in the fields arParam.xsize and arParam.ysize + of the ARHandle submitted to arglSetupForCurrentContext(). + + The pixel data buffer submitted may, under some circumstances be allowed to be larger than the + values of the calibrated camera image size (i.e. padded). See the discussion section of the + documentation for function arglPixelBufferSizeSet() for more information. + + This may only occur when the + underlying OpenGL ES impementation does not support non-power-of-two textures. For the Apple + iPhone family, this applies to the iPhone, the iPhone 3G, the iPod Touch 1st and 2nd Generation. + The iPhone 3GS and the iPod Touch 3rd Generation support non-power-of-two textures, and thus + padding of the pixel data buffer is not supported on these devices. If padding is desired, + the desired buffer size must be submitted using arglPixelBufferSizeSet(). Check that the + result from this function is TRUE before attempting to upload such a padded buffer. + @param bufDataPtr1 NULL for single-plane (interleaved) textures, otherwise for bi-planar textures, + a pointer to the pixel buffer, which is a block of memory from which texture + data will be read for the second plane containing the CbCr components. This plane must have + dimensions of half the size of plane 0, and 2-bytes per pixel (1 byte Cb, 1 byte Cr). + @result TRUE if the pixel buffer was successfully uploaded to OpenGL, FALSE otherwise. +*/ +char arglPixelBufferDataUploadBiPlanar(ARGL_CONTEXT_SETTINGS_REF contextSettings, ARUint8 *bufDataPtr0, ARUint8 *bufDataPtr1); +#define arglPixelBufferDataUpload(contextSettings,bufDataPtr) arglPixelBufferDataUploadBiPlanar(contextSettings,bufDataPtr,NULL) + +#endif // !ARGL_DISABLE_DISP_IMAGE + +/*! + @function + @abstract Check for the availability of an OpenGL extension. + @discussion + Provides the same functionality as the gluCheckExtension() function, + since some platforms don't have GLU version 1.3 or later. + @param extName Name of the extension, e.g. "GL_EXT_texture". + @param extString The OpenGL extensions string, as returned by glGetString(GL_EXTENSIONS); + @result TRUE, if the extension is found, FALSE otherwise. +*/ +GLboolean arglGluCheckExtension(const GLubyte* extName, const GLubyte *extString); + +/*! + @function + @abstract Checks for the presence of an OpenGL capability by version or extension. + @discussion + Checks for the presence of an OpenGL capability by version or extension. + The test returns true if EITHER the OpenGL driver's OpenGL implementation + version meets or exceeds a minimum value (passed in in minVersion) OR + if an OpenGL extension identifier passed in as a character string + is non-NULL, and is found in the current driver's list of supported extensions. + @param minVersion + A binary-coded decimal (i.e. version 1.0 is represented as 0x0100) version number. + If minVersion is zero, (i.e. there is no version of OpenGL with this extension in core) + the version test will always fail, and the result will only be true if the extension + string test passes. + @param extension A string with an extension name to search the drivers extensions + string for. E.g. "GL_EXT_texture". If NULL, the extension name test will always fail, + and the result will only be true if the version number test passes. + @result TRUE If either of the tests passes, or FALSE if both fail. +*/ +int arglGLCapabilityCheck(const unsigned short minVersion, const unsigned char *extension); + +#ifdef __cplusplus +} +#endif +#endif /* !__gsub_es_h__ */ diff --git a/libs/include/AR/gsub_es2.h b/libs/include/AR/gsub_es2.h new file mode 100755 index 0000000..1ae0702 --- /dev/null +++ b/libs/include/AR/gsub_es2.h @@ -0,0 +1,615 @@ +/* + * gsub_es2.h + * ARToolKit5 + * + * Graphics Subroutines (OpenGL ES 2.x) for ARToolKit. + * + * This file is part of ARToolKit. + * + * ARToolKit is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ARToolKit is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ARToolKit. If not, see . + * + * As a special exception, the copyright holders of this library give you + * permission to link this library with independent modules to produce an + * executable, regardless of the license terms of these independent modules, and to + * copy and distribute the resulting executable under terms of your choice, + * provided that you also meet, for each linked independent module, the terms and + * conditions of the license of that module. An independent module is a module + * which is neither derived from nor based on this library. If you modify this + * library, you may extend this exception to your version of the library, but you + * are not obligated to do so. If you do not wish to do so, delete this exception + * statement from your version. + * + * Copyright 2015 Daqri, LLC. + * Copyright 2011-2015 ARToolworks, Inc. + * + * Author(s): Philip Lamb + * + */ + +/*! + @header gsub_es2 + @abstract A collection of useful OpenGL ES 2.x routines for ARToolKit. + @discussion + gsub_es2 is the preferred means for drawing camera video + images acquired from ARToolKit's video libraries. It includes + optimized texture handling, and a variety of flexible drawing + options. + + gsub_es2 also provides utility functions for setting the + OpenGL viewing frustum and camera position based on ARToolKit- + camera parameters and marker positions. + + gsub_es2 does not depend on GLUT, or indeed, any particular + window or event handling system. It is therefore well suited + to use in applications which have their own window and event + handling code. + + @copyright 2011-2013 Philip Lamb + @version 1.0.0 + */ + +#ifndef __gsub_es2_h__ +#define __gsub_es2_h__ + +// ============================================================================ +// Public includes. +// ============================================================================ + +#include // ARUint8, AR_PIXEL_FORMAT +#include // ARParam, arParamDecompMat(), arParamObserv2Ideal() +#ifndef _WINRT +# define ARGL_DISABLE_DISP_IMAGE 0 +# include "glStateCache2.h" +#else +# define ARGL_DISABLE_DISP_IMAGE 1 +typedef float GLfloat; +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +// ============================================================================ +// Public types and definitions. +// ============================================================================ + + + +#ifndef TRUE +# define TRUE 1 +#endif +#ifndef FALSE +# define FALSE 0 +#endif + +#if !ARGL_DISABLE_DISP_IMAGE + +/*! + @typedef ARGL_CONTEXT_SETTINGS_REF + @abstract Opaque type to hold ARGL settings for a given OpenGL context. + @discussion + An OpenGL context is an implementation-defined structure which + keeps track of OpenGL state, including textures and display lists. + Typically, individual OpenGL windows will have distinct OpenGL + contexts assigned to them by the host operating system. + + As gsub_lite uses textures and display lists, it must be able to + track which OpenGL context a given texture or display list it is using + belongs to. This is especially important when gsub_lite is being used to + draw into more than one window (and therefore more than one context.) + + Basically, functions which depend on OpenGL state, will require an + ARGL_CONTEXT_SETTINGS_REF to be passed to them. An ARGL_CONTEXT_SETTINGS_REF + is generated by setting the current OpenGL context (e.g. if using GLUT, + you might call glutSetWindow()) and then calling arglSetupForCurrentContext(). + When you have finished using ARGL in a given context, you should call + arglCleanup(), passing in an ARGL_CONTEXT_SETTINGS_REF, to free the + memory used by the settings structure. + @availability First appeared in ARToolKit 2.68. + */ +typedef struct _ARGL_CONTEXT_SETTINGS *ARGL_CONTEXT_SETTINGS_REF; + +#endif + +// ============================================================================ +// Public functions. +// ============================================================================ + +/*! + @function + @abstract Create an OpenGL perspective projection matrix. + @discussion + Use this function to create a matrix suitable for passing to OpenGL + to set the viewing projection. + @param cparam Pointer to a set of ARToolKit camera parameters for the + current video source. + @param focalmax The maximum distance at which geometry will be rendered. + Any geometry further away from the camera than this distance will be clipped + and will not be appear in a rendered frame. Thus, this value should be + set high enough to avoid clipping of any geometry you care about. However, + the precision of the depth buffer is correlated with the ratio of focalmin + to focalmax, thus you should not set focalmax any higher than it needs to be. + This value should be specified in the same units as your OpenGL drawing. + @param focalmin The minimum distance at which geometry will be rendered. + Any geometry closer to the camera than this distance will be clipped + and will not be appear in a rendered frame. Thus, this value should be + set low enough to avoid clipping of any geometry you care about. However, + the precision of the depth buffer is correlated with the ratio of focalmin + to focalmax, thus you should not set focalmin any lower than it needs to be. + Additionally, geometry viewed in a stereo projections that is too close to + camera is difficult and tiring to view, so if you are rendering stereo + perspectives you should set this value no lower than the near-point of + the eyes. The near point in humans varies, but usually lies between 0.1 m + 0.3 m. This value should be specified in the same units as your OpenGL drawing. + @param m_projection Pointer to a array of 16 GLdoubles, which will be filled + out with a projection matrix suitable for passing to OpenGL. The matrix + is specified in column major order. + @availability First appeared in ARToolKit 2.68. +*/ +void arglCameraFrustumf(const ARParam *cparam, const float focalmin, const float focalmax, GLfloat m_projection[16]); + +/*! + @function + @abstract Create an OpenGL perspective projection matrix. + @discussion + Use this function to create a matrix suitable for passing to OpenGL + to set the viewing projection. + @param cparam Pointer to a set of ARToolKit camera parameters for the + current video source. + @param focalmax The maximum distance at which geometry will be rendered. + Any geometry further away from the camera than this distance will be clipped + and will not be appear in a rendered frame. Thus, this value should be + set high enough to avoid clipping of any geometry you care about. However, + the precision of the depth buffer is correlated with the ratio of focalmin + to focalmax, thus you should not set focalmax any higher than it needs to be. + This value should be specified in the same units as your OpenGL drawing. + @param focalmin The minimum distance at which geometry will be rendered. + Any geometry closer to the camera than this distance will be clipped + and will not be appear in a rendered frame. Thus, this value should be + set low enough to avoid clipping of any geometry you care about. However, + the precision of the depth buffer is correlated with the ratio of focalmin + to focalmax, thus you should not set focalmin any lower than it needs to be. + Additionally, geometry viewed in a stereo projections that is too close to + camera is difficult and tiring to view, so if you are rendering stereo + perspectives you should set this value no lower than the near-point of + he eyes. The near point in humans varies, but usually lies between 0.1 m + 0.3 m. This value should be specified in the same units as your OpenGL drawing. + @param m_projection (description) +*/ +void arglCameraFrustumRHf(const ARParam *cparam, const float focalmin, const float focalmax, GLfloat m_projection[16]); + +/*! + @function + @abstract Create an OpenGL viewing transformation matrix. + @discussion + Use this function to create a matrix suitable for passing to OpenGL + to set the viewing transformation of the virtual camera. + + The matrix is formed so that the world coordinate system is placed + at the centre of the marker, with the marker lying in the x-y plane. + The positive x axis points to the right of the marker, the positive y + axis to the bottom of the marker, and the positive z axis into the marker. + Note that this orientation, while still a right-hand coordinate system, + is oriented differentky from the usual sense for OpenGL graphics, and + if drawing with OpenGL, you might wish to use arglCameraFrustumRHf() instead. + @param para Pointer to 3x4 matrix array of doubles which specify the + position of an ARToolKit marker, as returned by arGetTransMat(). + @param m_modelview Pointer to a array of 16 GLdoubles, which will be filled + out with a modelview matrix suitable for passing to OpenGL. The matrix + is specified in column major order. + @param scale Specifies a scaling between ARToolKit's + units (usually millimeters) and OpenGL's coordinate system units. + What you pass for the scalefactor parameter depends on what units you + want to do your OpenGL drawing in. If you use a scalefactor of 1.0, then + 1.0 OpenGL unit will equal 1.0 millimetre (ARToolKit's default units). + To use different OpenGL units, e.g. metres, then you would pass 0.001. + @availability First appeared in ARToolKit 2.68. +*/ +void arglCameraViewf(float para[3][4], GLfloat m_modelview[16], const float scale); + +/*! + @function + @abstract Create an OpenGL viewing transformation matrix. + @discussion + Use this function to create a matrix suitable for passing to OpenGL + to set the viewing transformation of the virtual camera. + + The matrix is formed so that the world coordinate system is placed + at the centre of the marker, with the marker lying in the x-y plane. + The positive x axis points to the right of the marker, the positive y + axis to the top of the marker, and the positive z axis out of the marker. + This is a right-hand coordinate system with the usual sense for OpenGL + graphics. + @param para Pointer to 3x4 matrix array of doubles which specify the + position of an ARToolKit marker, as returned by arGetTransMat(). + @param m_modelview Pointer to a array of 16 GLdoubles, which will be filled + out with a modelview matrix suitable for passing to OpenGL. The matrix + is specified in column major order. + @param scale Specifies a scaling between ARToolKit's + units (usually millimeters) and OpenGL's coordinate system units. + What you pass for the scalefactor parameter depends on what units you + want to do your OpenGL drawing in. If you use a scalefactor of 1.0, then + 1.0 OpenGL unit will equal 1.0 millimetre (ARToolKit's default units). + To use different OpenGL units, e.g. metres, then you would pass 0.001. +*/ +void arglCameraViewRHf(float para[3][4], GLfloat m_modelview[16], const float scale); + +#if !ARGL_DISABLE_DISP_IMAGE + +/*! + @function + @abstract Initialise the gsub_lite library for the current OpenGL context. + @discussion + This function performs required setup of the gsub_lite library + for the current OpenGL context and must be called before any other argl*() + functions are called for this context. + + An OpenGL context holds all of the state of the OpenGL machine, including + textures and display lists etc. There will usually be one OpenGL context + for each window displaying OpenGL content. + + Other argl*() functions whose operation depends on OpenGL state will + require an ARGL_CONTEXT_SETTINGS_REF. This is just so that + they can keep track of per-context variables. + + You should call arglCleanup() passing in the ARGL_CONTEXT_SETTINGS_REF + when you have finished with the library for this context. + @param cparam Pointer to a set of ARToolKit camera parameters for the + current video source. The size of the source image is taken from the + fields xsize and ysize of the ARParam structure pointed to. Also, when + the draw mode is AR_DRAW_BY_TEXTURE_MAPPING (see the documentation for + the global variable arglDrawMode) the field dist_factor of the ARParam + structure pointed to will be taken as the amount to un-warp the supplied + image. + + The ARParam structure pointed to must remain valid in memory for the duration + of the ARGL_CONTEXT_SETTINGS_REF's usage. + @param pixelFormat The type and format of pixels of the images to be drawn by the + gsub library. This value can be changed later by using arglPixelFormatSet() + @result An ARGL_CONTEXT_SETTINGS_REF. See the documentation for this type for more info. + @availability First appeared in ARToolKit 2.68. +*/ +ARGL_CONTEXT_SETTINGS_REF arglSetupForCurrentContext(ARParam *cparam, AR_PIXEL_FORMAT pixelFormat); + +/*! + @function + @abstract Free memory used by gsub_lite associated with the specified context. + @discussion + Should be called after no more argl* functions are needed, in order + to prevent memory leaks etc. + + The library can be setup again for the context at a later time by calling + arglSetupForCurrentContext() again. + @param contextSettings A reference to ARGL's settings for an OpenGL + context, as returned by arglSetupForCurrentContext(). + @availability First appeared in ARToolKit 2.68. +*/ +void arglCleanup(ARGL_CONTEXT_SETTINGS_REF contextSettings); + +/*! + @function + @abstract Display an ARVideo image, by drawing it using OpenGL. + @discussion + This function draws an image from an ARVideo source to the current + OpenGL context. This operation is most useful in video see-through + augmented reality applications for drawing the camera view as a + background image, but can also be used in other ways. + + An undistorted image is drawn with the lower-left corner of the + bottom-left-most pixel at OpenGL screen coordinates (0,0), and the + upper-right corner of the top-right-most pixel at OpenGL screen + coodinates (x * zoom, y * zoom), where x and y are the values of the + fields cparam->xsize and cparam->ysize (see below) and zoom is the + value of the parameter zoom (also see below). If cparam->dist_factor + indicates that an un-warping correction should be applied, the actual + coordinates will differ from the values specified here. + + OpenGL state: Drawing is performed with depth testing and lighting + disabled, and thus leaves the the depth buffer (if any) unmodified. If + pixel transfer is by texturing (see documentation for arglDrawMode), + the drawing is done in replacement texture environment mode. + The depth test enable and lighting enable state and the texture + environment mode are restored before the function returns. + @param contextSettings A reference to ARGL's settings for the current OpenGL + context, as returned by arglSetupForCurrentContext() for this context. It + is the callers responsibility to make sure that the current context at the + time arglDisplayImage() is called matches that under which contextSettings + was created. + @availability First appeared in ARToolKit 2.68. +*/ +void arglDispImage(ARGL_CONTEXT_SETTINGS_REF contextSettings); + +/*! + @function + @abstract Display an ARVideo image, by drawing it using OpenGL, using and modifying current OpenGL state. + @discussion + This function is identical to arglDispImage except that whereas + arglDispImage sets an orthographic 2D projection and the OpenGL state + prior to drawing, this function does not. It also does not restore any + changes made to OpenGL state. + + This allows you to do effects with your image, other than just drawing it + 2D and with the lower-left corner of the bottom-left-most pixel attached + to the bottom-left (0,0) of the window. For example, you might use a + perspective projection instead of an orthographic projection with a + glLoadIdentity() / glTranslate() on the modelview matrix to place the + lower-left corner of the bottom-left-most pixel somewhere other than 0,0 + and leave depth-testing enabled. + + See the documentation for arglDispImage() for more information. + @availability First appeared in ARToolKit 2.68.2. + */ +void arglDispImageStateful(ARGL_CONTEXT_SETTINGS_REF contextSettings); + +/*! + @function + @abstract Set compensation for camera lens distortion in arglDispImage to off or on. + @discussion + By default, arglDispImage compensates for the distortion of the camera's + acquired image caused by the lens when it draws. By calling this function + with enabled = FALSE, this compensation will be disabled in the specified + drawing context. It may be re-enabled at any time. + This function is useful if you need to draw an image, but do not know the + extent of the camera's lens distortion (such as during distortion calibration). + While distortion compensation is disabled, the dist_factor[] array in a + the camera cparam structure passed to arglDispImage is ignored. + @param contextSettings A reference to ARGL's settings for the current OpenGL + context, as returned by arglSetupForCurrentContext() for this context. + @param enable TRUE to enabled distortion compensation, FALSE to disable it. + The default state for new contexts is enable = TRUE. + @result TRUE if the distortion value was set, FALSE if an error occurred. + @availability First appeared in ARToolKit 2.71. +*/ +char arglDistortionCompensationSet(ARGL_CONTEXT_SETTINGS_REF contextSettings, char enable); + +/*! + @function + @abstract Enquire as to the enable state of camera lens distortion compensation in arglDispImage. + @discussion + By default, arglDispImage compensates for the distortion of the camera's + acquired image caused by the lens when it draws. This function enquires + as to whether arglDispImage is currently doing compensation or not. + @param contextSettings A reference to ARGL's settings for the current OpenGL + context, as returned by arglSetupForCurrentContext() for this context. + @param enable Pointer to an integer value which will be set to TRUE if distortion + compensation is enabled in the specified context, or FALSE if it is disabled. + @result TRUE if the distortion value was retreived, FALSE if an error occurred. + @availability First appeared in ARToolKit 2.71. + */ +char arglDistortionCompensationGet(ARGL_CONTEXT_SETTINGS_REF contextSettings, char *enable); + +/*! + @function + @abstract Set the current video image drawing scalefactor. + @param zoom The amount to scale the video image up or down. To draw the video + image double size, use a zoom value of 2.0. To draw the video image + half size use a zoom value of 0.5. + */ +char arglSetPixelZoom(ARGL_CONTEXT_SETTINGS_REF contextSettings, float zoom); + +/*! + @function + @abstract Retrieve the current video image drawing scalefactor. + @param zoom The amount to scale the video image up or down. To draw the video + image double size, use a zoom value of 2.0. To draw the video image + half size use a zoom value of 0.5. + */ +char arglGetPixelZoom(ARGL_CONTEXT_SETTINGS_REF contextSettings, float *zoom); + +/*! + @function + @abstract Set the format of pixel data which will be passed to arglDispImage*() + @discussion (description) + In gsub_lite, the format of the pixels (i.e. the arrangement of components + within each pixel) can be changed at runtime. Use this function to inform + gsub_lite the format the pixels being passed to arglDispImage*() functions + are in. This setting applies only to the context passed in parameter + contextSettings. The default format is determined by + the value of AR_DEFAULT_PIXEL_FORMAT at the time the library was built. + Usually, image data is passed in directly from images generated by ARVideo, + and so you should ensure that ARVideo is generating pixels of the same format. + @param contextSettings A reference to ARGL's settings for the current OpenGL + context, as returned by arglSetupForCurrentContext() for this context. + @param format A symbolic constant for the pixel format being set. See + AR_PIXEL_FORMAT in ar.h for a list of all possible formats. + @result TRUE if the pixel format value was set, FALSE if an error occurred. + @availability First appeared in ARToolKit 2.71. +*/ +char arglPixelFormatSet(ARGL_CONTEXT_SETTINGS_REF contextSettings, AR_PIXEL_FORMAT format); + +/*! + @function + @abstract Get the format of pixel data in which arglDispImage*() is expecting data to be passed. + @discussion This function enquires as to the current format of pixel data being + expected by the arglDispImage*() functions. The default format is determined by + the value of AR_DEFAULT_PIXEL_FORMAT at the time the library was built. + @param contextSettings A reference to ARGL's settings for the current OpenGL + context, as returned by arglSetupForCurrentContext() for this context. + @param format A symbolic constant for the pixel format in use. See + AR_PIXEL_FORMAT in ar.h for a list of all possible formats. + @param size The number of bytes of memory occupied per pixel, for the given format. + @result TRUE if the pixel format and size values were retreived, FALSE if an error occurred. + @availability First appeared in ARToolKit 2.71. +*/ +char arglPixelFormatGet(ARGL_CONTEXT_SETTINGS_REF contextSettings, AR_PIXEL_FORMAT *format, int *size); + +/*! + @function + @abstract Find out whether ARGL is rotating all OpenGL drawing by 90 degrees. + @discussion + On some OpenGL ES devices, it may be desirable to rotate all OpenGL drawing by 90 + degrees in the window coordinate system, in order to swap the horizontal and + vertical axes of the device. This may be a higher performance solution than + manually swapping rows and columns of submitted data. + + This function queries the current state of whether such a rotation is being performed by ARGL or not. + @param contextSettings A reference to ARGL's settings for the current OpenGL + context, as returned by arglSetupForCurrentContext() for this context. + @result TRUE if a 90 degree rotation is enabled, FALSE if it is disabled. +*/ +char arglGetRotate90(ARGL_CONTEXT_SETTINGS_REF contextSettings); + +/*! + @function + @abstract Set or unset a 90 degree rotation in all OpenGL drawing performed by ARGL. + @discussion + On some OpenGL ES devices, it may be desirable to rotate all OpenGL drawing by 90 + degrees in the window coordinate system, in order to swap the horizontal and + vertical axes of the device. This may be a higher performance solution than + manually swapping rows and columns of submitted data. + + This function enables or disables such an axis swap in ARGL with very little + performance cost, by introducing a 90-degree rotation into the OpenGL projection matrix. + + By default, 90 degree rotation is DISABLED. + @param contextSettings A reference to ARGL's settings for the current OpenGL. + context, as returned by arglSetupForCurrentContext() for this context. + @param rotate90 Set to TRUE or 1 to enable 90 degree rotation, FALSE to disable. +*/ +void arglSetRotate90(ARGL_CONTEXT_SETTINGS_REF contextSettings, char rotate90); + +char arglGetFlipH(ARGL_CONTEXT_SETTINGS_REF contextSettings); +void arglSetFlipH(ARGL_CONTEXT_SETTINGS_REF contextSettings, char flipH); +char arglGetFlipV(ARGL_CONTEXT_SETTINGS_REF contextSettings); +void arglSetFlipV(ARGL_CONTEXT_SETTINGS_REF contextSettings, char flipV); + +/*! + @function + @abstract Specify a desired pixel buffer size larger than the camera image size. + @discussion + By default, the pixel buffer accepted by function arglPixelBufferDataUpload() + is assumed to be tightly packed, row-major array of dimensions + equal to the calibrated camera image size (as passed in the fields arParam.xsize and arParam.ysize + of the ARHandle submitted to arglSetupForCurrentContext(). + + The pixel data buffer submitted may, under some circumstances be allowed to be larger than the + values of the calibrated camera image size (i.e. padded). This may only occur when the + underlying OpenGL ES impementation does not support non-power-of-two textures. For the Apple + iPhone family, this applies to the iPhone, the iPhone 3G, the iPod Touch 1st and 2nd Generation. + The iPhone 3GS and the iPod Touch 3rd Generation support non-power-of-two textures, and thus + padding of the pixel data buffer is not supported on these devices. If padding is desired, + the desired buffer size must be submitted using this function. Check that the + result from this function is TRUE before attempting to upload such a padded buffer. + @param contextSettings A reference to ARGL's settings for the current OpenGL + context, as returned by arglSetupForCurrentContext() for this context. + @param bufWidth The desired buffer width, in pixels. + @param bufHeight The desired buffer height, in pixels. + @result TRUE if the desired buffer size is supported, FALSE otherwise. +*/ +char arglPixelBufferSizeSet(ARGL_CONTEXT_SETTINGS_REF contextSettings, int bufWidth, int bufHeight); + +/*! + @function + @abstract Query the size of pixel data buffers expected by arglPixelBufferDataUpload(). + @discussion + See function arglPixelBufferSizeSet() for a full discussion. + @param contextSettings A reference to ARGL's settings for the current OpenGL + context, as returned by arglSetupForCurrentContext() for this context. + @param bufWidth A pointer to int, which will be filled out with the buffer width, in pixels, or NULL if this value is not required. + @param bufHeight A pointer to int, which will be filled out with the buffer height, in pixels, or NULL if this value is not required.. + @result TRUE if the buffer size was successfully queried, FALSE otherwise. + */ +char arglPixelBufferSizeGet(ARGL_CONTEXT_SETTINGS_REF contextSettings, int *bufWidth, int *bufHeight); + +/*! + @function + @abstract Upload a buffer of pixel data to an OpenGL texture for later use by arglDispImage(). + @discussion + ARGL provides the ability to perform distortion-compensated texturing of a camera video image + into the OpenGL context, for the purpose of video-see through augmented reality. This function + uploads the camera image data to an OpenGL texture, ready for later drawing using the function + arglDispImage(). + @param contextSettings A reference to ARGL's settings for the current OpenGL + context, as returned by arglSetupForCurrentContext() for this context. + @param bufDataPtr0 A pointer to the pixel buffer, which is a block of memory from which texture + data will be read. + + The layout of pixel data in the memory pointed to by bufDataPtr is assumed to be + specified by the value of pixelFormat in the ARHandle submitted to arglSetupForCurrentContext(), + but can be changed by calling arglPixelFormatSet() and/or arglPixelBufferSizeSet(). + + By default, the pixel buffer is assumed to be tightly packed, row-major array of dimensions + equal to the calibrated camera image size (as passed in the fields arParam.xsize and arParam.ysize + of the ARHandle submitted to arglSetupForCurrentContext(). + + The pixel data buffer submitted may, under some circumstances be allowed to be larger than the + values of the calibrated camera image size (i.e. padded). See the discussion section of the + documentation for function arglPixelBufferSizeSet() for more information. + + This may only occur when the + underlying OpenGL ES impementation does not support non-power-of-two textures. For the Apple + iPhone family, this applies to the iPhone, the iPhone 3G, the iPod Touch 1st and 2nd Generation. + The iPhone 3GS and the iPod Touch 3rd Generation support non-power-of-two textures, and thus + padding of the pixel data buffer is not supported on these devices. If padding is desired, + the desired buffer size must be submitted using arglPixelBufferSizeSet(). Check that the + result from this function is TRUE before attempting to upload such a padded buffer. + @param bufDataPtr1 NULL for single-plane (interleaved) textures, otherwise for bi-planar textures, + a pointer to the pixel buffer, which is a block of memory from which texture + data will be read for the second plane containing the CbCr components. This plane must have + dimensions of half the size of plane 0, and 2-bytes per pixel (1 byte Cb, 1 byte Cr). + @result TRUE if the pixel buffer was successfully uploaded to OpenGL, FALSE otherwise. +*/ +char arglPixelBufferDataUploadBiPlanar(ARGL_CONTEXT_SETTINGS_REF contextSettings, ARUint8 *bufDataPtr0, ARUint8 *bufDataPtr1); +#define arglPixelBufferDataUpload(contextSettings,bufDataPtr) arglPixelBufferDataUploadBiPlanar(contextSettings,bufDataPtr,NULL) + +#endif // !ARGL_DISABLE_DISP_IMAGE + +#ifndef _WINRT + +/*! + @function + @abstract Check for the availability of an OpenGL extension. + @discussion + Provides the same functionality as the gluCheckExtension() function, + since some platforms don't have GLU version 1.3 or later. + @param extName Name of the extension, e.g. "GL_EXT_texture". + @param extString The OpenGL extensions string, as returned by glGetString(GL_EXTENSIONS); + @result TRUE, if the extension is found, FALSE otherwise. +*/ +GLboolean arglGluCheckExtension(const GLubyte* extName, const GLubyte *extString); + +/*! + @function + @abstract Checks for the presence of an OpenGL capability by version or extension. + @discussion + Checks for the presence of an OpenGL capability by version or extension. + The test returns true if EITHER the OpenGL driver's OpenGL implementation + version meets or exceeds a minimum value (passed in in minVersion) OR + if an OpenGL extension identifier passed in as a character string + is non-NULL, and is found in the current driver's list of supported extensions. + @param minVersion + A binary-coded decimal (i.e. version 1.0 is represented as 0x0100) version number. + If minVersion is zero, (i.e. there is no version of OpenGL with this extension in core) + the version test will always fail, and the result will only be true if the extension + string test passes. + @param extension A string with an extension name to search the drivers extensions + string for. E.g. "GL_EXT_texture". If NULL, the extension name test will always fail, + and the result will only be true if the version number test passes. + @result TRUE If either of the tests passes, or FALSE if both fail. +*/ +int arglGLCapabilityCheck(const unsigned short minVersion, const unsigned char *extension); + +/* Shader Utilities */ +GLint arglGLCompileShaderFromFile(GLuint *shader, GLenum type, const char *pathname); +GLint arglGLCompileShaderFromString(GLuint *shader, GLenum type, const char *s); +GLint arglGLLinkProgram(GLuint prog); +GLint arglGLValidateProgram(GLuint prog); +void arglGLDestroyShaders(GLuint vertShader, GLuint fragShader, GLuint prog); + +#endif // !_WINRT + +#ifdef __cplusplus +} +#endif +#endif /* !__gsub_es2_h__ */ diff --git a/libs/include/AR/gsub_lite.h b/libs/include/AR/gsub_lite.h new file mode 100755 index 0000000..72462b4 --- /dev/null +++ b/libs/include/AR/gsub_lite.h @@ -0,0 +1,631 @@ +/* + * gsub_lite.h + * ARToolKit5 + * + * Graphics Subroutines (Lite) for ARToolKit. + * + * This file is part of ARToolKit. + * + * ARToolKit is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ARToolKit is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ARToolKit. If not, see . + * + * As a special exception, the copyright holders of this library give you + * permission to link this library with independent modules to produce an + * executable, regardless of the license terms of these independent modules, and to + * copy and distribute the resulting executable under terms of your choice, + * provided that you also meet, for each linked independent module, the terms and + * conditions of the license of that module. An independent module is a module + * which is neither derived from nor based on this library. If you modify this + * library, you may extend this exception to your version of the library, but you + * are not obligated to do so. If you do not wish to do so, delete this exception + * statement from your version. + * + * Copyright 2015 Daqri, LLC. + * Copyright 2003-2015 ARToolworks, Inc. + * + * Author(s): Philip Lamb + * + */ + +/** + \file gsub_lite.h + \brief A collection of useful OpenGL routines for ARToolKit. + \cond GSUB_LITE + \htmlinclude gsub_lite/index.html +*/ + +/*! + @header gsub_lite + @abstract A collection of useful OpenGL routines for ARToolKit. + @discussion + Sample code for example usage of gsub_lite is included with + ARToolKit, in the directory <AR/examples/simpleLite>. + + gsub_lite is the preferred means for drawing camera video + images acquired from ARToolKit's video libraries. It includes + optimized texture handling, and a variety of flexible drawing + options. + + gsub_lite also provides utility functions for setting the + OpenGL viewing frustum and camera position based on ARToolKit- + camera parameters and marker positions. + + gsub_lite does not depend on GLUT, or indeed, any particular + window or event handling system. It is therefore well suited + to use in applications which have their own window and event + handling code. + + @copyright 2015 Daqri, LLC. + @version 5.2 + */ + +#ifndef __gsub_lite_h__ +#define __gsub_lite_h__ + +// ============================================================================ +// Public includes. +// ============================================================================ + +#ifdef __APPLE__ +# include +#else +# ifdef _WIN32 +# include +# endif +# include +#endif +#include // ARUint8, AR_PIXEL_FORMAT +#include // ARParam, arParamDecompMat(), arParamObserv2Ideal() + +#ifdef __cplusplus +extern "C" { +#endif + +// ============================================================================ +// Public types and definitions. +// ============================================================================ + +#define ARGL_DISABLE_DISP_IMAGE 0 + +#if !ARGL_DISABLE_DISP_IMAGE + +/*! + @typedef ARGL_CONTEXT_SETTINGS_REF + @abstract Opaque type to hold ARGL settings for a given OpenGL context. + @discussion + An OpenGL context is an implementation-defined structure which + keeps track of OpenGL state, including textures and display lists. + Typically, individual OpenGL windows will have distinct OpenGL + contexts assigned to them by the host operating system. + + As gsub_lite uses textures and display lists, it must be able to + track which OpenGL context a given texture or display list it is using + belongs to. This is especially important when gsub_lite is being used to + draw into more than one window (and therefore more than one context.) + + Basically, functions which depend on OpenGL state, will require an + ARGL_CONTEXT_SETTINGS_REF to be passed to them. An ARGL_CONTEXT_SETTINGS_REF + is generated by setting the current OpenGL context (e.g. if using GLUT, + you might call glutSetWindow()) and then calling arglSetupForCurrentContext(). + When you have finished using ARGL in a given context, you should call + arglCleanup(), passing in an ARGL_CONTEXT_SETTINGS_REF, to free the + memory used by the settings structure. + @availability First appeared in ARToolKit 2.68. + */ +typedef struct _ARGL_CONTEXT_SETTINGS *ARGL_CONTEXT_SETTINGS_REF; + +#endif + +// ============================================================================ +// Public functions. +// ============================================================================ + +/*! + @function + @abstract Create an OpenGL perspective projection matrix. + @discussion + Use this function to create a matrix suitable for passing to OpenGL + to set the viewing projection. + @param cparam Pointer to a set of ARToolKit camera parameters for the + current video source. + @param focalmax The maximum distance at which geometry will be rendered. + Any geometry further away from the camera than this distance will be clipped + and will not be appear in a rendered frame. Thus, this value should be + set high enough to avoid clipping of any geometry you care about. However, + the precision of the depth buffer is correlated with the ratio of focalmin + to focalmax, thus you should not set focalmax any higher than it needs to be. + This value should be specified in the same units as your OpenGL drawing. + @param focalmin The minimum distance at which geometry will be rendered. + Any geometry closer to the camera than this distance will be clipped + and will not be appear in a rendered frame. Thus, this value should be + set low enough to avoid clipping of any geometry you care about. However, + the precision of the depth buffer is correlated with the ratio of focalmin + to focalmax, thus you should not set focalmin any lower than it needs to be. + Additionally, geometry viewed in a stereo projections that is too close to + camera is difficult and tiring to view, so if you are rendering stereo + perspectives you should set this value no lower than the near-point of + the eyes. The near point in humans varies, but usually lies between 0.1 m + 0.3 m. This value should be specified in the same units as your OpenGL drawing. + @param m_projection Pointer to a array of 16 GLdoubles, which will be filled + out with a projection matrix suitable for passing to OpenGL. The matrix + is specified in column major order. + @availability First appeared in ARToolKit 2.68. +*/ +void arglCameraFrustum(const ARParam *cparam, const ARdouble focalmin, const ARdouble focalmax, ARdouble m_projection[16]); + +/*! + @function + @abstract Create an OpenGL perspective projection matrix. + @discussion + Use this function to create a matrix suitable for passing to OpenGL + to set the viewing projection. + @param cparam Pointer to a set of ARToolKit camera parameters for the + current video source. + @param focalmax The maximum distance at which geometry will be rendered. + Any geometry further away from the camera than this distance will be clipped + and will not be appear in a rendered frame. Thus, this value should be + set high enough to avoid clipping of any geometry you care about. However, + the precision of the depth buffer is correlated with the ratio of focalmin + to focalmax, thus you should not set focalmax any higher than it needs to be. + This value should be specified in the same units as your OpenGL drawing. + @param focalmin The minimum distance at which geometry will be rendered. + Any geometry closer to the camera than this distance will be clipped + and will not be appear in a rendered frame. Thus, this value should be + set low enough to avoid clipping of any geometry you care about. However, + the precision of the depth buffer is correlated with the ratio of focalmin + to focalmax, thus you should not set focalmin any lower than it needs to be. + Additionally, geometry viewed in a stereo projections that is too close to + camera is difficult and tiring to view, so if you are rendering stereo + perspectives you should set this value no lower than the near-point of + he eyes. The near point in humans varies, but usually lies between 0.1 m + 0.3 m. This value should be specified in the same units as your OpenGL drawing. + @param m_projection (description) +*/ +void arglCameraFrustumRH(const ARParam *cparam, const ARdouble focalmin, const ARdouble focalmax, ARdouble m_projection[16]); + +/*! + @function + @abstract Create an OpenGL viewing transformation matrix. + @discussion + Use this function to create a matrix suitable for passing to OpenGL + to set the viewing transformation of the virtual camera. + + The matrix is formed so that the world coordinate system is placed + at the centre of the marker, with the marker lying in the x-y plane. + The positive x axis points to the right of the marker, the positive y + axis to the bottom of the marker, and the positive z axis into the marker. + Note that this orientation, while still a right-hand coordinate system, + is oriented differentky from the usual sense for OpenGL graphics, and + if drawing with OpenGL, you might wish to use arglCameraFrustumRHf() instead. + @param para Pointer to 3x4 matrix array of doubles which specify the + position of an ARToolKit marker, as returned by arGetTransMat(). + @param m_modelview Pointer to a array of 16 GLdoubles, which will be filled + out with a modelview matrix suitable for passing to OpenGL. The matrix + is specified in column major order. + @param scale Specifies a scaling between ARToolKit's + units (usually millimeters) and OpenGL's coordinate system units. + What you pass for the scalefactor parameter depends on what units you + want to do your OpenGL drawing in. If you use a scalefactor of 1.0, then + 1.0 OpenGL unit will equal 1.0 millimetre (ARToolKit's default units). + To use different OpenGL units, e.g. metres, then you would pass 0.001. + @availability First appeared in ARToolKit 2.68. +*/ +void arglCameraView(const ARdouble para[3][4], ARdouble m_modelview[16], const ARdouble scale); + +/*! + @function + @abstract Create an OpenGL viewing transformation matrix. + @discussion + Use this function to create a matrix suitable for passing to OpenGL + to set the viewing transformation of the virtual camera. + + The matrix is formed so that the world coordinate system is placed + at the centre of the marker, with the marker lying in the x-y plane. + The positive x axis points to the right of the marker, the positive y + axis to the top of the marker, and the positive z axis out of the marker. + This is a right-hand coordinate system with the usual sense for OpenGL + graphics. + @param para Pointer to 3x4 matrix array of doubles which specify the + position of an ARToolKit marker, as returned by arGetTransMat(). + @param m_modelview Pointer to a array of 16 GLdoubles, which will be filled + out with a modelview matrix suitable for passing to OpenGL. The matrix + is specified in column major order. + @param scale Specifies a scaling between ARToolKit's + units (usually millimeters) and OpenGL's coordinate system units. + What you pass for the scalefactor parameter depends on what units you + want to do your OpenGL drawing in. If you use a scalefactor of 1.0, then + 1.0 OpenGL unit will equal 1.0 millimetre (ARToolKit's default units). + To use different OpenGL units, e.g. metres, then you would pass 0.001. +*/ +void arglCameraViewRH(const ARdouble para[3][4], ARdouble m_modelview[16], const ARdouble scale); + +#if !ARGL_DISABLE_DISP_IMAGE + +/*! + @function + @abstract Initialise the gsub_lite library for the current OpenGL context. + @discussion + This function performs required setup of the gsub_lite library + for the current OpenGL context and must be called before any other argl*() + functions are called for this context. + + An OpenGL context holds all of the state of the OpenGL machine, including + textures and display lists etc. There will usually be one OpenGL context + for each window displaying OpenGL content. + + Other argl*() functions whose operation depends on OpenGL state will + require an ARGL_CONTEXT_SETTINGS_REF. This is just so that + they can keep track of per-context variables. + + You should call arglCleanup() passing in the ARGL_CONTEXT_SETTINGS_REF + when you have finished with the library for this context. + @param cparam Pointer to a set of ARToolKit camera parameters for the + current video source. The size of the source image is taken from the + fields xsize and ysize of the ARParam structure pointed to. Also, when + the draw mode is AR_DRAW_BY_TEXTURE_MAPPING (see the documentation for + the global variable arglDrawMode) the field dist_factor of the ARParam + structure pointed to will be taken as the amount to un-warp the supplied + image. + + Prior to ARToolKit v5.1.5, the ARParam structure pointed to had to remain + valid in memory for the duration of the ARGL_CONTEXT_SETTINGS_REF's usage. + As of ARToolKit v5.1.5, the ARParam structure pointed to is copied, and + no longer need be maintained. + @param pixelFormat The type and format of pixels of the images to be drawn by the + gsub library. This value can be changed later by using arglPixelFormatSet() + @result An ARGL_CONTEXT_SETTINGS_REF. See the documentation for this type for more info. + @availability First appeared in ARToolKit 2.68. +*/ +ARGL_CONTEXT_SETTINGS_REF arglSetupForCurrentContext(ARParam *cparam, AR_PIXEL_FORMAT pixelFormat); + +/*! + @function + @abstract Provide an ARHandle structure from which to extract information about debug mode. + @discussion + This provides support for the debug mode in libAR. If gsub_lite has been compiled + with debug mode support, the passed in ARHandle is used as the source + of whether debug mode is enabled or disabled. If enabled, the binarized + debug image will be drawn instead of the input image. + @param arHandle A pointer to an ARHandle structure from which to extract debug info, + or NULL if debug functionality is not required. Default is NULL. + @result TRUE if the mode was set, FALSE if an error occurred. + @availability First appeared in ARToolKit 4.5.12. + @seealso arglPixelBufferDataUpload arglPixelBufferDataUpload +*/ +int arglSetupDebugMode(ARGL_CONTEXT_SETTINGS_REF contextSettings, ARHandle *arHandle); + + +/*! + @function + @abstract Free memory used by gsub_lite associated with the specified context. + @discussion + Should be called after no more argl* functions are needed, in order + to prevent memory leaks etc. + + The library can be setup again for the context at a later time by calling + arglSetupForCurrentContext() again. + @param contextSettings A reference to ARGL's settings for an OpenGL + context, as returned by arglSetupForCurrentContext(). + @availability First appeared in ARToolKit 2.68. +*/ +void arglCleanup(ARGL_CONTEXT_SETTINGS_REF contextSettings); + +/*! + @function + @abstract Display an ARVideo image, by drawing it using OpenGL. + @discussion + This function draws an image from an ARVideo source to the current + OpenGL context. This operation is most useful in video see-through + augmented reality applications for drawing the camera view as a + background image, but can also be used in other ways. + + An undistorted image is drawn with the lower-left corner of the + bottom-left-most pixel at OpenGL screen coordinates (0,0), and the + upper-right corner of the top-right-most pixel at OpenGL screen + coodinates (x * zoom, y * zoom), where x and y are the values of the + fields cparam->xsize and cparam->ysize (see below) and zoom is the + value of the parameter zoom (also see below). If cparam->dist_factor + indicates that an un-warping correction should be applied, the actual + coordinates will differ from the values specified here. + + OpenGL state: Drawing is performed with depth testing and lighting + disabled, and thus leaves the the depth buffer (if any) unmodified. If + pixel transfer is by texturing (see documentation for arglDrawMode), + the drawing is done in replacement texture environment mode. + The depth test enable and lighting enable state and the texture + environment mode are restored before the function returns. + @param contextSettings A reference to ARGL's settings for the current OpenGL + context, as returned by arglSetupForCurrentContext() for this context. It + is the callers responsibility to make sure that the current context at the + time arglDisplayImage() is called matches that under which contextSettings + was created. + @availability First appeared in ARToolKit 2.68. +*/ +void arglDispImage(ARGL_CONTEXT_SETTINGS_REF contextSettings); + +/*! + @function + @abstract Display an ARVideo image, by drawing it using OpenGL, using and modifying current OpenGL state. + @discussion + This function is identical to arglDispImage except that whereas + arglDispImage sets an orthographic 2D projection and the OpenGL state + prior to drawing, this function does not. It also does not restore any + changes made to OpenGL state. + + This allows you to do effects with your image, other than just drawing it + 2D and with the lower-left corner of the bottom-left-most pixel attached + to the bottom-left (0,0) of the window. For example, you might use a + perspective projection instead of an orthographic projection with a + glLoadIdentity() / glTranslate() on the modelview matrix to place the + lower-left corner of the bottom-left-most pixel somewhere other than 0,0 + and leave depth-testing enabled. + + See the documentation for arglDispImage() for more information. + @availability First appeared in ARToolKit 2.68.2. + */ +void arglDispImageStateful(ARGL_CONTEXT_SETTINGS_REF contextSettings); + +/*! + @function + @abstract Set compensation for camera lens distortion in arglDispImage to off or on. + @discussion + By default, arglDispImage compensates for the distortion of the camera's + acquired image caused by the lens when it draws. By calling this function + with enabled = FALSE, this compensation will be disabled in the specified + drawing context. It may be re-enabled at any time. + This function is useful if you need to draw an image, but do not know the + extent of the camera's lens distortion (such as during distortion calibration). + While distortion compensation is disabled, the dist_factor[] array in a + the camera cparam structure passed to arglDispImage is ignored. + @param contextSettings A reference to ARGL's settings for the current OpenGL + context, as returned by arglSetupForCurrentContext() for this context. + @param enable TRUE to enabled distortion compensation, FALSE to disable it. + The default state for new contexts is enable = TRUE. + @result TRUE if the distortion value was set, FALSE if an error occurred. + @availability First appeared in ARToolKit 2.71. +*/ +int arglDistortionCompensationSet(ARGL_CONTEXT_SETTINGS_REF contextSettings, int enable); + +/*! + @function + @abstract Enquire as to the enable state of camera lens distortion compensation in arglDispImage. + @discussion + By default, arglDispImage compensates for the distortion of the camera's + acquired image caused by the lens when it draws. This function enquires + as to whether arglDispImage is currently doing compensation or not. + @param contextSettings A reference to ARGL's settings for the current OpenGL + context, as returned by arglSetupForCurrentContext() for this context. + @param enable Pointer to an integer value which will be set to TRUE if distortion + compensation is enabled in the specified context, or FALSE if it is disabled. + @result TRUE if the distortion value was retreived, FALSE if an error occurred. + @availability First appeared in ARToolKit 2.71. + */ +int arglDistortionCompensationGet(ARGL_CONTEXT_SETTINGS_REF contextSettings, int *enable); + +/*! + @function + @abstract Set the current video image drawing scalefactor. + @param zoom The amount to scale the video image up or down. To draw the video + image double size, use a zoom value of 2.0. To draw the video image + half size use a zoom value of 0.5. + */ +int arglSetPixelZoom(ARGL_CONTEXT_SETTINGS_REF contextSettings, float zoom); + +/*! + @function + @abstract Retrieve the current video image drawing scalefactor. + @param zoom The amount to scale the video image up or down. To draw the video + image double size, use a zoom value of 2.0. To draw the video image + half size use a zoom value of 0.5. + */ +int arglGetPixelZoom(ARGL_CONTEXT_SETTINGS_REF contextSettings, float *zoom); + +/*! + @function + @abstract Set the format of pixel data which will be passed to arglDispImage*() + @discussion (description) + In gsub_lite, the format of the pixels (i.e. the arrangement of components + within each pixel) can be changed at runtime. Use this function to inform + gsub_lite the format the pixels being passed to arglDispImage*() functions + are in. This setting applies only to the context passed in parameter + contextSettings. The default format is determined by + the value of AR_DEFAULT_PIXEL_FORMAT at the time the library was built. + Usually, image data is passed in directly from images generated by ARVideo, + and so you should ensure that ARVideo is generating pixels of the same format. + @param contextSettings A reference to ARGL's settings for the current OpenGL + context, as returned by arglSetupForCurrentContext() for this context. + @param format A symbolic constant for the pixel format being set. See + AR_PIXEL_FORMAT in ar.h for a list of all possible formats. + @result TRUE if the pixel format value was set, FALSE if an error occurred. + @availability First appeared in ARToolKit 2.71. +*/ +int arglPixelFormatSet(ARGL_CONTEXT_SETTINGS_REF contextSettings, AR_PIXEL_FORMAT format); + +/*! + @function + @abstract Get the format of pixel data in which arglDispImage*() is expecting data to be passed. + @discussion This function enquires as to the current format of pixel data being + expected by the arglDispImage*() functions. The default format is determined by + the value of AR_DEFAULT_PIXEL_FORMAT at the time the library was built. + @param contextSettings A reference to ARGL's settings for the current OpenGL + context, as returned by arglSetupForCurrentContext() for this context. + @param format A symbolic constant for the pixel format in use. See + AR_PIXEL_FORMAT in ar.h for a list of all possible formats. + @param size The number of bytes of memory occupied per pixel, for the given format. + @result TRUE if the pixel format and size values were retreived, FALSE if an error occurred. + @availability First appeared in ARToolKit 2.71. +*/ +int arglPixelFormatGet(ARGL_CONTEXT_SETTINGS_REF contextSettings, AR_PIXEL_FORMAT *format, int *size); + +/*! + @function + @abstract Find out whether ARGL is rotating all OpenGL drawing by 90 degrees. + @discussion + On some OpenGL ES devices, it may be desirable to rotate all OpenGL drawing by 90 + degrees in the window coordinate system, in order to swap the horizontal and + vertical axes of the device. This may be a higher performance solution than + manually swapping rows and columns of submitted data. + + This function queries the current state of whether such a rotation is being performed by ARGL or not. + @param contextSettings A reference to ARGL's settings for the current OpenGL + context, as returned by arglSetupForCurrentContext() for this context. + @result TRUE if a 90 degree rotation is enabled, FALSE if it is disabled. +*/ +int arglGetRotate90(ARGL_CONTEXT_SETTINGS_REF contextSettings); + +/*! + @function + @abstract Set or unset a 90 degree rotation in all OpenGL drawing performed by ARGL. + @discussion + On some OpenGL ES devices, it may be desirable to rotate all OpenGL drawing by 90 + degrees in the window coordinate system, in order to swap the horizontal and + vertical axes of the device. This may be a higher performance solution than + manually swapping rows and columns of submitted data. + + This function enables or disables such an axis swap in ARGL with very little + performance cost, by introducing a 90-degree rotation into the OpenGL projection matrix. + + By default, 90 degree rotation is DISABLED. + @param contextSettings A reference to ARGL's settings for the current OpenGL. + context, as returned by arglSetupForCurrentContext() for this context. + @param rotate90 Set to TRUE or 1 to enable 90 degree rotation, FALSE to disable. +*/ +void arglSetRotate90(ARGL_CONTEXT_SETTINGS_REF contextSettings, int rotate90); + +int arglGetFlipH(ARGL_CONTEXT_SETTINGS_REF contextSettings); +void arglSetFlipH(ARGL_CONTEXT_SETTINGS_REF contextSettings, int flipH); +int arglGetFlipV(ARGL_CONTEXT_SETTINGS_REF contextSettings); +void arglSetFlipV(ARGL_CONTEXT_SETTINGS_REF contextSettings, int flipV); + +/*! + @function + @abstract Specify a desired pixel buffer size larger than the camera image size. + @discussion + By default, the pixel buffer accepted by function arglPixelBufferDataUpload() + is assumed to be tightly packed, row-major array of dimensions + equal to the calibrated camera image size (as passed in the fields arParam.xsize and arParam.ysize + of the ARHandle submitted to arglSetupForCurrentContext(). + + The pixel data buffer submitted may, under some circumstances be allowed to be larger than the + values of the calibrated camera image size (i.e. padded). This may only occur when the + underlying OpenGL ES impementation does not support non-power-of-two textures. For the Apple + iPhone family, this applies to the iPhone, the iPhone 3G, the iPod Touch 1st and 2nd Generation. + The iPhone 3GS and the iPod Touch 3rd Generation support non-power-of-two textures, and thus + padding of the pixel data buffer is not supported on these devices. If padding is desired, + the desired buffer size must be submitted using this function. Check that the + result from this function is TRUE before attempting to upload such a padded buffer. + @param contextSettings A reference to ARGL's settings for the current OpenGL + context, as returned by arglSetupForCurrentContext() for this context. + @param bufWidth The desired buffer width, in pixels. + @param bufHeight The desired buffer height, in pixels. + @result TRUE if the desired buffer size is supported, FALSE otherwise. +*/ +char arglPixelBufferSizeSet(ARGL_CONTEXT_SETTINGS_REF contextSettings, int bufWidth, int bufHeight); + +/*! + @function + @abstract Query the size of pixel data buffers expected by arglPixelBufferDataUpload(). + @discussion + See function arglPixelBufferSizeSet() for a full discussion. + @param contextSettings A reference to ARGL's settings for the current OpenGL + context, as returned by arglSetupForCurrentContext() for this context. + @param bufWidth A pointer to int, which will be filled out with the buffer width, in pixels, or NULL if this value is not required. + @param bufHeight A pointer to int, which will be filled out with the buffer height, in pixels, or NULL if this value is not required.. + @result TRUE if the buffer size was successfully queried, FALSE otherwise. + */ +char arglPixelBufferSizeGet(ARGL_CONTEXT_SETTINGS_REF contextSettings, int *bufWidth, int *bufHeight); + +/*! + @function + @abstract Upload a buffer of pixel data to an OpenGL texture for later use by arglDispImage(). + @discussion + ARGL provides the ability to perform distortion-compensated texturing of a camera video image + into the OpenGL context, for the purpose of video-see through augmented reality. This function + uploads the camera image data to an OpenGL texture, ready for later drawing using the function + arglDispImage(). + + If a pointer to an ARParam structure has been passed in to function arglSetupDebugMode, then + a check will be made whether debug mode is enabled, and if it is, then the buffer pointed to + by this function will be ignored, and instead the debug image will be loaded for texturing. + @param contextSettings A reference to ARGL's settings for the current OpenGL + context, as returned by arglSetupForCurrentContext() for this context. + @param bufDataPtr A pointer to the pixel buffer, which is a block of memory from which texture + data will be read. + + The layout of pixel data in the memory pointed to by bufDataPtr is assumed to be + specified by the value of pixelFormat in the ARHandle submitted to arglSetupForCurrentContext(), + but can be changed by calling arglPixelFormatSet() and/or arglPixelBufferSizeSet(). + + By default, the pixel buffer is assumed to be tightly packed, row-major array of dimensions + equal to the calibrated camera image size (as passed in the fields arParam.xsize and arParam.ysize + of the ARHandle submitted to arglSetupForCurrentContext(). + + The pixel data buffer submitted may, under some circumstances be allowed to be larger than the + values of the calibrated camera image size (i.e. padded). See the discussion section of the + documentation for function arglPixelBufferSizeSet() for more information. + + This may only occur when the underlying OpenGL impementation does not support non-power-of-two + textures. If padding is desired, the desired buffer size must be submitted using + arglPixelBufferSizeSet(). Check that the result from this function is TRUE before attempting to + upload such a padded buffer. + @result TRUE if the pixel buffer was successfully uploaded to OpenGL, FALSE otherwise. + @seealso arglSetupDebugMode arglSetupDebugMode +*/ +int arglPixelBufferDataUpload(ARGL_CONTEXT_SETTINGS_REF contextSettings, ARUint8 *bufDataPtr); + +#endif // !ARGL_DISABLE_DISP_IMAGE + +/*! + @function + @abstract Check for the availability of an OpenGL extension. + @discussion + Provides the same functionality as the gluCheckExtension() function, + since some platforms don't have GLU version 1.3 or later. + @param extName Name of the extension, e.g. "GL_EXT_texture". + @param extString The OpenGL extensions string, as returned by glGetString(GL_EXTENSIONS); + @result TRUE, if the extension is found, FALSE otherwise. + @availability First available in ARToolKit 4.5.0. + */ +GLboolean arglGluCheckExtension(const GLubyte* extName, const GLubyte *extString); + +/*! + @function + @abstract Checks for the presence of an OpenGL capability by version or extension. + @discussion + Checks for the presence of an OpenGL capability by version or extension. + The test returns true if EITHER the OpenGL driver's OpenGL implementation + version meets or exceeds a minimum value (passed in in minVersion) OR + if an OpenGL extension identifier passed in as a character string + is non-NULL, and is found in the current driver's list of supported extensions. + @param minVersion + A binary-coded decimal (i.e. version 1.0 is represented as 0x0100) version number. + If minVersion is zero, (i.e. there is no version of OpenGL with this extension in core) + the version test will always fail, and the result will only be true if the extension + string test passes. + @param extension A string with an extension name to search the drivers extensions + string for. E.g. "GL_EXT_texture". If NULL, the extension name test will always fail, + and the result will only be true if the version number test passes. + @result TRUE If either of the tests passes, or FALSE if both fail. + @availability First available in ARToolKit 4.5.0. + */ +int arglGLCapabilityCheck(const unsigned short minVersion, const unsigned char *extension); + +#ifdef __cplusplus +} +#endif + +/** + \endcond + */ + +#endif /* !__gsub_lite_h__ */ diff --git a/libs/include/AR/gsub_mtx.h b/libs/include/AR/gsub_mtx.h new file mode 100755 index 0000000..15c945f --- /dev/null +++ b/libs/include/AR/gsub_mtx.h @@ -0,0 +1,80 @@ +/* + * gsub_mtx.h + * ARToolKit5 + * + * This file is part of ARToolKit. + * + * ARToolKit is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ARToolKit is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ARToolKit. If not, see . + * + * As a special exception, the copyright holders of this library give you + * permission to link this library with independent modules to produce an + * executable, regardless of the license terms of these independent modules, and to + * copy and distribute the resulting executable under terms of your choice, + * provided that you also meet, for each linked independent module, the terms and + * conditions of the license of that module. An independent module is a module + * which is neither derived from nor based on this library. If you modify this + * library, you may extend this exception to your version of the library, but you + * are not obligated to do so. If you do not wish to do so, delete this exception + * statement from your version. + * + * Copyright 2015 Daqri, LLC. + * Copyright 2013-2015 ARToolworks, Inc. + * + * Author(s): Philip Lamb + */ + +/* + * + * Matrix routines that emulate the identical OpenGL 1.0-3.0 / OpenGL ES 1.0-1.1 routines, + * but with the current matrix passed as the first parameter, rather than being controlled + * by glMatrixMode calls. For documentation, read the relevant gl* manual pages (e.g. + * 'man 3 glLoadIdentity') + * + * gsub_mtx is available as part of libARgsub_lite, libARgsub_es and libARgsub_es2. + * + */ + +#ifndef __gsub_mtx_h__ +#define __gsub_mtx_h__ + +#ifdef __cplusplus +extern "C" { +#endif + +void mtxLoadIdentityf(float M[16]); // Replace matrix M with the identity matrix. +void mtxLoadMatrixf(float M[16], const float T[16]); // Replace matrix M with the specified matrix T. +void mtxMultMatrixf(float M[16], const float T[16]); // Multiply matrix M with matrix T. +void mtxTranslatef(float M[16], const float x, const float y, const float z); // Multiply M by a translation matrix. +void mtxRotatef(float M[16], const float q, const float x, const float y, const float z); // Multiply matrix M by a rotation matrix. q in degrees. +void mtxScalef(float M[16], const float x, const float y, const float z); // Multiply matrix M by a general scaling matrix. +void mtxOrthof(float M[16], float left, float right, float bottom, float top, float zNear, float zFar); // Multiply matrix M with an orthographic matrix. +void mtxFrustumf(float M[16], float left, float right, float bottom, float top, float zNear, float zFar); // Multiply matrix M by a perspective matrix. +void mtxPerspectivef(float M[16], float fovy, float aspect, float zNear, float zFar); // Multiply matrix M by a perspective matrix. fovy in degrees. +void mtxLookAtf(float M[16], float eyeX, float eyeY, float eyeZ, float centerX, float centerY, float centerZ, float upX, float upY, float upZ); // Multiply matrix M by a viewing matrix derived from an eye point, a reference point indicating the center of the scene, and an UP vector. + +void mtxLoadIdentityd(double M[16]); // Replace matrix M with the identity matrix. +void mtxLoadMatrixd(double M[16], const double T[16]); // Replace matrix M with the specified matrix T. +void mtxMultMatrixd(double M[16], const double T[16]); // Multiply matrix M with matrix T. +void mtxTranslated(double M[16], const double x, const double y, const double z); // Multiply M by a translation matrix. +void mtxRotated(double M[16], const double q, const double x, const double y, const double z); // Multiply matrix M by a rotation matrix. q in degrees. +void mtxScaled(double M[16], const double x, const double y, const double z); // Multiply matrix M by a general scaling matrix. +void mtxOrthod(double M[16], double left, double right, double bottom, double top, double zNear, double zFar); // Multiply matrix M with an orthographic matrix. +void mtxFrustumd(double M[16], double left, double right, double bottom, double top, double zNear, double zFar); // Multiply matrix M by a perspective matrix. +void mtxPerspectived(double M[16], double fovy, double aspect, double zNear, double zFar); // Multiply matrix M by a perspective matrix. fovy in degrees. +void mtxLookAtd(double M[16], double eyeX, double eyeY, double eyeZ, double centerX, double centerY, double centerZ, double upX, double upY, double upZ); // Multiply matrix M by a viewing matrix derived from an eye point, a reference point indicating the center of the scene, and an UP vector. + +#ifdef __cplusplus +} +#endif +#endif // !__gsub_mtx_h__ \ No newline at end of file diff --git a/libs/include/AR/icp.h b/libs/include/AR/icp.h new file mode 100755 index 0000000..279101e --- /dev/null +++ b/libs/include/AR/icp.h @@ -0,0 +1,180 @@ +/* + * icp.h + * ARToolKit5 + * + * This file is part of ARToolKit. + * + * ARToolKit is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ARToolKit is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ARToolKit. If not, see . + * + * As a special exception, the copyright holders of this library give you + * permission to link this library with independent modules to produce an + * executable, regardless of the license terms of these independent modules, and to + * copy and distribute the resulting executable under terms of your choice, + * provided that you also meet, for each linked independent module, the terms and + * conditions of the license of that module. An independent module is a module + * which is neither derived from nor based on this library. If you modify this + * library, you may extend this exception to your version of the library, but you + * are not obligated to do so. If you do not wish to do so, delete this exception + * statement from your version. + * + * Copyright 2015 Daqri, LLC. + * Copyright 2004-2015 ARToolworks, Inc. + * + * Author(s): Hirokazu Kato + * + */ + +#ifndef ICP_H +#define ICP_H + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define ICP_TRANS_MAT_IDENTITY NULL + + +/* + * Point Data + */ +typedef struct { + ICP2DCoordT *screenCoord; + ICP3DCoordT *worldCoord; + int num; +} ICPDataT; + +typedef struct { + ICP2DCoordT *screenCoordL; + ICP3DCoordT *worldCoordL; + int numL; + ICP2DCoordT *screenCoordR; + ICP3DCoordT *worldCoordR; + int numR; +} ICPStereoDataT; + + + +/* + * Handle + */ +typedef struct { + ARdouble matXc2U[3][4]; + int maxLoop; + ARdouble breakLoopErrorThresh; + ARdouble breakLoopErrorRatioThresh; + ARdouble breakLoopErrorThresh2; + ARdouble inlierProb; +} ICPHandleT; + +typedef struct { + ARdouble matXcl2Ul[3][4]; + ARdouble matXcr2Ur[3][4]; + ARdouble matC2L[3][4]; + ARdouble matC2R[3][4]; + int maxLoop; + ARdouble breakLoopErrorThresh; + ARdouble breakLoopErrorRatioThresh; + ARdouble breakLoopErrorThresh2; + ARdouble inlierProb; +} ICPStereoHandleT; + + + + +/*------------ icpUtil.c --------------*/ +int icpGetInitXw2Xc_from_PlanarData( ARdouble matXc2U[3][4], ICP2DCoordT screenCoord[], ICP3DCoordT worldCoord[], int num, ARdouble initMatXw2Xc[3][4] ); + + +/*------------ icpPoint.c --------------*/ +ICPHandleT *icpCreateHandle ( ARdouble matXc2U[3][4] ); +int icpDeleteHandle ( ICPHandleT **handle ); +int icpSetMatXc2U ( ICPHandleT *handle, ARdouble matXc2U[3][4] ); +int icpGetMatXc2U ( ICPHandleT *handle, ARdouble matXc2U[3][4] ); +int icpSetMaxLoop ( ICPHandleT *handle, int maxLoop ); +int icpGetMaxLoop ( ICPHandleT *handle, int *maxLoop ); +int icpSetBreakLoopErrorThresh ( ICPHandleT *handle, ARdouble breakLoopErrorThresh ); +int icpGetBreakLoopErrorThresh ( ICPHandleT *handle, ARdouble *breakLoopErrorThresh ); +int icpSetBreakLoopErrorRatioThresh ( ICPHandleT *handle, ARdouble breakLoopErrorThresh ); +int icpGetBreakLoopErrorRatioThresh ( ICPHandleT *handle, ARdouble *breakLoopErrorThresh ); +int icpSetBreakLoopErrorThresh2 ( ICPHandleT *handle, ARdouble breakLoopErrorThresh2 ); +int icpGetBreakLoopErrorThresh2 ( ICPHandleT *handle, ARdouble *breakLoopErrorThresh2 ); +int icpSetInlierProbability ( ICPHandleT *handle, ARdouble inlierProbability ); +int icpGetInlierProbability ( ICPHandleT *handle, ARdouble *inlierProbability ); +int icpPoint ( ICPHandleT *handle, ICPDataT *data, ARdouble initMatXw2Xc[3][4], ARdouble matXw2Xc[3][4], ARdouble *err ); +int icpPointRobust ( ICPHandleT *handle, ICPDataT *data, ARdouble initMatXw2Xc[3][4], ARdouble matXw2Xc[3][4], ARdouble *err ); + + +/*------------ icpPointStereo.c --------------*/ +ICPStereoHandleT *icpStereoCreateHandle ( ARdouble matXcl2Ul[3][4], ARdouble matXcr2Ur[3][4], ARdouble matC2L[3][4], ARdouble matC2R[3][4] ); +int icpStereoDeleteHandle ( ICPStereoHandleT **handle ); +int icpStereoSetMatXcl2Ul ( ICPStereoHandleT *handle, ARdouble matXcl2Ul[3][4] ); +int icpStereoSetMatXcr2Ur ( ICPStereoHandleT *handle, ARdouble matXcr2Ur[3][4] ); +int icpStereoGetMatXcl2Ul ( ICPStereoHandleT *handle, ARdouble matXcl2Ul[3][4] ); +int icpStereoGetMatXcr2Ur ( ICPStereoHandleT *handle, ARdouble matXcr2Ur[3][4] ); +int icpStereoSetMatC2L ( ICPStereoHandleT *handle, ARdouble matC2L[3][4] ); +int icpStereoSetMatC2R ( ICPStereoHandleT *handle, ARdouble matC2R[3][4] ); +int icpStereoGetMatC2L ( ICPStereoHandleT *handle, ARdouble matC2L[3][4] ); +int icpStereoGetMatC2R ( ICPStereoHandleT *handle, ARdouble matC2R[3][4] ); +int icpStereoSetMaxLoop ( ICPStereoHandleT *handle, int maxLoop ); +int icpStereoGetMaxLoop ( ICPStereoHandleT *handle, int *maxLoop ); +int icpStereoSetBreakLoopErrorThresh ( ICPStereoHandleT *handle, ARdouble breakLoopErrorThresh ); +int icpStereoGetBreakLoopErrorThresh ( ICPStereoHandleT *handle, ARdouble *breakLoopErrorThresh ); +int icpStereoSetBreakLoopErrorRatioThresh ( ICPStereoHandleT *handle, ARdouble breakLoopErrorThresh ); +int icpStereoGetBreakLoopErrorRatioThresh ( ICPStereoHandleT *handle, ARdouble *breakLoopErrorThresh ); +int icpStereoSetBreakLoopErrorThresh2 ( ICPStereoHandleT *handle, ARdouble breakLoopErrorThresh2 ); +int icpStereoGetBreakLoopErrorThresh2 ( ICPStereoHandleT *handle, ARdouble *breakLoopErrorThresh2 ); +int icpStereoSetInlierProbability ( ICPStereoHandleT *handle, ARdouble inlierProbability ); +int icpStereoGetInlierProbability ( ICPStereoHandleT *handle, ARdouble *inlierProbability ); +int icpStereoPoint ( ICPStereoHandleT *handle, ICPStereoDataT *data, ARdouble initMatXw2Xc[3][4], ARdouble matXw2Xc[3][4], ARdouble *err ); +int icpStereoPointRobust ( ICPStereoHandleT *handle, ICPStereoDataT *data, ARdouble initMatXw2Xc[3][4], ARdouble matXw2Xc[3][4], ARdouble *err ); + + +#if 0 +int icpRobustGetXw2Xc( ICPHandleT *handle, + ICPDataT *data, + ARdouble initMatXw2Xc[3][4], + ARdouble matXw2Xc[3][4], + ARdouble *err ); + +int icpGetXw2XcFromLineAndPoint( ICPHandleT *handle, + ICPLinesDataT *linesData, + ICPDataT *pointData, + ARdouble initMatXw2Xc[3][4], + ARdouble matXw2Xc[3][4], + ARdouble *err ); + + +int icpStereoCheckErr( ARdouble S[6], ARdouble matXcl2Ul[3][4], ARdouble matXcl2Ur[3][4], ICPStereoDataT *data, ARdouble *err ); +int icpRobustCheckErr( ARdouble S[6], ARdouble matXc2U[3][4], ICPDataT *data, ARdouble *weight, ARdouble *err ); +int icpRobustUpdateWeight( ARdouble S[6], ARdouble matXc2U[3][4], ICPDataT *data, ARdouble sd2, ARdouble *weight ); + + +int icpGetJ_E_S( ARdouble J_E_S[6], ICP2DLineT *line, ICP2DLineSegT *lineSeg, ARdouble matXc2U[3][4], ARdouble q[7], ARdouble s[6], + ICP3DLineSegT *cameraCoord, ICP3DLineSegT *worldCoord, ICP2DCoordT *observedScreenCoord ); +int icpGetJ_E_L( ARdouble J_E_L[3], ICP2DLineT *line, ICP2DCoordT *screenCoord ); +int icpGetJ_L_X( ARdouble J_L_X[3][4], ICP2DLineSegT *lineSeg ); +int icpGetLine( ICP2DLineT *line, ICP2DLineSegT *lineSeg ); +int icpGetdE( ARdouble *dE, ICP2DLineT *line, ICP2DCoordT *screenCoord ); +int icpLineCheckErr( ARdouble S[6], ARdouble matXc2U[3][4], ICPLinesDataT *data, ARdouble *err ); +#endif + + + +#ifdef __cplusplus +} +#endif +#endif diff --git a/libs/include/AR/icpCalib.h b/libs/include/AR/icpCalib.h new file mode 100755 index 0000000..974892f --- /dev/null +++ b/libs/include/AR/icpCalib.h @@ -0,0 +1,70 @@ +/* + * icpCalib.h + * ARToolKit5 + * + * This file is part of ARToolKit. + * + * ARToolKit is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ARToolKit is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ARToolKit. If not, see . + * + * As a special exception, the copyright holders of this library give you + * permission to link this library with independent modules to produce an + * executable, regardless of the license terms of these independent modules, and to + * copy and distribute the resulting executable under terms of your choice, + * provided that you also meet, for each linked independent module, the terms and + * conditions of the license of that module. An independent module is a module + * which is neither derived from nor based on this library. If you modify this + * library, you may extend this exception to your version of the library, but you + * are not obligated to do so. If you do not wish to do so, delete this exception + * statement from your version. + * + * Copyright 2015 Daqri, LLC. + * Copyright 2004-2015 ARToolworks, Inc. + * + * Author(s): Hirokazu Kato + * + */ + +#ifndef ICP_CALIB_H +#define ICP_CALIB_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define ICP_CALIB_STEREO_MAX_LOOP 100 +#define ICP_CALIB_STEREO_BREAK_LOOP_ERROR_THRESH 0.001 +#define ICP_CALIB_STEREO_BREAK_LOOP_ERROR_RATIO_THRESH 0.99 + + +typedef struct { + ICP2DCoordT *screenCoordL; + ICP2DCoordT *screenCoordR; + ICP3DCoordT *worldCoordL; + ICP3DCoordT *worldCoordR; + int numL; + int numR; + ARdouble initMatXw2Xcl[3][4]; +} ICPCalibDataT; + +int icpCalibStereo( ICPCalibDataT data[], int num, + ARdouble matXcl2Ul[3][4], ARdouble matXcr2Ur[3][4], ARdouble initTransL2R[3][4], + ARdouble matTransL2R[3][4], + ARdouble *err ); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/libs/include/AR/icpCore.h b/libs/include/AR/icpCore.h new file mode 100755 index 0000000..d3e120c --- /dev/null +++ b/libs/include/AR/icpCore.h @@ -0,0 +1,95 @@ +/* + * icpCore.h + * ARToolKit5 + * + * This file is part of ARToolKit. + * + * ARToolKit is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ARToolKit is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ARToolKit. If not, see . + * + * As a special exception, the copyright holders of this library give you + * permission to link this library with independent modules to produce an + * executable, regardless of the license terms of these independent modules, and to + * copy and distribute the resulting executable under terms of your choice, + * provided that you also meet, for each linked independent module, the terms and + * conditions of the license of that module. An independent module is a module + * which is neither derived from nor based on this library. If you modify this + * library, you may extend this exception to your version of the library, but you + * are not obligated to do so. If you do not wish to do so, delete this exception + * statement from your version. + * + * Copyright 2015 Daqri, LLC. + * Copyright 2004-2015 ARToolworks, Inc. + * + * Author(s): Hirokazu Kato + * + */ + +#ifndef ICP_CORE_H +#define ICP_CORE_H + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef M_PI +#define M_PI 3.14159265358979323846F +#endif + +#define ICP_DEBUG 0 +#define ICP_MAX_LOOP 10 +#define ICP_BREAK_LOOP_ERROR_THRESH 0.1F +#define ICP_BREAK_LOOP_ERROR_RATIO_THRESH 0.99F +#define ICP_BREAK_LOOP_ERROR_THRESH2 4.0F +#define ICP_INLIER_PROBABILITY 0.50F + +typedef struct { + ARdouble x; + ARdouble y; +} ICP2DCoordT; + +typedef struct { + ARdouble x; + ARdouble y; + ARdouble z; +} ICP3DCoordT; + +typedef struct { + ARdouble a; + ARdouble b; + ARdouble c; +} ICP2DLineT; + +typedef struct { + ICP2DCoordT p1; + ICP2DCoordT p2; +} ICP2DLineSegT; + +typedef struct { + ICP3DCoordT p1; + ICP3DCoordT p2; +} ICP3DLineSegT; + + +int icpGetXc_from_Xw_by_MatXw2Xc( ICP3DCoordT *Xc, ARdouble matXw2Xc[3][4], ICP3DCoordT *Xw ); +int icpGetU_from_X_by_MatX2U( ICP2DCoordT *u, ARdouble matX2U[3][4], ICP3DCoordT *coord3d ); +int icpGetJ_U_S( ARdouble J_U_S[2][6], ARdouble matXc2U[3][4], ARdouble matXw2Xc[3][4], ICP3DCoordT *worldCoord ); +int icpGetDeltaS( ARdouble S[6], ARdouble dU[], ARdouble J_U_S[][6], int n ); +int icpUpdateMat( ARdouble matXw2Xc[3][4], ARdouble dS[6] ); + +void icpDispMat( char *title, ARdouble *mat, int row, int clm ); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/libs/include/AR/matrix.h b/libs/include/AR/matrix.h new file mode 100755 index 0000000..4397e4b --- /dev/null +++ b/libs/include/AR/matrix.h @@ -0,0 +1,156 @@ +/* + * matrix.h + * ARToolKit5 + * + * This file is part of ARToolKit. + * + * ARToolKit is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ARToolKit is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ARToolKit. If not, see . + * + * As a special exception, the copyright holders of this library give you + * permission to link this library with independent modules to produce an + * executable, regardless of the license terms of these independent modules, and to + * copy and distribute the resulting executable under terms of your choice, + * provided that you also meet, for each linked independent module, the terms and + * conditions of the license of that module. An independent module is a module + * which is neither derived from nor based on this library. If you modify this + * library, you may extend this exception to your version of the library, but you + * are not obligated to do so. If you do not wish to do so, delete this exception + * statement from your version. + * + * Copyright 2015 Daqri, LLC. + * Copyright 2002-2015 ARToolworks, Inc. + * + * Author(s): Hirokazu Kato, Philip Lamb + * + */ + +#ifndef AR_MATRIX_H +#define AR_MATRIX_H + +#include + + +#ifdef __cplusplus +extern "C" { +#endif + + +/* === matrix definition === + + <---- clm ---> + [ 10 20 30 ] ^ + [ 20 10 15 ] | + [ 12 23 13 ] row + [ 20 10 15 ] | + [ 13 14 15 ] v + +=========================== */ + +typedef struct { + ARdouble *m; + int row; + int clm; +} ARMat; + +#ifdef ARDOUBLE_IS_FLOAT +# define ARMatf ARMat +#else +typedef struct { + float *m; + int row; + int clm; +} ARMatf; +#endif + +typedef struct { + ARdouble *v; + int clm; +} ARVec; + + +/* 0 origin */ +#define ARELEM0(mat,r,c) ((mat)->m[(r)*((mat)->clm)+(c)]) +/* 1 origin */ +#define ARELEM1(mat,row,clm) ARELEM0(mat,row-1,clm-1) + + + +ARMat *arMatrixAlloc(int row, int clm); +int arMatrixFree(ARMat *m); +#ifdef ARDOUBLE_IS_FLOAT +# define arMatrixAllocf arMatrixAlloc +# define arMatrixFreef arMatrixFree +#else +ARMatf *arMatrixAllocf(int row, int clm); +int arMatrixFreef(ARMatf *m); +#endif + +int arMatrixDup(ARMat *dest, ARMat *source); +ARMat *arMatrixAllocDup(ARMat *source); + +int arMatrixUnit(ARMat *unit); +ARMat *arMatrixAllocUnit(int dim); + +int arMatrixMul(ARMat *dest, ARMat *a, ARMat *b); +ARMat *arMatrixAllocMul(ARMat *a, ARMat *b); + +#ifdef ARDOUBLE_IS_FLOAT +# define arMatrixMulf arMatrixMul +# define arMatrixAllocMulf arMatrixAllocMul +#else +int arMatrixMulf(ARMatf *dest, ARMatf *a, ARMatf *b); +ARMatf *arMatrixAllocMulf(ARMatf *a, ARMatf *b); +#endif + +int arMatrixTrans(ARMat *dest, ARMat *source); // Transpose source, place result in dest. +ARMat *arMatrixAllocTrans(ARMat *source); // Transpose source, place result in newly allocated matrix. + +#ifdef ARDOUBLE_IS_FLOAT +# define arMatrixTransf arMatrixTrans +# define arMatrixAllocTransf arMatrixAllocTrans +#else +int arMatrixTransf(ARMatf *dest, ARMatf *source); +ARMatf *arMatrixAllocTransf(ARMatf *source); +#endif + +int arMatrixInv(ARMat *dest, ARMat *source); +int arMatrixSelfInv(ARMat *m); +ARMat *arMatrixAllocInv(ARMat *source); + +#ifdef ARDOUBLE_IS_FLOAT +# define arMatrixSelfInvf arMatrixSelfInv +#else +int arMatrixSelfInvf(ARMatf *m); +#endif + +ARdouble arMatrixDet(ARMat *m); + +int arMatrixPCA( ARMat *input, ARMat *evec, ARVec *ev, ARVec *mean ); +int arMatrixPCA2( ARMat *input, ARMat *evec, ARVec *ev ); + +int arMatrixDisp(ARMat *m); + + +ARVec *arVecAlloc( int clm ); +int arVecFree( ARVec *v ); +int arVecDisp( ARVec *v ); +ARdouble arVecHousehold( ARVec *x ); +ARdouble arVecInnerproduct( ARVec *x, ARVec *y ); +int arVecTridiagonalize( ARMat *a, ARVec *d, ARVec *e ); + + +#ifdef __cplusplus +} +#endif +#endif diff --git a/libs/include/AR/param.h b/libs/include/AR/param.h new file mode 100755 index 0000000..7d12adc --- /dev/null +++ b/libs/include/AR/param.h @@ -0,0 +1,449 @@ +/* + * param.h + * ARToolKit5 + * + * This file is part of ARToolKit. + * + * ARToolKit is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ARToolKit is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ARToolKit. If not, see . + * + * As a special exception, the copyright holders of this library give you + * permission to link this library with independent modules to produce an + * executable, regardless of the license terms of these independent modules, and to + * copy and distribute the resulting executable under terms of your choice, + * provided that you also meet, for each linked independent module, the terms and + * conditions of the license of that module. An independent module is a module + * which is neither derived from nor based on this library. If you modify this + * library, you may extend this exception to your version of the library, but you + * are not obligated to do so. If you do not wish to do so, delete this exception + * statement from your version. + * + * Copyright 2015 Daqri, LLC. + * Copyright 2003-2015 ARToolworks, Inc. + * + * Author(s): Takeshi Mita, Shinsaku Hiura, Hirokazu Kato, Philip Lamb + * + */ +/******************************************************* + * + * Author: Takeshi Mita, Shinsaku Hiura, Hirokazu Kato + * + * tmita@inolab.sys.es.osaka-u.ac.jp + * shinsaku@sys.es.osaka-u.ac.jp + * kato@sys.im.hiroshima-cu.ac.jp + * + * Revision: 5.0 + * Date: 03/08/13 + * + *******************************************************/ + +#ifndef AR_PARAM_H +#define AR_PARAM_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/*! + @header param + @abstract ARToolKit functions for handling calibrated camera parameters. + @discussion +*/ +/*! + @defined + @abstract Default version for functions accepting a "distortion function version" parameter. + @discussion See function arParamObserv2Ideal() for discussion. +*/ +#define AR_DIST_FUNCTION_VERSION_DEFAULT 4 +/*! + @defined + @abstract Maximum version allowable for functions accepting a "distortion function version" parameter. + @discussion See function arParamObserv2Ideal() for discussion. +*/ +#define AR_DIST_FUNCTION_VERSION_MAX 4 +/*! + @defined + @abstract Maximum number of values in a distortion factor array. + @discussion See function arParamObserv2Ideal() for discussion. +*/ +#define AR_DIST_FACTOR_NUM_MAX 9 +/*! + @defined + @abstract Default padding added around a lookup-table based camera parameter. + @discussion See function arParamLTCreate() for discussion. +*/ +#define AR_PARAM_LT_DEFAULT_OFFSET 15 + +/*! + @typedef + @abstract Structure holding camera parameters, including image size, projection matrix and lens distortion parameters. + @discussion + ARToolKit's tracking depends on accurate knowledge of the properties of the + imaging system used to acquire input images. This structure holds the properties + of an imaging system for internal use in ARToolKit. This information is used + throughout the entire ARToolKit pipeline, including knowing the size of images + being returned by the video library, marker detection and pose estimation, + and warping of camera images for video-see-through registration. + @field xsize The width in pixels of images returned by arVideoGetImage() for the camera. + @field ysize The height in pixels of images returned by arVideoGetImage() for the camera. + @field mat The projection matrix for the calibrated camera parameters. This can be + converted to an OpenGL projection matrix by the function arglCameraFrustumRHf(). + @field dist_factor See function arParamObserv2Ideal() for discussion. + @field dist_function_version See function arParamObserv2Ideal() for discussion. + @seealso arParamClear arParamClear + @seealso arParamLoad arParamLoad + @seealso arParamSave arParamSave + */ +typedef struct { + int xsize; + int ysize; + ARdouble mat[3][4]; + ARdouble dist_factor[AR_DIST_FACTOR_NUM_MAX]; + int dist_function_version; // Must be last field in structure (as will not be written to disk). +} ARParam; + +// Constant array with parameters applicable to each version +// of the camera parameter distortion function. +typedef struct { + int dist_factor_num; + int ARParam_size; +} arParamVersionInfo_t; +extern const arParamVersionInfo_t arParamVersionInfo[AR_DIST_FUNCTION_VERSION_MAX]; + +typedef struct { + float *i2o; + float *o2i; + int xsize; + int ysize; + int xOff; + int yOff; +} ARParamLTf; + +//typedef struct { +// short *i2o; +// short *o2i; +// int xsize; +// int ysize; +// int xOff; +// int yOff; +//} ARParamLTi; + +/*! + @typedef + @abstract Structure holding camera parameters, in lookup table form. + @discussion + ARToolKit's tracking depends on accurate knowledge of the properties of the + imaging system used to acquire input images. This structure holds the properties + of an imaging system for internal use in ARToolKit. This information is used + throughout the entire ARToolKit pipeline, including knowing the size of images + being returned by the video library, marker detection and pose estimation, + and warping of camera images for video-see-through registration. + + This version of the structure contains a pre-calculated lookup table of + values covering the camera image width and height, plus a padded border. + @field param A copy of original ARParam from which the lookup table was calculated. + @field paramLTf The lookup table. +*/ +typedef struct { + ARParam param; + ARParamLTf paramLTf; + //ARParamLTi paramLTi; +} ARParamLT; + +int arParamDisp( const ARParam *param ); + +/*! + @function + @abstract Create a camera parameter structure representing an idealised lens. + @discussion + This function creates a camera parameter structure representing an idealised lens, + that is, a lens with a symmetrical perspective projection and no distortion. + This idealised lens is useful in cases where you wish to match the lens model + of an OpenGL camera with the same window dimensions. + @param param Pointer to an ARParam structure which will be filled out with + the resulting camera parameters. + @param xsize The horizontal dimension of the image. + @param ysize The vertical dimension of the image. + @param dist_function_version Allows creation of parameters with an older version + of the lens distortion model. Pass AR_DIST_FUNCTION_VERSION_DEFAULT to create an ARParam + with the current lens distortion model, or a lesser integer to use an earlier version. + @result 0 if the function completed successfully, or -1 in case of error. + */ +int arParamClear( ARParam *param, int xsize, int ysize, int dist_function_version ); + +int arParamDistFactorClear( ARdouble dist_factor[AR_DIST_FACTOR_NUM_MAX], int xsize, int ysize, int dist_function_version ); + +int arParamChangeSize( ARParam *source, int xsize, int ysize, ARParam *newparam ); + +int arParamDecomp( const ARParam *source, ARParam *icpara, ARdouble trans[3][4] ); + +int arParamDecompMat( const ARdouble source[3][4], ARdouble cpara[3][4], ARdouble trans[3][4] ); + +#ifdef ARDOUBLE_IS_FLOAT +#define arParamDecompMatf arParamDecompMat +#else +int arParamDecompMatf( const ARdouble source[3][4], float cpara[3][4], float trans[3][4] ); +#endif + +/*! + @function + @abstract Use lens distortion parameters to convert idealised (zero-distortion) window coordinates to observed (distorted) coordinates. + @discussion + See function arParamObserv2Ideal() for full discussion. + + This function is the output function of the pair. It's inputs are + idealised coordinates, e.g. taken from OpenGL. The outputs are the + location where in a distorted image where the same point would lie. + @param dist_factor An array of ARdouble values holding the lens distortion + parameters. These values are generated as part of the camera calibration + process in ARToolKit. The exact number of values from the array used by the + function is determined by the distortion function version, but does not + exceed AR_DIST_FACTOR_NUM_MAX. + @param ix Input idealised normalised window coordinate x axis value. + @param iy Input idealised normalised window coordinate y axis value. + @param ox Pointer to ARdouble, which on return will hold the observed normalised window coordinate x axis value. + @param oy Pointer to ARdouble, which on return will hold the observed normalised window coordinate y axis value. + @param dist_function_version An integer, in the range [1, AR_DIST_FUNCTION_VERSION_MAX] which determines the + algorithm used to interpret the dist_factor values. + + See function arParamObserv2Ideal() for full discussion. + @result 0 in case of function success, or -1 if an error occured. At + present the only error possible is an invalid value of dist_function_version. + @seealso arParamObserv2Ideal arParamObserv2Ideal + @seealso arParamObserv2IdealLTf arParamObserv2IdealLTf +*/ +int arParamIdeal2Observ( const ARdouble dist_factor[AR_DIST_FACTOR_NUM_MAX], const ARdouble ix, const ARdouble iy, + ARdouble *ox, ARdouble *oy, const int dist_function_version ); + +/*! + @function + @abstract Use lens distortion parameters to convert observed (distorted) window coordinates to idealised (zero-distortion) coordinates. + @discussion + This function is used by ARToolKit to convert for the + the effects of lens distortion in images which have been acquired + from lens-based optical systems. All lenses introduce some amount + of lens distortion. ARToolKit includes calibration utilities to + measure the centre of distortion and the radial distortion factors + in the x and y dimensions. This calibration information is saved + as part of the camera parameters. + + This function is one of a pair of functions which convert between + OBSERVED window coordinates (i.e. the location of a known reference + point, as measured in the x-y viewing plane of an image containing + lens distortion) and IDEALISED coordinates (i.e. the location of the + same reference point as measured in an image containing no radial + distortion, e.g. an image rendered using OpenGL's viewing model.) + + This function is the input function of the pair. It's inputs are + distorted coordinates, e.g. taken from an image acquired from a camera + The outputs are the location where in an idealised image (e.g. generated + with OpenGL) where the same point would lie. + + @param dist_factor An array of ARdouble values holding the lens distortion + parameters. These values are generated as part of the camera calibration + process in ARToolKit. The exact number of values from the array used by the + function is determined by the distortion function version, but does not + exceed AR_DIST_FACTOR_NUM_MAX. + @param ix Input observed normalised window coordinate x axis value. + @param iy Input observed normalised window coordinate y axis value. + @param ox Pointer to ARdouble, which on return will hold the idealised normalised window coordinate x axis value. + @param oy Pointer to ARdouble, which on return will hold the idealised normalised window coordinate y axis value. + @param dist_function_version An integer, in the range [1, AR_DIST_FUNCTION_VERSION_MAX] which determines the + algorithm used to interpret the dist_factor values. + + The values correspond to the following algorithms: + + version 1: The original ARToolKit lens model, with a single radial distortion factor, plus center of distortion.
+ version 2: Improved distortion model, introduced in ARToolKit v4.0. This algorithm adds a quadratic term to the radial distortion factor of the version 1 algorithm.
+ version 3: Improved distortion model with aspect ratio, introduced in ARToolKit v4.0. The addition of an aspect ratio to the version 2 algorithm allows for non-square pixels, as found e.g. in DV image streams.
+ version 4: OpenCV-based distortion model, introduced in ARToolKit v4.3. This differs from the standard OpenCV model by the addition of a scale factor, so that input values do not exceed the range [-1.0, 1.0] in either forward or inverse conversions. + @result 0 in case of function success, or -1 if an error occured. At + present the only error possible is an invalid value of dist_function_version. + @seealso arParamIdeal2Observ arParamIdeal2Observ + @seealso arParamIdeal2ObservLTf arParamIdeal2ObservLTf +*/ +int arParamObserv2Ideal( const ARdouble dist_factor[AR_DIST_FACTOR_NUM_MAX], const ARdouble ox, const ARdouble oy, + ARdouble *ix, ARdouble *iy, const int dist_function_version ); +/*! + @function + @abstract Save lens parameters to a file. + @discussion + See the discussion under ARParam for more info. + @param filename Path to file to which to save the parameters. + The file pointed to may later be reloaded with arParamLoad. + @param num Number of ARParams to be saved, normally 1. + @param param Pointer to the ARParam structure to save. + @result 0 if successful, or -1 if an error occured. + @seealso ARParam ARParam + @seealso arParamLoad arParamLoad + @seealso arParamLoadFromBuffer arParamLoadFromBuffer + */ +int arParamSave( const char *filename, const int num, const ARParam *param, ...); + +/*! + @function + @abstract Load lens parameters from a file. + @discussion + See the discussion under ARParam for more info. + @param filename Path to file from which to load the parameters. + The file pointed to should be a file saved with arParamSave. + @param num Number of ARParams to be loaded, normally 1. + @param param Pointer to the ARParam structure into which the parameters will be read. + @result 0 if successful, or -1 if an error occured. + @seealso ARParam ARParam + @seealso arParamLoadFromBuffer arParamLoadFromBuffer + @seealso arParamSave arParamSave + */ +int arParamLoad( const char *filename, int num, ARParam *param, ...); + + /*! + @function + @abstract Load lens parameters from a buffer. + @discussion + See the discussion under ARParam for more info. + @param buffer Buffer from which the parameter(s) will be loaded. + The buffer could be (for example) the contents of a parameter file read with fread(). + @param bufsize Size of the contents of buffer. + @param param Pointer to the ARParam structure into which the parameters will be read. + @result 0 if successful, or -1 if an error occured. + @seealso ARParam ARParam + @seealso arParamLoad arParamLoad + @seealso arParamSave arParamSave + */ +int arParamLoadFromBuffer( const void *buffer, size_t bufsize, ARParam *param); + +int arParamGetPerspectiveMat( ARdouble global[][3], ARdouble idealScreen[][2], int data_num, ARdouble mat[3][4] ); + +int arParamSaveExt( const char *filename, ARdouble para[3][4] ); +int arParamLoadExt( const char *filename, ARdouble para[3][4] ); +int arParamLoadExtFromBuffer(const void *buffer, size_t bufsize, ARdouble para[3][4] ); +int arParamDispExt( ARdouble para[3][4]); + +int arParamSaveOptical(const char *filename, const ARdouble fovy, const ARdouble aspect, const ARdouble m[16]); +int arParamLoadOptical(const char *filename, ARdouble *fovy_p, ARdouble *aspect_p, ARdouble m[16]); +int arParamLoadOpticalFromBuffer(const void *buffer, size_t bufsize, ARdouble *fovy_p, ARdouble *aspect_p, ARdouble m[16]); +int arParamDispOptical(const ARdouble fovy, const ARdouble aspect, const ARdouble m[16]); + +int arParamLTSave( char *filename, char *ext, ARParamLT *paramLT ); +ARParamLT *arParamLTLoad( char *filename, char *ext ); + +/*! + @function + @abstract Allocate and calculate a lookup-table camera parameter from a standard camera parameter. + @discussion A lookup-table based camera parameter offers significant performance + savings in certain ARToolKit operations (including unwarping of pattern spaces) + compared to use of the standard camera parameter. + + The original ARParam camera parameters structure is copied into the ARParamLT + structure, and is available as paramLT->param. + @param param A pointer to an ARParam structure from which the lookup table will be generaeted. + This ARParam structure will be copied, and the original may be disposed of. + @param offset An integer value which specifies how much the lookup table values will be + padded around the original camera parameters size. Normally, the default value + AR_PARAM_LT_DEFAULT_OFFSET (defined elsewhere in this header) should be used. However, + when using a camera with a large amount of lens distortion, a higher value may be + required to cope with the corners or sides of the camera image frame. + @result A pointer to a newly-allocated ARParamLT structure, or NULL if an error + occurred. Once the ARParamLT is no longer needed, it should be disposed + of by calling arParamLTFree() on it. + @seealso arParamLTFree arParamLTFree + */ +ARParamLT *arParamLTCreate( ARParam *param, int offset ); + +/*! + @function + @abstract Dispose of a memory allocated to a lookup-table camera parameter. + @discussion + @param paramLT_p Pointer to a pointer to the paramLT structure to be disposed of. + On return, the location pointed to will be set to NULL. + @result -1 if an error occurred, or 0 in the case of no error. + @seealso arParamLTCreate arParamLTCreate + */ +int arParamLTFree( ARParamLT **paramLT_p ); + +/*! + @function + @abstract Use a lookup-table camera parameter to convert idealised (zero-distortion) window coordinates to observed (distorted) coordinates. + @discussion + See function arParamObserv2IdealLTf() for full discussion. + + This function is the output function of the pair. It's inputs are + idealised coordinates, e.g. taken from OpenGL. The outputs are the + location where in a distorted image where the same point would lie. + @param paramLTf A lookup-table based version of the lens distortion + parameters. These values are generated as part of the camera calibration + process in ARToolKit, and converted to a lookup table by arParamLTCreate(). + @param ix Input idealised normalised window coordinate x axis value. + @param iy Input idealised normalised window coordinate y axis value. + @param ox Pointer to ARdouble, which on return will hold the observed normalised window coordinate x axis value. + @param oy Pointer to ARdouble, which on return will hold the observed normalised window coordinate y axis value. + @result 0 in case of function success, or -1 if an error occured. One possible + error condition is the case where the input portion of the pair is outside the + range of coordinates covered by the lookup table. + @seealso arParamLTCreate arParamLTCreate + @seealso arParamIdeal2Observ arParamIdeal2Observ + @seealso arParamObserv2IdealLTf arParamObserv2IdealLTf +*/ + +int arParamIdeal2ObservLTf( ARParamLTf *paramLTf, float ix, float iy, float *ox, float *oy); + + +/*! + @function + @abstract Use a lookup-table camera parameter to convert observed (distorted) window coordinates to idealised (zero-distortion) coordinates. + @discussion + This function is used by ARToolKit to convert for the + the effects of lens distortion in images which have been acquired + from lens-based optical systems. All lenses introduce some amount + of lens distortion. ARToolKit includes calibration utilities to + measure the centre of distortion and the radial distortion factors + in the x and y dimensions. This calibration information is saved + as part of the camera parameters. + + This function is one of a pair of functions which convert between + OBSERVED window coordinates (i.e. the location of a known reference + point, as measured in the x-y viewing plane of an image containing + lens distortion) and IDEALISED coordinates (i.e. the location of the + same reference point as measured in an image containing no radial + distortion, e.g. an image rendered using OpenGL's viewing model.) + + This function is the input function of the pair. It's inputs are + distorted coordinates, e.g. taken from an image acquired from a camera + The outputs are the location where in an idealised image (e.g. generated + with OpenGL) where the same point would lie. + + @param paramLTf A lookup-table based version of the lens distortion + parameters. These values are generated as part of the camera calibration + process in ARToolKit, and converted to a lookup table by arParamLTCreate(). + @param ix Input observed normalised window coordinate x axis value. + @param iy Input observed normalised window coordinate y axis value. + @param ox Pointer to ARdouble, which on return will hold the idealised normalised window coordinate x axis value. + @param oy Pointer to ARdouble, which on return will hold the idealised normalised window coordinate y axis value. + @result 0 in case of function success, or -1 if an error occured. One possible + error condition is the case where the input portion of the pair is outside the + range of coordinates covered by the lookup table. + @seealso arParamObserv2Ideal arParamObserv2Ideal + @seealso arParamIdeal2ObservLTf arParamIdeal2ObservLTf +*/ +int arParamObserv2IdealLTf( ARParamLTf *paramLTf, float ox, float oy, float *ix, float *iy); + +//int arParamIdeal2ObservLTi( ARParamLTi *paramLTi, int ix, int iy, int *ox, int *oy); + +//int arParamObserv2IdealLTi( ARParamLTi *paramLTi, int ox, int oy, int *ix, int *iy); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/libs/include/AR/sys/CameraVideo.h b/libs/include/AR/sys/CameraVideo.h new file mode 100755 index 0000000..7e2b3c1 --- /dev/null +++ b/libs/include/AR/sys/CameraVideo.h @@ -0,0 +1,259 @@ +/* + * CameraVideo.h + * ARToolKit5 + * + * This file is part of ARToolKit. + * + * ARToolKit is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ARToolKit is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ARToolKit. If not, see . + * + * As a special exception, the copyright holders of this library give you + * permission to link this library with independent modules to produce an + * executable, regardless of the license terms of these independent modules, and to + * copy and distribute the resulting executable under terms of your choice, + * provided that you also meet, for each linked independent module, the terms and + * conditions of the license of that module. An independent module is a module + * which is neither derived from nor based on this library. If you modify this + * library, you may extend this exception to your version of the library, but you + * are not obligated to do so. If you do not wish to do so, delete this exception + * statement from your version. + * + * Copyright 2015 Daqri, LLC. + * Copyright 2008-2015 ARToolworks, Inc. + * + * Author(s): Philip Lamb + * + * Rev Date Who Changes + * 1.0.0 2008-05-04 PRL Written. + * + */ + +#import +#import + +@protocol CameraVideoTookPictureDelegate +@required +/* + This delegate method is called each time a frame is captured + from the video stream. + + The frame can be retrieved with the call: + + UInt64 timestamp; + unsigned char *frameData = frameTimestamp:×tamp; + */ +- (void) cameraVideoTookPicture:(id)sender userData:(void *)data; +@optional +/* + This delegate method is called if the user requested a high-resolution JPEG photo. + You can write the JPEG to the user's photo roll with this code: + + #import + ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init]; + [library writeImageDataToSavedPhotosAlbum:jpegData metadata:nil completionBlock:^(NSURL *assetURL, NSError *error) { + if (error) { + NSLog(@"Error writing captured photo to photo album.\n"); + } + }]; + [library release]; + + or you can write it directly to a file: + + if (![jpegData writeToFile:jpegPath atomically:NO]) { + NSLog(@"Error writing captured photo to '%@'\n", jpegPath); + } + + There is no guarantee that this call will be made on any particular thread. +*/ +- (void) cameravideoTookPictureHires:(id)sender userData:(void *)data jpegData:(NSData *)jpegData; +@end + +typedef void (^CameraVideoStartAsyncCompletionBlock)(void); + +extern NSString *const CameraVideoiOSDeviceiPhone; // "iPhone" +extern NSString *const CameraVideoiOSDeviceiPhone3G; // "iPhone 3G" +extern NSString *const CameraVideoiOSDeviceiPhone3GS; // "iPhone 3GS" +extern NSString *const CameraVideoiOSDeviceiPhone4; // "iPhone 4" +extern NSString *const CameraVideoiOSDeviceiPhone4S; // "iPhone 4S" +extern NSString *const CameraVideoiOSDeviceiPhone5; // "iPhone 5" +extern NSString *const CameraVideoiOSDeviceiPhone5s; // "iPhone 5s" +extern NSString *const CameraVideoiOSDeviceiPhone5c; // "iPhone 5c" +extern NSString *const CameraVideoiOSDeviceiPhone6; // "iPhone 6" +extern NSString *const CameraVideoiOSDeviceiPhone6Plus; // "iPhone 6 Plus" +extern NSString *const CameraVideoiOSDeviceiPhone6S; // "iPhone 6S" +extern NSString *const CameraVideoiOSDeviceiPhone6SPlus; // "iPhone 6S Plus" +extern NSString *const CameraVideoiOSDeviceiPodTouch4; // "iPod Touch (4th Generation)" +extern NSString *const CameraVideoiOSDeviceiPodTouch5; // "iPod Touch (5th Generation)" +extern NSString *const CameraVideoiOSDeviceiPad2; // "iPad 2" +extern NSString *const CameraVideoiOSDeviceiPad3; // "iPad (3rd generation)" +extern NSString *const CameraVideoiOSDeviceiPad4; // "iPad (4th generation)" +extern NSString *const CameraVideoiOSDeviceiPadAir; // "iPad Air" +extern NSString *const CameraVideoiOSDeviceiPadAir2; // "iPad Air 2" +extern NSString *const CameraVideoiOSDeviceiPadMini; // "iPad mini" +extern NSString *const CameraVideoiOSDeviceiPadMini2; // "iPad mini (2nd generation)" +extern NSString *const CameraVideoiOSDeviceiPadMini3; // "iPad mini (3rd generation)" +extern NSString *const CameraVideoiOSDeviceiPadMini4; // "iPad mini (4th generation)" +extern NSString *const CameraVideoiOSDeviceiPhoneX; // "iPhone (Unknown model)" +extern NSString *const CameraVideoiOSDeviceiPodX; // "iPod (Unknown model)" +extern NSString *const CameraVideoiOSDeviceiPadX; // "iPad (Unknown model)" +extern NSString *const CameraVideoiOSDeviceAppleTVX; // "Apple TV (Unknown model)" + +@class CameraVideo; + +@interface CameraVideo : NSObject + +- (id) init; + +@property(readonly) NSString *iOSDevice; + +/* + Set or get the video image quality/size. + + Attempts to change this property while (running == TRUE) will be ignored. + + Acceptable values: + AVCaptureSessionPresetHigh // iPhone 3G: 400x304. + // iPhone 3GS: 640x480. + // iPhone 4/iPod touch 4G/iPad 2: rear 1280x720, front 640x480. + // iPhone 4S and later, iPad (3rd generation): rear 1920x1080, front 640x480. + // iPhone (4th generation), iPad Air, iPad Mini, iPad Mini (2nd generation): rear 1920x1080, front 1280x720 + // iPhone 5, 5c, 5s: rear 1920x1080, front 1280x720. + AVCaptureSessionPresetMedium // iPhone 3G: 400x304 + // iPhone 3GS/iPhone 4/iPod touch 4G/iPad 2: 480x360 + AVCaptureSessionPresetLow // iPhone 3G/iPhone 3GS/iPhone 4/iPod touch 4G/iPad 2: 192x144. + AVCaptureSessionPreset640x480 // iPhone 3G: not supported. iPhone 3GS/iPhone 4/iPod touch 4G/iPad 2:640x480. + AVCaptureSessionPreset1280x720 // iPhone 3G/3GS: not supported. iPhone 4/iPod touch 4G/iPad 2:1280x720. + AVCaptureSessionPreset352x288 // iOS 5.0-only, iPhone 3GS and later. + AVCaptureSessionPreset1920x1080 // iOS 5.0-only, iPhone 4S and later, iPad (3rd generation) and later. + Default value is AVCaptureSessionPresetMedium. + + N.B. 1920x1080 and 1280x720 are 16:9 aspect ratio. + 640x480, 480x360, 192x144 are 4:3 aspect ratio. + + */ +@property(nonatomic, assign) NSString *captureSessionPreset; + +/* + Set or get the video device position. + + Attempts to change this property while (running == TRUE) will be ignored. + + Acceptable values: + AVCaptureDevicePositionBack + AVCaptureDevicePositionFront + Default value is AVCaptureDevicePositionBack. + */ +@property(nonatomic) AVCaptureDevicePosition captureDevicePosition; + +/* + Set or get the video image pixel format. + + Attempts to change this property while (running == TRUE) will be ignored. + + Acceptable values: + kCVPixelFormatType_32BGRA (Default.) + kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange + kCVPixelFormatType_420YpCbCr8BiPlanarFullRange (Recommended for iPhone 3GS, 4 and later.) + kCVPixelFormatType_422YpCbCr8 (Recommended for iPhone 3G) + */ +@property(nonatomic) OSType pixelFormat; + +// Starts capture from camera and waits until the first frame has +// been received. Then sets 'running' and returns to caller. +// Note that since this runs the runloop, it may deadlock if +// a runloop task is invoked which waits on this this thread. +// It is recommended to use -startAsync: instead. +// In cases of error, 'running' will not be set on return. +- (void) start; + +// Starts capture from camera, sets 'running' and returns to caller +// immediately. Once the first frame has been received, invokes +// 'completion' on main queue. +// In cases of error, 'running' will not be set on return. +- (void) startAsync:(CameraVideoStartAsyncCompletionBlock)completion; + +// Set once -start or -startAsync: has been called successfully. +@property(nonatomic, readonly) BOOL running; +@property(nonatomic) BOOL pause; + +// The delegate which gets call each time a new frame is available, and its userdata. +// See discussion of CameraVideoTookPictureDelegate above. +@property(nonatomic, assign) id tookPictureDelegate; +@property(nonatomic, assign) void *tookPictureDelegateUserData; + +// These values are valid only once the first frame has been received. +// When invalid, they return 0. +// When a multi-planar format is in use, these are the same as calling +// -widthOfPlane:0, -heightOfPlane:0 or -bytesPerRowOfPlane:0. +@property(nonatomic, readonly) size_t width; +@property(nonatomic, readonly) size_t height; +@property(nonatomic, readonly) size_t bytesPerRow; + +@property(nonatomic, readonly) size_t planeCount; // 0 for non-planar formats, or number of planes (will be 2 for kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange and kCVPixelFormatType_420YpCbCr8BiPlanarFullRange (iPhone 4 and later). +- (size_t)widthOfPlane:(unsigned int)plane; +- (size_t)heightOfPlane:(unsigned int)plane; +- (size_t)bytesPerRowOfPlane:(unsigned int)plane; + +@property(nonatomic) BOOL flipV; +@property(nonatomic) BOOL flipH; + +// Invoke this method to request the capture of a high resolution photo from the video +// stream. If successful, the CameraVideoTookPictureDelegate delegate protocol +// method -cameravideoTookPictureHires:userData:jpegData: will be invoked, so make +// sure you've set the delegate before invocation. +- (void) takePhoto; +// You can also do the same thing, just from a notification with this method. +- (void) takePhotoViaNotification:(NSNotification *)notification; + +// If set, when the next frame arrives it will be saved to the user's camera roll. +// Only supported when using 32-bit RGB pixel formats, e.g. pixelFormat = kCVPixelFormatType_32BGRA. +@property BOOL willSaveNextFrame; + +// Sets focus mode. When mode == AVCaptureFocusModeAutoFocus, then coords must be a +// valid 2D coordinate in pixels, with 0,0 at the top-left of the frame where the frame +// is considered upright when the device is held in landscape mode with the home button on the right. +// Note that this DOES NOT give a visual indication of the focus point; that is up to the +// caller to display, should he or she wish to. +- (BOOL) setFocus:(AVCaptureFocusMode)mode atPixelCoords:(CGPoint)coords; + +// Get a pointer to the most recent frame. +// If timestampOut is non-NULL, it will be filled with a timestamp using the same +// timebase as CVGetCurrentHostTime(). +- (unsigned char *) frameTimestamp:(UInt64 *)timestampOut; + +// Get a pointer to the most recent only if it is newer than 'timestamp'. +// Otherwise returns NULL. +// If timestampOut is non-NULL, it will be filled with a timestamp using the same +// timebase as CVGetCurrentHostTime(). +- (unsigned char *) frameTimestamp:(UInt64 *)timestampOut ifNewerThanTimestamp:(UInt64)timestamp; + +- (BOOL) framePlanes:(unsigned char **)bufDataPtrs count:(size_t)count timestamp:(UInt64 *)timestampOut; +- (BOOL) framePlanes:(unsigned char **)bufDataPtrs count:(size_t)count timestamp:(UInt64 *)timestampOut ifNewerThanTimestamp:(UInt64)timestamp; +@property(nonatomic, readonly) UInt64 timestampsPerSecond; + +// If set, callbacks on the delegate method -cameraVideoTookPicture:userData: will +// be made on a serial queue not necessarily attached to the main thread. +// Defaults to FALSE, i.e. callbacks are on the main thread. This allows OpenGL +// operations, which should normally be on the main thread, to be called during the callback. +// Changing this variable after calling -start will not take effect until -start is next called. +@property(nonatomic) BOOL multithreaded; + +- (void) stop; +- (void) dealloc; + + + + + + +@end \ No newline at end of file diff --git a/libs/include/AR/sys/MovieVideo.h b/libs/include/AR/sys/MovieVideo.h new file mode 100755 index 0000000..c5d1aa4 --- /dev/null +++ b/libs/include/AR/sys/MovieVideo.h @@ -0,0 +1,91 @@ +/* + * MovieVideo.h + * ARToolKit5 + * + * This file is part of ARToolKit. + * + * ARToolKit is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ARToolKit is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ARToolKit. If not, see . + * + * As a special exception, the copyright holders of this library give you + * permission to link this library with independent modules to produce an + * executable, regardless of the license terms of these independent modules, and to + * copy and distribute the resulting executable under terms of your choice, + * provided that you also meet, for each linked independent module, the terms and + * conditions of the license of that module. An independent module is a module + * which is neither derived from nor based on this library. If you modify this + * library, you may extend this exception to your version of the library, but you + * are not obligated to do so. If you do not wish to do so, delete this exception + * statement from your version. + * + * Copyright 2015 Daqri, LLC. + * Copyright 2010-2015 ARToolworks, Inc. + * + * Author(s): Philip Lamb + * + */ + +#import + +#import // AR_PIXEL_FORMAT + +// Notifications. +extern NSString *const MovieVideoMediaLoadedNofication; +extern NSString *const MovieVideoPlaybackEndedNofication; + +@interface MovieVideo : NSObject + +// +// Options for configuration string 'conf'. +// +// -width=w Set width of buffer pointed to by bufDataPtr to w. Default is actual width of video. +// -height=h Set height of buffer pointed to by bufDataPtr to h. Default is actual height of video. +// -pixelformat=pppp Format for pixels pointed to by bufDataPtr. pppp is either 4 character type, or unsigned 32-bit integer, corresponding to appropriate AVFoundation type. Default is 'BGRA'. Another common format is '420v'. +// -[no]fliph If -fliph, flips incoming video frames horizontally. Default is -nofliph. +// -[no]flipv If -flipv, flips incoming video frames vertically. Default is -noflipv. +// -[no]loop If -loop, video will loop back to beginning when end is reached. Default is -noloop. +// -[no]fill If -fill, video will be proportionally resized from the centre to fill the buffer. If -nofill, video will be fitted inside buffer, and may be letter-boxed or pillar-boxed. Default is -nofill. +// -[no]1to1 If -1to1, video will be shown inside buffer at original side (may be cropped or displayed with a border). Default is -no1to1. +// -[no]stretch If -stretch, video will be stretched to fill the buffer. Default is -nostretch. +// -[no]mute If -mute, any audio in the movie file will be ignored. Default is -nomute. +// -[no]singlebuffer If -singlebuffer, video frames will be single buffered (may produce tearing). Default is -nosinglebuffer. +// -[no]pause If -pause, video will be paused when first loaded. Default is -nopause. +// -[no]alpha Hint that the video contains an alpha channel. Default is -noalpha. +// -transparent=hhhhhh Transparent colour, expressed as an RGB hex triplet (e.g. ff0000 for red). +// -chromakey=min,max Perform chroma-keying on video. Chroma values must be expressed as minimum and maximum hue angles 'min' and 'max' in range [0-360), separated by a comma. +// + + +-(id) initWithURL:(NSURL *)url config:(char *)conf; +-(bool) start; +-(unsigned char *)getFrame; +-(void) stop; + +@property(nonatomic, getter=isPaused) BOOL paused; +@property(nonatomic, readonly, getter=isLoaded) BOOL loaded; +@property(readonly) NSInteger contentWidth; +@property(readonly) NSInteger contentHeight; +@property(nonatomic, readonly) AR_PIXEL_FORMAT ARPixelFormat; +@property(readonly) OSType pixFormat; +@property(readonly) size_t bufWidth; +@property(readonly) size_t bufHeight; +@property(readonly) size_t bufRowBytes; +@property(nonatomic, readonly) unsigned char *bufDataPtr; + +@property(nonatomic, readonly) BOOL transparent; +-(BOOL) transparencyByTransparentRGBA:(uint32_t *)rgba; +-(void) setTransparencyByTransparent:(BOOL)on RGBA:(uint32_t)rgba; +-(BOOL) transparencyByChromaKeyHueMinAngle:(float *)hueMinAngle hueMaxAngle:(float *)hueMaxAngle; +-(void) setTransparencyByChromaKey:(BOOL)on hueMinAngle:(float)hueMinAngle hueMaxAngle:(float)hueMaxAngle; + +@end diff --git a/libs/include/AR/sys/WindowsMediaCapture.h b/libs/include/AR/sys/WindowsMediaCapture.h new file mode 100755 index 0000000..a65440b --- /dev/null +++ b/libs/include/AR/sys/WindowsMediaCapture.h @@ -0,0 +1,115 @@ +/* + * WindowsMediaCapture.h + * ARToolKit5 + * + * This file is part of ARToolKit. + * + * ARToolKit is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ARToolKit is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ARToolKit. If not, see . + * + * As a special exception, the copyright holders of this library give you + * permission to link this library with independent modules to produce an + * executable, regardless of the license terms of these independent modules, and to + * copy and distribute the resulting executable under terms of your choice, + * provided that you also meet, for each linked independent module, the terms and + * conditions of the license of that module. An independent module is a module + * which is neither derived from nor based on this library. If you modify this + * library, you may extend this exception to your version of the library, but you + * are not obligated to do so. If you do not wish to do so, delete this exception + * statement from your version. + * + * Copyright 2015 Daqri, LLC. + * Copyright 2014-2015 ARToolworks, Inc. + * + * Author(s): Philip Lamb + * + */ + +#pragma once + +#include + +#include +#include +#include +#include +#include +#include +#include "CaptureFrameGrabber/CaptureFrameGrabber.h" + +class WindowsMediaCapture +{ + +public: + WindowsMediaCapture(void)/* : m_stopLockCondVar {}*/; + virtual ~WindowsMediaCapture(void); + + // Setup/tear down functions + bool StartCapture(int width, + int height, + Platform::String^ pixelFormat = Windows::Media::MediaProperties::MediaEncodingSubtypes::Rgb24, // Raw formats: Rgb24, Rgb32, Nv12, Argb32, Bgra8, Yv12, Yuy2, Iyuv + int preferredDeviceIndex = 0, + Windows::Devices::Enumeration::Panel preferredLocation = Windows::Devices::Enumeration::Panel::Unknown, + void (*errorCallback)(void *) = NULL, + void *errorCallbackUserdata = NULL + ); + bool Capturing() const; // Returns true if between StartCapture() and StopCapture(). + uint8_t *GetFrame(); // Returns NULL if no new frame available, or pointer to frame buffer if new frame is available. Dimensions of buffer are width()*height()*Bpp(). If non-NULL buffer returned, then any previous non-NULL buffer is invalidated. + void StopCapture(); + + int width() const; + int height() const; + int Bpp() const; + bool flipV() const; + void setFlipV(bool flag); + + Windows::Devices::Enumeration::Panel deviceLocation() const; + std::string deviceName() const; + void WindowsMediaCapture::showSettings(void); + +private: + //Disable Copy ctor and assignment + WindowsMediaCapture(const WindowsMediaCapture& other) = delete; // Copy constructor not implemented. + auto operator=(const WindowsMediaCapture& other) -> WindowsMediaCapture& = delete; // Copy assignment operator not implemented. + //Disable Move ctor and assignment + WindowsMediaCapture(WindowsMediaCapture&&) = delete; + auto operator=(WindowsMediaCapture&&) -> WindowsMediaCapture& = delete; + + bool initDevices(); + void _GrabFrameAsync(Media::CaptureFrameGrabber^ frameGrabber); + + bool m_started; + int m_width; + int m_height; + int m_Bpp; + bool m_flipV; + Platform::String^ m_pixelFormat; + Platform::Agile m_devices; + Platform::Agile m_mediaCapture; + int m_deviceIndex; + Windows::Devices::Enumeration::Panel m_deviceLocation; + std::string m_deviceName; + ::Media::CaptureFrameGrabber^ m_frameGrabber; + bool m_frameGrabberInited; + long m_frameCountIn; + long m_frameCountOut; + uint8_t *m_buf0; + uint8_t *m_buf1; + int m_bufNext; + std::mutex m_bufLock; + void (*m_errorCallback)(void *); + void *m_errorCallbackUserdata; + bool m_frameGrabberIsDone; + std::mutex m_stopLockMutex; + std::condition_variable m_stopLockCondVar; +}; \ No newline at end of file diff --git a/libs/include/AR/sys/videoAndroid.h b/libs/include/AR/sys/videoAndroid.h new file mode 100755 index 0000000..9dde915 --- /dev/null +++ b/libs/include/AR/sys/videoAndroid.h @@ -0,0 +1,108 @@ +/* + * videoAndroid.h + * ARToolKit5 + * + * This file is part of ARToolKit. + * + * ARToolKit is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ARToolKit is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ARToolKit. If not, see . + * + * As a special exception, the copyright holders of this library give you + * permission to link this library with independent modules to produce an + * executable, regardless of the license terms of these independent modules, and to + * copy and distribute the resulting executable under terms of your choice, + * provided that you also meet, for each linked independent module, the terms and + * conditions of the license of that module. An independent module is a module + * which is neither derived from nor based on this library. If you modify this + * library, you may extend this exception to your version of the library, but you + * are not obligated to do so. If you do not wish to do so, delete this exception + * statement from your version. + * + * Copyright 2015 Daqri, LLC. + * Copyright 2014-2015 ARToolworks, Inc. + * + * Author(s): Philip Lamb + * + */ + +#ifndef AR_VIDEO_ANDROID_H +#define AR_VIDEO_ANDROID_H + +#define AR_VIDEO_ANDROID_ENABLE_NATIVE_CAMERA 0 + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +enum { + AR_VIDEO_PARAM_ANDROID_DEVICEID, // s, readonly +#if !AR_VIDEO_ANDROID_ENABLE_NATIVE_CAMERA + AR_VIDEO_PARAM_ANDROID_WIDTH, // i + AR_VIDEO_PARAM_ANDROID_HEIGHT, // i + AR_VIDEO_PARAM_ANDROID_PIXELFORMAT, // i (cast to AR_PIXEL_FORMAT) +#endif + AR_VIDEO_PARAM_ANDROID_CAMERA_INDEX, // i + AR_VIDEO_PARAM_ANDROID_CAMERA_FACE, // i + AR_VIDEO_PARAM_ANDROID_FOCAL_LENGTH, // d + AR_VIDEO_PARAM_ANDROID_INTERNET_STATE // i +}; + +enum { + AR_VIDEO_ANDROID_CAMERA_FACE_REAR = 0, + AR_VIDEO_ANDROID_CAMERA_FACE_FRONT, +}; + +typedef struct _AR2VideoParamAndroidT AR2VideoParamAndroidT; + +#define AR_VIDEO_ANDROID_FOCAL_LENGTH_DEFAULT 0.3 // Metres. + +// +// At present, videoAndroid provides only some of the usual APIs, and doesn't support frame retrieval. +// Most of the video functionality on Android is handled in separate Android-specific classes. +// For Java (JDK) Android apps, the classes are in ARBaseLib. +// For Native (NDK) Android apps, the classes are in the 'CameraSurface' class (part of the example code). +// + +int ar2VideoDispOptionAndroid ( void ); +AR2VideoParamAndroidT *ar2VideoOpenAndroid ( const char *config ); +int ar2VideoCloseAndroid ( AR2VideoParamAndroidT *vid ); +int ar2VideoGetIdAndroid ( AR2VideoParamAndroidT *vid, ARUint32 *id0, ARUint32 *id1 ); +int ar2VideoGetSizeAndroid ( AR2VideoParamAndroidT *vid, int *x,int *y ); +AR_PIXEL_FORMAT ar2VideoGetPixelFormatAndroid ( AR2VideoParamAndroidT *vid ); + +#if AR_VIDEO_ANDROID_ENABLE_NATIVE_CAMERA +AR2VideoBufferT *ar2VideoGetImageAndroid ( AR2VideoParamAndroidT *vid ); +int ar2VideoCapStartAndroid ( AR2VideoParamAndroidT *vid ); +int ar2VideoCapStartAsyncAndroid ( AR2VideoParamAndroidT *vid, AR_VIDEO_FRAME_READY_CALLBACK callback, void *userdata ); +int ar2VideoCapStopAndroid ( AR2VideoParamAndroidT *vid ); +#endif + +int ar2VideoGetParamiAndroid ( AR2VideoParamAndroidT *vid, int paramName, int *value ); +int ar2VideoSetParamiAndroid ( AR2VideoParamAndroidT *vid, int paramName, int value ); +int ar2VideoGetParamdAndroid ( AR2VideoParamAndroidT *vid, int paramName, double *value ); +int ar2VideoSetParamdAndroid ( AR2VideoParamAndroidT *vid, int paramName, double value ); +int ar2VideoGetParamsAndroid ( AR2VideoParamAndroidT *vid, const int paramName, char **value ); +int ar2VideoSetParamsAndroid ( AR2VideoParamAndroidT *vid, const int paramName, const char *value ); + +//int ar2VideoSetBufferSizeAndroid(AR2VideoParamAndroidT *vid, const int width, const int height); +//int ar2VideoGetBufferSizeAndroid(AR2VideoParamAndroidT *vid, int *width, int *height); + +int ar2VideoGetCParamAsyncAndroid (AR2VideoParamAndroidT *vid, void (*callback)(const ARParam *, void *), void *userdata); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/libs/include/AR/sys/videoDummy.h b/libs/include/AR/sys/videoDummy.h new file mode 100755 index 0000000..115ed4a --- /dev/null +++ b/libs/include/AR/sys/videoDummy.h @@ -0,0 +1,93 @@ +/* + * videoDummy.h + * ARToolKit5 + * + * This file is part of ARToolKit. + * + * ARToolKit is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ARToolKit is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ARToolKit. If not, see . + * + * As a special exception, the copyright holders of this library give you + * permission to link this library with independent modules to produce an + * executable, regardless of the license terms of these independent modules, and to + * copy and distribute the resulting executable under terms of your choice, + * provided that you also meet, for each linked independent module, the terms and + * conditions of the license of that module. An independent module is a module + * which is neither derived from nor based on this library. If you modify this + * library, you may extend this exception to your version of the library, but you + * are not obligated to do so. If you do not wish to do so, delete this exception + * statement from your version. + * + * Copyright 2015 Daqri, LLC. + * Copyright 2004-2015 ARToolworks, Inc. + * + * Author(s): Hirokazu Kato, Philip Lamb + * + */ +/******************************************************* + * + * Author: Hirokazu Kato + * + * kato@sys.im.hiroshima-cu.ac.jp + * + * Revision: 4.4 + * Date: 2004/01/01 + * + *******************************************************/ + +#ifndef AR_VIDEO_DUMMY_H +#define AR_VIDEO_DUMMY_H + + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct { + AR2VideoBufferT buffer; + int width; + int height; + AR_PIXEL_FORMAT format; + int bufWidth; + int bufHeight; +} AR2VideoParamDummyT; + + +int ar2VideoDispOptionDummy ( void ); +AR2VideoParamDummyT *ar2VideoOpenDummy ( const char *config ); +int ar2VideoCloseDummy ( AR2VideoParamDummyT *vid ); +int ar2VideoGetIdDummy ( AR2VideoParamDummyT *vid, ARUint32 *id0, ARUint32 *id1 ); +int ar2VideoGetSizeDummy ( AR2VideoParamDummyT *vid, int *x,int *y ); +AR_PIXEL_FORMAT ar2VideoGetPixelFormatDummy ( AR2VideoParamDummyT *vid ); +AR2VideoBufferT *ar2VideoGetImageDummy ( AR2VideoParamDummyT *vid ); +int ar2VideoCapStartDummy ( AR2VideoParamDummyT *vid ); +int ar2VideoCapStopDummy ( AR2VideoParamDummyT *vid ); + +int ar2VideoGetParamiDummy ( AR2VideoParamDummyT *vid, int paramName, int *value ); +int ar2VideoSetParamiDummy ( AR2VideoParamDummyT *vid, int paramName, int value ); +int ar2VideoGetParamdDummy ( AR2VideoParamDummyT *vid, int paramName, double *value ); +int ar2VideoSetParamdDummy ( AR2VideoParamDummyT *vid, int paramName, double value ); +int ar2VideoGetParamsDummy ( AR2VideoParamDummyT *vid, const int paramName, char **value ); +int ar2VideoSetParamsDummy ( AR2VideoParamDummyT *vid, const int paramName, const char *value ); + +int ar2VideoSetBufferSizeDummy(AR2VideoParamDummyT *vid, const int width, const int height); +int ar2VideoGetBufferSizeDummy(AR2VideoParamDummyT *vid, int *width, int *height); + + +#ifdef __cplusplus +} +#endif +#endif diff --git a/libs/include/AR/sys/videoGStreamer.h b/libs/include/AR/sys/videoGStreamer.h new file mode 100755 index 0000000..57ba201 --- /dev/null +++ b/libs/include/AR/sys/videoGStreamer.h @@ -0,0 +1,73 @@ +/* + * videoGStreamer.h + * ARToolKit5 + * + * Video capture module utilising the GStreamer pipeline for AR Toolkit + * + * This file is part of ARToolKit. + * + * ARToolKit is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ARToolKit is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ARToolKit. If not, see . + * + * As a special exception, the copyright holders of this library give you + * permission to link this library with independent modules to produce an + * executable, regardless of the license terms of these independent modules, and to + * copy and distribute the resulting executable under terms of your choice, + * provided that you also meet, for each linked independent module, the terms and + * conditions of the license of that module. An independent module is a module + * which is neither derived from nor based on this library. If you modify this + * library, you may extend this exception to your version of the library, but you + * are not obligated to do so. If you do not wish to do so, delete this exception + * statement from your version. + * + * Copyright 2015 Daqri, LLC. + * Copyright 2008-2015 ARToolworks, Inc. + * Copyright 2003-2008 Hartmut Seichter + * + * Author(s): Hartmut Seichter, Philip Lamb + * + */ + +#ifndef AR_VIDEO_GSTREAMER_H +#define AR_VIDEO_GSTREAMER_H + + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct _AR2VideoParamGStreamerT AR2VideoParamGStreamerT; + +int ar2VideoDispOptionGStreamer ( void ); +AR2VideoParamGStreamerT *ar2VideoOpenGStreamer ( const char *config_in ); +int ar2VideoCloseGStreamer ( AR2VideoParamGStreamerT *vid ); +int ar2VideoGetIdGStreamer ( AR2VideoParamGStreamerT *vid, ARUint32 *id0, ARUint32 *id1 ); +int ar2VideoGetSizeGStreamer ( AR2VideoParamGStreamerT *vid, int *x,int *y ); +AR_PIXEL_FORMAT ar2VideoGetPixelFormatGStreamer ( AR2VideoParamGStreamerT *vid ); +AR2VideoBufferT *ar2VideoGetImageGStreamer ( AR2VideoParamGStreamerT *vid ); +int ar2VideoCapStartGStreamer ( AR2VideoParamGStreamerT *vid ); +int ar2VideoCapStopGStreamer ( AR2VideoParamGStreamerT *vid ); + +int ar2VideoGetParamiGStreamer ( AR2VideoParamGStreamerT *vid, int paramName, int *value ); +int ar2VideoSetParamiGStreamer ( AR2VideoParamGStreamerT *vid, int paramName, int value ); +int ar2VideoGetParamdGStreamer ( AR2VideoParamGStreamerT *vid, int paramName, double *value ); +int ar2VideoSetParamdGStreamer ( AR2VideoParamGStreamerT *vid, int paramName, double value ); + + +#ifdef __cplusplus +} +#endif +#endif // !AR_VIDEO_GSTREAMER_H diff --git a/libs/include/AR/sys/videoImage.h b/libs/include/AR/sys/videoImage.h new file mode 100755 index 0000000..80f5fd3 --- /dev/null +++ b/libs/include/AR/sys/videoImage.h @@ -0,0 +1,76 @@ +/* + * videoImage.h + * ARToolKit5 + * + * This file is part of ARToolKit. + * + * ARToolKit is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ARToolKit is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ARToolKit. If not, see . + * + * As a special exception, the copyright holders of this library give you + * permission to link this library with independent modules to produce an + * executable, regardless of the license terms of these independent modules, and to + * copy and distribute the resulting executable under terms of your choice, + * provided that you also meet, for each linked independent module, the terms and + * conditions of the license of that module. An independent module is a module + * which is neither derived from nor based on this library. If you modify this + * library, you may extend this exception to your version of the library, but you + * are not obligated to do so. If you do not wish to do so, delete this exception + * statement from your version. + * + * Copyright 2015 Daqri, LLC. + * Copyright 2012-2015 ARToolworks, Inc. + * + * Author(s): Philip Lamb + * + */ + +#ifndef AR_VIDEO_IMAGE_H +#define AR_VIDEO_IMAGE_H + + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct _AR2VideoParamImageT AR2VideoParamImageT; + + +int ar2VideoDispOptionImage ( void ); +AR2VideoParamImageT *ar2VideoOpenImage ( const char *config ); +int ar2VideoCloseImage ( AR2VideoParamImageT *vid ); +int ar2VideoGetIdImage ( AR2VideoParamImageT *vid, ARUint32 *id0, ARUint32 *id1 ); +int ar2VideoGetSizeImage ( AR2VideoParamImageT *vid, int *x,int *y ); +AR_PIXEL_FORMAT ar2VideoGetPixelFormatImage ( AR2VideoParamImageT *vid ); +AR2VideoBufferT *ar2VideoGetImageImage ( AR2VideoParamImageT *vid ); +int ar2VideoCapStartImage ( AR2VideoParamImageT *vid ); +int ar2VideoCapStopImage ( AR2VideoParamImageT *vid ); + +int ar2VideoGetParamiImage ( AR2VideoParamImageT *vid, int paramName, int *value ); +int ar2VideoSetParamiImage ( AR2VideoParamImageT *vid, int paramName, int value ); +int ar2VideoGetParamdImage ( AR2VideoParamImageT *vid, int paramName, double *value ); +int ar2VideoSetParamdImage ( AR2VideoParamImageT *vid, int paramName, double value ); +int ar2VideoGetParamsImage ( AR2VideoParamImageT *vid, const int paramName, char **value ); +int ar2VideoSetParamsImage ( AR2VideoParamImageT *vid, const int paramName, const char *value ); + +int ar2VideoSetBufferSizeImage(AR2VideoParamImageT *vid, const int width, const int height); +int ar2VideoGetBufferSizeImage(AR2VideoParamImageT *vid, int *width, int *height); + + +#ifdef __cplusplus +} +#endif +#endif diff --git a/libs/include/AR/sys/videoLinux1394Cam.h b/libs/include/AR/sys/videoLinux1394Cam.h new file mode 100755 index 0000000..7b74b39 --- /dev/null +++ b/libs/include/AR/sys/videoLinux1394Cam.h @@ -0,0 +1,47 @@ +/* + * videoLinux1394Cam.h + * ARToolKit5 + * + * This file is part of ARToolKit. + * + * ARToolKit is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ARToolKit is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ARToolKit. If not, see . + * + * As a special exception, the copyright holders of this library give you + * permission to link this library with independent modules to produce an + * executable, regardless of the license terms of these independent modules, and to + * copy and distribute the resulting executable under terms of your choice, + * provided that you also meet, for each linked independent module, the terms and + * conditions of the license of that module. An independent module is a module + * which is neither derived from nor based on this library. If you modify this + * library, you may extend this exception to your version of the library, but you + * are not obligated to do so. If you do not wish to do so, delete this exception + * statement from your version. + * + * Copyright 2015 Daqri, LLC. + * Copyright 2009-2015 ARToolworks, Inc. + * + * Author(s): Hirokazu Kato + * + */ + +#ifndef AR_VIDEO_LINUX_1394CAM_H +#define AR_VIDEO_LINUX_1394CAM_H + +#ifdef AR_INPUT_1394CAM_USE_LIBDC1394_V2 +#include +#else +#include +#endif + +#endif diff --git a/libs/include/AR/sys/videoLinux1394CamV1.h b/libs/include/AR/sys/videoLinux1394CamV1.h new file mode 100755 index 0000000..334847b --- /dev/null +++ b/libs/include/AR/sys/videoLinux1394CamV1.h @@ -0,0 +1,135 @@ +/* + * videoLinux1394CamV1.h + * ARToolKit5 + * + * This file is part of ARToolKit. + * + * ARToolKit is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ARToolKit is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ARToolKit. If not, see . + * + * As a special exception, the copyright holders of this library give you + * permission to link this library with independent modules to produce an + * executable, regardless of the license terms of these independent modules, and to + * copy and distribute the resulting executable under terms of your choice, + * provided that you also meet, for each linked independent module, the terms and + * conditions of the license of that module. An independent module is a module + * which is neither derived from nor based on this library. If you modify this + * library, you may extend this exception to your version of the library, but you + * are not obligated to do so. If you do not wish to do so, delete this exception + * statement from your version. + * + * Copyright 2015 Daqri, LLC. + * Copyright 2004-2015 ARToolworks, Inc. + * + * Author(s): Hirokazu Kato + * + */ +/******************************************************* + * + * Author: Hirokazu Kato + * + * kato@sys.im.hiroshima-cu.ac.jp + * + * Revision: 2.1 + * Date: 2004/01/01 + * + *******************************************************/ + +#ifndef AR_VIDEO_LINUX_1394CAM1_H +#define AR_VIDEO_LINUX_1394CAM1_H + +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define AR2VIDEO_1394_PORT_MAX 4 + + +#define AR2VIDEO_1394_STATUS_IDLE 0 +#define AR2VIDEO_1394_STATUS_RUN 1 +#define AR2VIDEO_1394_STATUS_STOP 2 + +typedef struct { + AR2VideoBufferT in; + AR2VideoBufferT wait; + AR2VideoBufferT out; + pthread_mutex_t mutex; +} AR2VideoBuffer1394T; + +typedef struct { + int node; + int mode; + int rate; + int speed; + int format7; + int debug; + + int port; + quadlet_t euid[2]; + int channel; + int dma_channel; + int format; + int dma_buf_num; + int drop_frames; + int int_mode; + int int_rate; + int int_speed; + int status; + + int internal_id; + dc1394_feature_set features; + dc1394_cameracapture camera; + pthread_t capture; + AR2VideoBuffer1394T buffer; +} AR2VideoParam1394T; + + +int ar2VideoDispOption1394 ( void ); +AR2VideoParam1394T *ar2VideoOpen1394 ( const char *config ); +int ar2VideoClose1394 ( AR2VideoParam1394T *vid ); +int ar2VideoGetId1394 ( AR2VideoParam1394T *vid, ARUint32 *id0, ARUint32 *id1 ); +int ar2VideoGetSize1394 ( AR2VideoParam1394T *vid, int *x,int *y ); +AR_PIXEL_FORMAT ar2VideoGetPixelFormat1394 ( AR2VideoParam1394T *vid ); +AR2VideoBufferT *ar2VideoGetImage1394 ( AR2VideoParam1394T *vid ); +int ar2VideoCapStart1394 ( AR2VideoParam1394T *vid ); +int ar2VideoCapStop1394 ( AR2VideoParam1394T *vid ); + +int ar2VideoGetParami1394 ( AR2VideoParam1394T *vid, int paramName, int *value ); +int ar2VideoSetParami1394 ( AR2VideoParam1394T *vid, int paramName, int value ); +int ar2VideoGetParamd1394 ( AR2VideoParam1394T *vid, int paramName, double *value ); +int ar2VideoSetParamd1394 ( AR2VideoParam1394T *vid, int paramName, double value ); + +int ar2VideoGetValue1394 ( AR2VideoParam1394T *vid, int paramName, int *value ); +int ar2VideoSetValue1394 ( AR2VideoParam1394T *vid, int paramName, int value ); +int ar2VideoGetAutoOn1394 ( AR2VideoParam1394T *vid, int paramName, int *value ); +int ar2VideoSetAutoOn1394 ( AR2VideoParam1394T *vid, int paramName, int value ); +int ar2VideoGetFeatureOn1394 ( AR2VideoParam1394T *vid, int paramName, int *value ); +int ar2VideoSetFeatureOn1394 ( AR2VideoParam1394T *vid, int paramName, int value ); +int ar2VideoGetMaxValue1394 ( AR2VideoParam1394T *vid, int paramName, int *value ); +int ar2VideoGetMinValue1394 ( AR2VideoParam1394T *vid, int paramName, int *value ); + +int ar2VideoSaveParam1394 ( AR2VideoParam1394T *vid, char *filename ); +int ar2VideoLoadParam1394 ( AR2VideoParam1394T *vid, char *filename ); +#ifdef __cplusplus +} +#endif +#endif diff --git a/libs/include/AR/sys/videoLinux1394CamV2.h b/libs/include/AR/sys/videoLinux1394CamV2.h new file mode 100755 index 0000000..088c7fe --- /dev/null +++ b/libs/include/AR/sys/videoLinux1394CamV2.h @@ -0,0 +1,125 @@ +/* + * videoLinux1394CamV2.h + * ARToolKit5 + * + * This file is part of ARToolKit. + * + * ARToolKit is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ARToolKit is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ARToolKit. If not, see . + * + * As a special exception, the copyright holders of this library give you + * permission to link this library with independent modules to produce an + * executable, regardless of the license terms of these independent modules, and to + * copy and distribute the resulting executable under terms of your choice, + * provided that you also meet, for each linked independent module, the terms and + * conditions of the license of that module. An independent module is a module + * which is neither derived from nor based on this library. If you modify this + * library, you may extend this exception to your version of the library, but you + * are not obligated to do so. If you do not wish to do so, delete this exception + * statement from your version. + * + * Copyright 2015 Daqri, LLC. + * Copyright 2009-2015 ARToolworks, Inc. + * + * Author(s): Hirokazu Kato + * + */ + +#ifndef AR_VIDEO_LINUX_1394CAM2_H +#define AR_VIDEO_LINUX_1394CAM2_H + +#include +//#include +#include +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + + +#define AR2VIDEO_1394_STATUS_IDLE 0 +#define AR2VIDEO_1394_STATUS_RUN 1 +#define AR2VIDEO_1394_STATUS_STOP 2 + +typedef struct { + AR2VideoBufferT in; + AR2VideoBufferT wait; + AR2VideoBufferT out; + pthread_mutex_t mutex; +} AR2VideoBuffer1394T; + +typedef struct { + int mode; + int rate; + int speed; + int format7; + int debug; + + uint32_t guid[2]; + int width; + int height; + int bits; + int dma_buf_num; + int internal_id; + int status; + dc1394camera_t *camera; + dc1394video_mode_t int_mode; + dc1394video_modes_t modes; + dc1394framerate_t int_rate; + dc1394framerates_t rates; + dc1394speed_t int_speed; + dc1394operation_mode_t int_opmode; + dc1394featureset_t features; + pthread_t capture; + AR2VideoBuffer1394T buffer; +} AR2VideoParam1394T; + + +int ar2VideoDispOption1394 ( void ); +AR2VideoParam1394T *ar2VideoOpen1394 ( const char *config ); +int ar2VideoClose1394 ( AR2VideoParam1394T *vid ); +int ar2VideoGetId1394 ( AR2VideoParam1394T *vid, ARUint32 *id0, ARUint32 *id1 ); +int ar2VideoGetSize1394 ( AR2VideoParam1394T *vid, int *x,int *y ); +AR_PIXEL_FORMAT ar2VideoGetPixelFormat1394 ( AR2VideoParam1394T *vid ); +AR2VideoBufferT *ar2VideoGetImage1394 ( AR2VideoParam1394T *vid ); +int ar2VideoCapStart1394 ( AR2VideoParam1394T *vid ); +int ar2VideoCapStop1394 ( AR2VideoParam1394T *vid ); + +int ar2VideoGetParami1394 ( AR2VideoParam1394T *vid, int paramName, int *value ); +int ar2VideoSetParami1394 ( AR2VideoParam1394T *vid, int paramName, int value ); +int ar2VideoGetParamd1394 ( AR2VideoParam1394T *vid, int paramName, double *value ); +int ar2VideoSetParamd1394 ( AR2VideoParam1394T *vid, int paramName, double value ); + +int ar2VideoGetValue1394 ( AR2VideoParam1394T *vid, int paramName, int *value ); +int ar2VideoSetValue1394 ( AR2VideoParam1394T *vid, int paramName, int value ); +int ar2VideoGetAutoOn1394 ( AR2VideoParam1394T *vid, int paramName, int *value ); +int ar2VideoSetAutoOn1394 ( AR2VideoParam1394T *vid, int paramName, int value ); +int ar2VideoGetFeatureOn1394 ( AR2VideoParam1394T *vid, int paramName, int *value ); +int ar2VideoSetFeatureOn1394 ( AR2VideoParam1394T *vid, int paramName, int value ); +int ar2VideoGetMaxValue1394 ( AR2VideoParam1394T *vid, int paramName, int *value ); +int ar2VideoGetMinValue1394 ( AR2VideoParam1394T *vid, int paramName, int *value ); + +int ar2VideoGetAbsValue1394 ( AR2VideoParam1394T *vid, int paramName, ARdouble *value ); +int ar2VideoSetAbsValue1394 ( AR2VideoParam1394T *vid, int paramName, ARdouble value ); +int ar2VideoGetAbsMaxValue1394 ( AR2VideoParam1394T *vid, int paramName, ARdouble *value ); +int ar2VideoGetAbsMinValue1394 ( AR2VideoParam1394T *vid, int paramName, ARdouble *value ); + +int ar2VideoSaveParam1394 ( AR2VideoParam1394T *vid, char *filename ); +int ar2VideoLoadParam1394 ( AR2VideoParam1394T *vid, char *filename ); +#ifdef __cplusplus +} +#endif +#endif diff --git a/libs/include/AR/sys/videoLinuxV4L.h b/libs/include/AR/sys/videoLinuxV4L.h new file mode 100755 index 0000000..db5b592 --- /dev/null +++ b/libs/include/AR/sys/videoLinuxV4L.h @@ -0,0 +1,118 @@ +/* + * videoLinuxV4L.h + * ARToolKit5 + * + * This file is part of ARToolKit. + * + * ARToolKit is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ARToolKit is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ARToolKit. If not, see . + * + * As a special exception, the copyright holders of this library give you + * permission to link this library with independent modules to produce an + * executable, regardless of the license terms of these independent modules, and to + * copy and distribute the resulting executable under terms of your choice, + * provided that you also meet, for each linked independent module, the terms and + * conditions of the license of that module. An independent module is a module + * which is neither derived from nor based on this library. If you modify this + * library, you may extend this exception to your version of the library, but you + * are not obligated to do so. If you do not wish to do so, delete this exception + * statement from your version. + * + * Copyright 2015 Daqri, LLC. + * Copyright 2004-2015 ARToolworks, Inc. + * + * Author(s): Hirokazu Kato + * + */ +/******************************************************* + * + * Author: Hirokazu Kato + * + * kato@sys.im.hiroshima-cu.ac.jp + * + * Revision: 5.4 + * Date: 2004/01/01 + * + *******************************************************/ + +#ifndef AR_VIDEO_LINUX_V4L_H +#define AR_VIDEO_LINUX_V4L_H + +#include +#include +//#include +#include +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define AR2VIDEO_V4L_STATUS_IDLE 0 +#define AR2VIDEO_V4L_STATUS_RUN 1 +#define AR2VIDEO_V4L_STATUS_STOP 2 + +typedef struct { + AR2VideoBufferT in; + AR2VideoBufferT wait; + AR2VideoBufferT out; + pthread_mutex_t mutex; +} AR2VideoBufferV4LT; + +typedef struct { + char dev[256]; + int width; + int height; + int channel; + int mode; + AR_PIXEL_FORMAT format; + int debug; + double contrast; + double brightness; + double hue; + double whiteness; + double color; + + int fd; + int status; + int video_cont_num; + ARUint8 *map; + struct video_mbuf vm; + struct video_mmap vmm; + pthread_t capture; + AR2VideoBufferV4LT buffer; +} AR2VideoParamV4LT; + + +int ar2VideoDispOptionV4L ( void ); +AR2VideoParamV4LT *ar2VideoOpenV4L ( const char *config ); +int ar2VideoCloseV4L ( AR2VideoParamV4LT *vid ); +int ar2VideoGetIdV4L ( AR2VideoParamV4LT *vid, ARUint32 *id0, ARUint32 *id1 ); +int ar2VideoGetSizeV4L ( AR2VideoParamV4LT *vid, int *x,int *y ); +AR_PIXEL_FORMAT ar2VideoGetPixelFormatV4L ( AR2VideoParamV4LT *vid ); +AR2VideoBufferT *ar2VideoGetImageV4L ( AR2VideoParamV4LT *vid ); +int ar2VideoCapStartV4L ( AR2VideoParamV4LT *vid ); +int ar2VideoCapStopV4L ( AR2VideoParamV4LT *vid ); + +int ar2VideoGetParamiV4L ( AR2VideoParamV4LT *vid, int paramName, int *value ); +int ar2VideoSetParamiV4L ( AR2VideoParamV4LT *vid, int paramName, int value ); +int ar2VideoGetParamdV4L ( AR2VideoParamV4LT *vid, int paramName, double *value ); +int ar2VideoSetParamdV4L ( AR2VideoParamV4LT *vid, int paramName, double value ); + + +#ifdef __cplusplus +} +#endif +#endif diff --git a/libs/include/AR/sys/videoQuickTime.h b/libs/include/AR/sys/videoQuickTime.h new file mode 100755 index 0000000..1af1bad --- /dev/null +++ b/libs/include/AR/sys/videoQuickTime.h @@ -0,0 +1,92 @@ +/* + * videoQuickTime.h + * ARToolKit5 + * + * This file is part of ARToolKit. + * + * ARToolKit is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ARToolKit is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ARToolKit. If not, see . + * + * As a special exception, the copyright holders of this library give you + * permission to link this library with independent modules to produce an + * executable, regardless of the license terms of these independent modules, and to + * copy and distribute the resulting executable under terms of your choice, + * provided that you also meet, for each linked independent module, the terms and + * conditions of the license of that module. An independent module is a module + * which is neither derived from nor based on this library. If you modify this + * library, you may extend this exception to your version of the library, but you + * are not obligated to do so. If you do not wish to do so, delete this exception + * statement from your version. + * + * Copyright 2015 Daqri, LLC. + * Copyright 2002-2015 ARToolworks, Inc. + * + * Author(s): Kiyoshi Kiyokawa, Hirokazu Kato, Philip Lamb + * + * Rev Date Who Changes + * 1.1.0 2003-09-09 PRL Based on Apple "Son of MungGrab" sample code for QuickTime 6. + * Added config option "-fps" to superimpose frame counter on video. + * Returns aligned data in ARGB pixel format. + * 1.2.0 2004-04-28 PRL Now one thread per video source. Versions of QuickTime + * prior to 6.4 are NOT thread safe, and with these earlier + * versions, QuickTime toolbox access will be serialised. + * 1.2.1 2004-06-28 PRL Support for 2vuy and yuvs pixel formats. + * 1.3.0 2004-07-13 PRL Code from Daniel Heckenberg to directly access vDig. + * 1.3.1 2004-12-07 PRL Added config option "-pixelformat=" to support pixel format + * specification at runtime, with default determined at compile time. + * 1.4.0 2005-03-08 PRL Video input settings now saved and restored. + * 1.4.1 2005-03-15 PRL QuickTime 6.4 or newer is now required by default. In order + * to allow earlier versions, AR_VIDEO_SUPPORT_OLD_QUICKTIME must + * be uncommented at compile time. + * + */ +/* + * Video capture subrutine for Linux/libdc1394 devices + * Author: Kiyoshi Kiyokawa ( kiyo@crl.go.jp ) + * Hirokazu Kato ( kato@sys.im.hiroshima-cu.ac.jp ) + * + * Revision: 1.0 Date: 2002/01/01 + * + */ + +#ifndef AR_VIDEO_QUICKTIME_H +#define AR_VIDEO_QUICKTIME_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct _AR2VideoParamQuickTimeT AR2VideoParamQuickTimeT; + +AR_DLL_API int ar2VideoDispOptionQuickTime ( void ); +AR_DLL_API AR2VideoParamQuickTimeT *ar2VideoOpenQuickTime ( const char *config ); +AR_DLL_API int ar2VideoCloseQuickTime ( AR2VideoParamQuickTimeT *vid ); +AR_DLL_API int ar2VideoGetIdQuickTime ( AR2VideoParamQuickTimeT *vid, ARUint32 *id0, ARUint32 *id1 ); +AR_DLL_API int ar2VideoGetSizeQuickTime ( AR2VideoParamQuickTimeT *vid, int *x,int *y ); +AR_DLL_API AR_PIXEL_FORMAT ar2VideoGetPixelFormatQuickTime ( AR2VideoParamQuickTimeT *vid ); +AR_DLL_API AR2VideoBufferT *ar2VideoGetImageQuickTime ( AR2VideoParamQuickTimeT *vid ); +AR_DLL_API int ar2VideoCapStartQuickTime ( AR2VideoParamQuickTimeT *vid ); +AR_DLL_API int ar2VideoCapStopQuickTime ( AR2VideoParamQuickTimeT *vid ); +AR_DLL_API int ar2VideoGetParamiQuickTime ( AR2VideoParamQuickTimeT *vid, int paramName, int *value ); +AR_DLL_API int ar2VideoSetParamiQuickTime ( AR2VideoParamQuickTimeT *vid, int paramName, int value ); +AR_DLL_API int ar2VideoGetParamdQuickTime ( AR2VideoParamQuickTimeT *vid, int paramName, double *value ); +AR_DLL_API int ar2VideoSetParamdQuickTime ( AR2VideoParamQuickTimeT *vid, int paramName, double value ); + +AR_DLL_API AR_VIDEO_QUICKTIME_MOVIE_t ar2VideoGetMovieQuickTime( AR2VideoParamQuickTimeT *vid ); + +#ifdef __cplusplus +} +#endif +#endif // AR_VIDEO_QUICKTIME_H diff --git a/libs/include/AR/sys/videoQuickTime7.h b/libs/include/AR/sys/videoQuickTime7.h new file mode 100755 index 0000000..3caa8d9 --- /dev/null +++ b/libs/include/AR/sys/videoQuickTime7.h @@ -0,0 +1,91 @@ +/* + * videoQuickTime7.h + * ARToolKit5 + * + * This file is part of ARToolKit. + * + * ARToolKit is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ARToolKit is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ARToolKit. If not, see . + * + * As a special exception, the copyright holders of this library give you + * permission to link this library with independent modules to produce an + * executable, regardless of the license terms of these independent modules, and to + * copy and distribute the resulting executable under terms of your choice, + * provided that you also meet, for each linked independent module, the terms and + * conditions of the license of that module. An independent module is a module + * which is neither derived from nor based on this library. If you modify this + * library, you may extend this exception to your version of the library, but you + * are not obligated to do so. If you do not wish to do so, delete this exception + * statement from your version. + * + * Copyright 2015 Daqri, LLC. + * Copyright 2010-2015 ARToolworks, Inc. + * + * Author(s): Philip Lamb + * + * Rev Date Who Changes + * 1.0.0 2010-07-01 PRL Written. + * + */ + +#ifndef AR_VIDEO_QUICKTIME7_H +#define AR_VIDEO_QUICKTIME7_H + + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + + + +typedef struct _AR2VideoParamQuickTime7T AR2VideoParamQuickTime7T; + + +int ar2VideoDispOptionQuickTime7 ( void ); +AR2VideoParamQuickTime7T *ar2VideoOpenQuickTime7 ( const char *config ); +int ar2VideoCloseQuickTime7 ( AR2VideoParamQuickTime7T *vid ); +int ar2VideoGetIdQuickTime7 ( AR2VideoParamQuickTime7T *vid, ARUint32 *id0, ARUint32 *id1 ); +int ar2VideoGetSizeQuickTime7 ( AR2VideoParamQuickTime7T *vid, int *x,int *y ); +AR_PIXEL_FORMAT ar2VideoGetPixelFormatQuickTime7 ( AR2VideoParamQuickTime7T *vid ); +AR2VideoBufferT *ar2VideoGetImageQuickTime7 ( AR2VideoParamQuickTime7T *vid ); +int ar2VideoCapStartQuickTime7 ( AR2VideoParamQuickTime7T *vid ); +int ar2VideoCapStopQuickTime7 ( AR2VideoParamQuickTime7T *vid ); + +int ar2VideoGetParamiQuickTime7 ( AR2VideoParamQuickTime7T *vid, int paramName, int *value ); +int ar2VideoSetParamiQuickTime7 ( AR2VideoParamQuickTime7T *vid, int paramName, int value ); +int ar2VideoGetParamdQuickTime7 ( AR2VideoParamQuickTime7T *vid, int paramName, double *value ); +int ar2VideoSetParamdQuickTime7 ( AR2VideoParamQuickTime7T *vid, int paramName, double value ); +int ar2VideoGetParamsQuickTime7 ( AR2VideoParamQuickTime7T *vid, const int paramName, char **value ); +int ar2VideoSetParamsQuickTime7 ( AR2VideoParamQuickTime7T *vid, const int paramName, const char *value ); + +//int ar2VideoSetBufferSizeQuickTime7(AR2VideoParamQuickTime7T *vid, const int width, const int height); +//int ar2VideoGetBufferSizeQuickTime7(AR2VideoParamQuickTime7T *vid, int *width, int *height); + +void ar2VideoSetGotImageFunctionQuickTime7(AR2VideoParamQuickTime7T *vid, void (*gotImageFunc)(AR2VideoBufferT *, void *), void *userData); +void (*ar2VideoGetGotImageFunctionQuickTime7(AR2VideoParamQuickTime7T *vid))(AR2VideoBufferT *, void *); + + +// videoQuickTime7 uses an underlying native classe (QTKitVideo). +// This function retrieves a pointer, allowing direct access to the underlying native +// object instance. +#ifdef __OBJC__ +id ar2VideoGetQTKitVideoInstanceQuickTime7(AR2VideoParamQuickTime7T *vid); +#endif + +#ifdef __cplusplus +} +#endif +#endif diff --git a/libs/include/AR/sys/videoQuickTimeMovie.h b/libs/include/AR/sys/videoQuickTimeMovie.h new file mode 100755 index 0000000..222643d --- /dev/null +++ b/libs/include/AR/sys/videoQuickTimeMovie.h @@ -0,0 +1,449 @@ +/* + * videoQuickTimeMovie.h + * ARToolKit5 + * + * QuickTime movie playing routines. + * + * This file is part of ARToolKit. + * + * ARToolKit is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ARToolKit is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ARToolKit. If not, see . + * + * As a special exception, the copyright holders of this library give you + * permission to link this library with independent modules to produce an + * executable, regardless of the license terms of these independent modules, and to + * copy and distribute the resulting executable under terms of your choice, + * provided that you also meet, for each linked independent module, the terms and + * conditions of the license of that module. An independent module is a module + * which is neither derived from nor based on this library. If you modify this + * library, you may extend this exception to your version of the library, but you + * are not obligated to do so. If you do not wish to do so, delete this exception + * statement from your version. + * + * Copyright 2015 Daqri, LLC. + * Copyright 2013-2015 ARToolworks, Inc. + * Copyright 2007-2013 Philip Lamb. + * + * Author(s): Philip Lamb + * + * Rev Date Who Changes + * 1.0.0 2007-01-12 PRL Initial version. + */ +/*! + @header videoQuickTimeMovie + @abstract QuickTime movie playing routines. + @version 5.2 + @updated 2015-05-05 + @discussion + Mac OS, Mac OS X, and QuickTime for Windows are supported. + On Windows, link against qtmlClient.lib + @copyright 2015 Daqri, LLC + */ + +#ifndef __videoQuickTimeMovie_h__ +#define __videoQuickTimeMovie_h__ + +#if defined(__cplusplus) +extern "C" { +#endif + +// ============================================================================ +// Includes +// ============================================================================ + +// ============================================================================ +// Public types. +// ============================================================================ + +typedef struct _AR_VIDEO_QUICKTIME_MOVIE_t *AR_VIDEO_QUICKTIME_MOVIE_t; + +/*! + @enum AR_E_* + @abstract Symbolic codes for errors reported by routines in the AR library. + @discussion + As the actual numerical values for certain errors may change from time + to time, these symbolic codes should be used instead. + @constant AR_E_NONE No error. + @constant AR_E_OUT_OF_MEMORY Out of memory. + @constant AR_E_OVERFLOW Overflow. + @constant AR_E_NODATA Data was requested but none was available. + @constant AR_E_IOERROR Error during input / output operation. + @constant AR_E_EOF End of file reached. + @constant AR_E_TIMEOUT Timed out. + @constant AR_E_INVALID_COMMAND Invalid command. + @constant AR_E_INVALID_ENUM Invalid enumeration. + @constant AR_E_THREADS An error occured during a thread-management operation. + @constant AR_E_FILE_NOT_FOUND File not found. + @constant AR_E_LENGTH_UNAVAILABLE Length not available. + @constant AR_E_GENERIC Error. + @constant AR_E_LIBRARY_NOT_AVAILABLE A required library is not installed. + @constant AR_E_LIBRARY_TOO_OLD The minimum version requirement of a library was not met. + @constant AR_E_LIBRARY_TOO_NEW The maximum version requirement of a library was not met. + @constant AR_E_GENERIC_TOOLBOX Error returned from System tool. + @constant AR_E_HARDWARE_NOT_AVAILABLE Required hardware is not available. + @constant AR_E_BIRD_CONFIGURATION The bird hardware is incorrectly configured. + @constant AR_E_BIRD_PHASEERROR Data from the bird was lost and arrived from the bird out-of-phase. + @constant AR_E_HARDWARE_GENERIC Hardware error. + @constant AR_E_NET_NOT_AVAILABLE Network not available. + @constant AR_E_NET_NOT_CONNECTED Network not connected. + @constant AR_E_NET_GENERIC Network error. + */ +enum { + AR_E_NONE = 0, + AR_E_OUT_OF_MEMORY = -1, + AR_E_OVERFLOW = -2, + AR_E_NODATA = -3, + AR_E_IOERROR = -4, + AR_E_EOF = -6, + AR_E_TIMEOUT = -7, + AR_E_INVALID_COMMAND = -8, + AR_E_INVALID_ENUM = -9, + AR_E_THREADS = -10, + AR_E_FILE_NOT_FOUND = -11, + AR_E_LENGTH_UNAVAILABLE = -12, + AR_E_GENERIC = -9999, + AR_E_LIBRARY_NOT_AVAILABLE = -10001, + AR_E_LIBRARY_TOO_OLD = -10002, + AR_E_LIBRARY_TOO_NEW = -10003, + AR_E_GENERIC_TOOLBOX = -10999, + AR_E_HARDWARE_NOT_AVAILABLE = -11001, + AR_E_HARDWARE_GENERIC = -11999, + AR_E_NET_NOT_AVAILABLE = -12001, + AR_E_NET_NOT_CONNECTED = -12002, + AR_E_NET_GENERIC = -12999, +}; +typedef int AR_E_t; + +// ============================================================================ +// Public globals. +// ============================================================================ + +// ============================================================================ +// Public functions. +// ============================================================================ + +/*! + @function + @abstract Initialise QuickTime. + @discussion This function load the QuickTime libraries. + It must be called once per application, before any other + arVideoQuickTimeMovie*() functions are called. + @result AR_E_NONE if initialisation occured without error, + or an error code otherwise. Notable error codes include + AR_E_LIBRARY_NOT_AVAILABLE if QuickTime is not installed, + and AR_E_LIBRARY_TOO_OLD if the version of QuickTime + installed is too old. +*/ + +AR_DLL_API AR_E_t arVideoQuickTimeMovieInit(void); + +/*! + @function + @abstract Open and play any type of movie readable by QuickTime. + @discussion (description) + @param URL + This parameter is the full specification of the movie file + or stream to be played. It must be specified in URL form, + beginning with the characters "file://", "http://", "https://", + "rtsp://" or "ftp://". QuickTime's URL handler will be used to + attempt to open the movie file from the URL. Take care to + observe correct URL encoding, e.g. encoding spaces in the name + as "%20". + + If you wish to specify the path to a local file as a file:// + URL, you can use the convenience method arUtilGetFileURI. + @param conf + This optional parameter points to a C-string specifying + options describing the way in which to play the movie. Options + should be separated by spaces. The following options are + understood:
+		-1to1
+			Do not fit the movie to the window or buffer size, but
+			instead display it at its original size (1 to 1 scaling).
+		-fill
+			Rather than fitting the movie into the window so that all
+			the movie is visible, scale it so that it completely fills
+			the window or buffer. The movie's aspect ratio will be
+			maintained, and this may result in some of the movie
+			being clipped at the top and bottom or left and right.
+		-stretch
+			Rather than fitting the movie into the window so that all
+			the movie is visible, scale it so that it completely fills
+			the window or buffer. The movie's aspect ratio will be
+			stretched if necessary so that no pixels are clipped.
+		-loop
+			Request that the movie loop continuously. This
+			parameter has no effect for streaming movies. Unless
+			this parameter is specified, calls to arVideoQuickTimeMovieIdle()
+			will return AR_E_EOF when the movie has finished playing.
+		-showcontroller
+			Show the QuickTime movie controller in the frame. Unless
+			running in offscreen mode, the user will be able to
+			interact with the controller to pause and jog the movie.
+		-mute
+			Set movie audio volume to 0.
+		-pause
+			Open movie in paused state. A call to videoQuickTimeMovieSetPlayRate()
+			would be required to unpause the movie.
+		-width=w
+			Scale movie native frame to width w.
+		-height=h
+			Scale movie native frame to height h.
+		-fliph
+			Flip movie frame horizontally.
+		-flipv
+			Flip movie frame vertically.
+		-offscreen
+			Don't display the movie onscreen in a full-screen window,
+			but instead render into an offscreen pixel buffer, which
+			may then be retrieved by calling arVideoQuickTimeMovieGetFrame().
+		-pixelformat=cccc
+			Ignored unless -offscreen is also passed, requests return of
+			movie frames with pixels in format cccc, where cccc is either a
+			numeric pixel format number or a valid 4-character-code for a
+			pixel format. The following values are supported:
+			32, BGRA, RGBA, ABGR, 24, 24BG, 2vuy, yuvs.
+			(See http://developer.apple.com/quicktime/icefloe/dispatch020.html.)
+		-singlebuffer
+			Ignored unless -offscreen is also passed, use single buffering of
+			captured movie instead of triple-buffering.
+
+			
+ If you only wish to resume playback of a movie that has been paused, + use arVideoQuickTimeMovieSetPlayRate(movie, 1.0f); instead. + @param movie_p Pointer to a AR_VIDEO_QUICKTIME_MOVIE_t value, which will be + filled in with the value on successful return from the function. + This value should then be passed to other arVideoQuickTimeMovie*() functions + to identify the movie. + @result AR_E_NONE in case of successful opening, or an error code + less than 0 otherwise. Notable error codes to watch for include + AR_E_FILE_NOT_FOUND if the pathname or URL could not be found. +*/ +AR_DLL_API AR_E_t arVideoQuickTimeMoviePlay(char *URL, char *conf, AR_VIDEO_QUICKTIME_MOVIE_t *movie_p); + +/*! + @function + @abstract Allocate processing time to a playing movie, and check for end of movie. + @discussion + In order to grant processor time to a playing movie, this function + must be called at least as often as the frame rate of the movie + while the movie is playing. + This function also checks for the end of the movie (if the movie is + not being looped.) + @param movie Movie to be granted processing time. + @result If the movie has finished playing, the result code AR_E_EOF + will be returned, and the calling program can then perform any + housekeeping needed before calling arVideoQuickTimeMovieStop() to + stop and unload the movie. If no error, AR_E_NONE is returned. +*/ +AR_DLL_API AR_E_t arVideoQuickTimeMovieIdle(AR_VIDEO_QUICKTIME_MOVIE_t movie); + +/*! + @function + @abstract Set the playback rate of a movie, and pause/resume/fast forward/rewind. + @discussion + The playback rate of a movie may be continuously varied. + This function sets the rate. + Some useful rates include 0.0f (pause), 1.0f (playback at normal rate), -1.0f + (play backwards), 2.0f (fast forward at 2x normal rate). + @param movie Movie to have its rate set. + @param rate Floating point value indicating the rate to set. + @result AR_E_NONE in case of no error, or an error code. +*/ +AR_DLL_API AR_E_t arVideoQuickTimeMovieSetPlayRate(AR_VIDEO_QUICKTIME_MOVIE_t movie, float rate); + +/*! + @function + @abstract Get the playback rate of a movie. + @discussion + The playback rate of a movie may be continuously varied. + This function gets the rate. + Some interesting rates include 0.0f (pause), 1.0f (playback at normal rate). + @param movie Movie to have its rate retrieved. + @param rate Pointer to a float, which will be filled out with the rate. + @result AR_E_NONE in case of no error, or an error code. +*/ +AR_DLL_API AR_E_t arVideoQuickTimeMovieGetPlayRate(AR_VIDEO_QUICKTIME_MOVIE_t movie, float *rate); + +/*! + @function + @abstract Set the playback volume of a movie. + @discussion + The volume of a movie sound tracks (if any) may be continuously varied. + This function sets the volume. + Some useful volumes include 0.0f (muted), 1.0f (full volume). + @param movie Movie to have its volume set. + @param rate Floating point value indicating the volume to set. + @result AR_E_NONE in case of no error, or an error code. +*/ +AR_DLL_API AR_E_t arVideoQuickTimeMovieSetPlayVolume(AR_VIDEO_QUICKTIME_MOVIE_t movie, float volume); + +/*! + @function + @abstract (description) + @discussion + The volume of a movie sound tracks (if any) may be continuously varied. + This function gets the volume. + Some interesting volumes include 0.0f (muted), 1.0f (full volume). + @param movie Movie to have its volume retrieved. + @param rate Pointer to a float, which will be filled out with the volume. + @result AR_E_NONE in case of no error, or an error code. +*/ +AR_DLL_API AR_E_t arVideoQuickTimeMovieGetPlayVolume(AR_VIDEO_QUICKTIME_MOVIE_t movie, float *volume); + +/*! + @function + @abstract Determine the length of a movie in seconds (if possible). + @discussion + This function determines the length in seconds of a playing movie. + Some movies, e.g. streaming movies, QuickTime VR movies, and interactive + movies, may not have a valid length, so be sure to check the function return value. + @param movie Movie to have its length retrieved. + @param rate Pointer to a double, which will be filled out with the length. + @result AR_E_NONE if the length was able to be retrieved, or AR_E_LENGTH_UNAVAILABLE + if the movie does not have a valid length, or an error code < 0 otherwise. +*/ +AR_DLL_API AR_E_t arVideoQuickTimeMovieGetPlayLength(AR_VIDEO_QUICKTIME_MOVIE_t movie, double *lengthInSeconds); + +/*! + @function + @abstract Get the current movie playback position in seconds. + @discussion + While a movie is playing (or paused etc), you can use this function to + determine how far through the movie has played. + @param movie Movie to have its position retrieved. + @param positionInSeconds Pointer to a double, which will be filled out with + the current position of the playback head, in seconds since start. + @result AR_E_NONE if the position was able to be retrieved, or AR_E_LENGTH_UNAVAILABLE + if the movie does not have a valid length, or an error code < 0 otherwise. +*/ +AR_DLL_API AR_E_t arVideoQuickTimeMovieGetPlayPosition(AR_VIDEO_QUICKTIME_MOVIE_t movie, double *positionInSeconds); + +/*! + @function + @abstract Set the current movie playback position in seconds. + @discussion + A playing movie can have its playback position set non-linearly. + Use this function to position the playback head at the specified + number of seconds after the movie start. + Some movies, e.g. streaming movies, QuickTime VR movies, and interactive + movies, may not have a valid length, in which case the movie + playback position cannot be adjusted. + Adjusting the movie playback position does not change the movie's + rate (e.g. whether it is paused, running at normal speed etc.) + @param movie Movie to have its position set. + @param positionInSeconds Number of seconds since movie start to + move the playback head to. + @result AR_E_NONE if the position was able to be set, or AR_E_LENGTH_UNAVAILABLE + if the movie does not have a valid length, or AR_E_OVERFLOW if the position + specified was outside the movie's valid position range, or an error code < 0 otherwise. +*/ +AR_DLL_API AR_E_t arVideoQuickTimeMovieSetPlayPosition(AR_VIDEO_QUICKTIME_MOVIE_t movie, double positionInSeconds); + +AR_DLL_API AR_E_t arVideoQuickTimeMovieSetPlayPositionNextFrame(AR_VIDEO_QUICKTIME_MOVIE_t movie); + +AR_DLL_API int arVideoQuickTimeMovieIsPlayingEveryFrame(AR_VIDEO_QUICKTIME_MOVIE_t movie); + +/*! + @function + @abstract Get pixel data for one frame of a movie playing offscreen. + @discussion + Offscreen movies play into a offscreen pixel buffer. This function + retrieves the most recent frame (if available) in the form of a pointer + to an unstructured block of pixels, beginning with the first colour + component of the top-leftmost pixel, and continuing with the remaining + pixels in the top line of the frame, then the remaining lines of the + frame. + + If no new frame is currently available, NULL will be returned. + + Calling this function invalidates the data pointed to by any + previous return value of this function, thus returned pointers + should not be cached. The calling routine will have exclusive + access to the returned buffer, however, at least until the next call + to this function. + + The dimensions of the returned buffer (width, height and depth) are + retrieved by calling arVideoQuickTimeMovieGetFrameSize(). + @param movie A movie playing offscreen + (i.e. opened with the "-offscreen" config parameter). + @param time If supplied, will be filled with the movie frame time (in decimal seconds). + @result Pointer to a pixel buffer, or NULL if no new pixels are available. + */ +AR_DLL_API unsigned char *arVideoQuickTimeMovieGetFrame(AR_VIDEO_QUICKTIME_MOVIE_t movie, double *time); + +/*! + @function + @abstract Get size and format information for a movie playing offscreen. + @discussion + Offscreen movies play into a offscreen pixel buffer. This function + retrieves the size and pixel format of the pixel buffers returned by + calls to arVideoQuickTimeMovieGetFrame(). + + The total size of the buffer in bytes = width * height * pixelSize. + @param width + Pointer to an unsigned integer, which will be filled out with the width + in pixels of the pixel buffer. You may pass NULL if you do not need the + width. + @param height (description) + Pointer to an unsigned integer, which will be filled out with the height + in pixels of the pixel buffer. You may pass NULL if you do not need the + height. + @param pixelSize (description) + Pointer to an unsigned integer, which will be filled out with the size in + bytes of individual pixels in the pixel buffer. E.g., ARGB pixels (the + default on Mac OS) and BGRA pixels (the default on Windows) are 4 bytes + in size. You may pass NULL if you do not need the + pixelSize. + @param pixFormat (description) + Pointer to an unsigned integer, which will be filled out with the a + symbolic value corresponding to one of the AR_PIXEL_FORMAT_* + constants defined in config.h. + You may pass NULL if you do not need the + pixel format. + @result AR_E_NONE in case of no error, or an error code. + */ +AR_DLL_API AR_E_t arVideoQuickTimeMovieGetFrameSize(AR_VIDEO_QUICKTIME_MOVIE_t movie, unsigned int *width, unsigned int *height, unsigned int *pixelSize, unsigned int *pixFormat); + +/*! + @function + @abstract Stop and unload a movie. + @discussion + This function ceases playback of a movie. If the movie + is playing in a fullscreen window, the window will be closed + and removed. If the movie is playing offscreen, the offscreen + buffers will be unloaded. + + If you only wish to pause a movie, use arVideoQuickTimeMovieSetPlayRate(movie, 0.0f); + insteaad. + @param movie_p Pointer to a AR_VIDEO_QUICKTIME_MOVIE_t value, which identifies + the movie to be stopped and closed. On return, the contents of this + location will be set to NULL. + @result AR_E_NONE in case of no error, or an error code. +*/ +AR_DLL_API AR_E_t arVideoQuickTimeMovieStop(AR_VIDEO_QUICKTIME_MOVIE_t *movie_p); + +/*! + @function + @abstract Finalise QuickTime. + @discussion This function unloads the QuickTime libraries. + It may be called once per application, after all use of + arVideoQuickTimeMovie*() functions is complete. + */ +AR_DLL_API void arVideoQuickTimeMovieFinal(void); + +#if defined(__cplusplus) +} +#endif + +#endif // !__videoQuickTimeMovie_h__ diff --git a/libs/include/AR/sys/videoWindowsDSVideoLib.h b/libs/include/AR/sys/videoWindowsDSVideoLib.h new file mode 100755 index 0000000..c4ceb99 --- /dev/null +++ b/libs/include/AR/sys/videoWindowsDSVideoLib.h @@ -0,0 +1,92 @@ +/* + * videoWindowsDSVideoLib.h + * ARToolKit5 + * + * This file is part of ARToolKit. + * + * ARToolKit is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ARToolKit is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ARToolKit. If not, see . + * + * As a special exception, the copyright holders of this library give you + * permission to link this library with independent modules to produce an + * executable, regardless of the license terms of these independent modules, and to + * copy and distribute the resulting executable under terms of your choice, + * provided that you also meet, for each linked independent module, the terms and + * conditions of the license of that module. An independent module is a module + * which is neither derived from nor based on this library. If you modify this + * library, you may extend this exception to your version of the library, but you + * are not obligated to do so. If you do not wish to do so, delete this exception + * statement from your version. + * + * Copyright 2015 Daqri, LLC. + * Copyright 2004-2015 ARToolworks, Inc. + * + * Author(s): Thomas Pintaric, Philip Lamb + * + * Rev Date Who Changes + * 2.68.2 2004-07-20 PRL Rewrite for ARToolKit 2.68.2 + * 2.71.0 2005-08-05 PRL Incorporate DSVL-0.0.8b + * + */ +/* + ======================================================================== + PROJECT: DirectShow Video Processing Library + Version: 0.0.8 (05/04/2005) + ======================================================================== + Author: Thomas Pintaric, Vienna University of Technology + Contact: pintaric@ims.tuwien.ac.at http://ims.tuwien.ac.at/~thomas + ======================================================================= + + Copyright (C) 2005 Vienna University of Technology + + For further information please contact Thomas Pintaric under + or write to Thomas Pintaric, + Vienna University of Technology, Favoritenstr. 9-11/E188/2, A-1040 + Vienna, Austria. + ======================================================================== + */ + +#ifndef AR_VIDEO_WIN_DSVL_H +#define AR_VIDEO_WIN_DSVL_H + +#include +#include +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct _AR2VideoParamWinDSVLT AR2VideoParamWinDSVLT; + +int ar2VideoDispOptionWinDSVL ( void ); +AR2VideoParamWinDSVLT *ar2VideoOpenWinDSVL ( const char *config ); +int ar2VideoCloseWinDSVL ( AR2VideoParamWinDSVLT *vid ); +int ar2VideoGetIdWinDSVL ( AR2VideoParamWinDSVLT *vid, ARUint32 *id0, ARUint32 *id1 ); +int ar2VideoGetSizeWinDSVL ( AR2VideoParamWinDSVLT *vid, int *x,int *y ); +AR_PIXEL_FORMAT ar2VideoGetPixelFormatWinDSVL ( AR2VideoParamWinDSVLT *vid ); +AR2VideoBufferT *ar2VideoGetImageWinDSVL ( AR2VideoParamWinDSVLT *vid ); +int ar2VideoCapStartWinDSVL ( AR2VideoParamWinDSVLT *vid ); +int ar2VideoCapStopWinDSVL ( AR2VideoParamWinDSVLT *vid ); + +int ar2VideoGetParamiWinDSVL ( AR2VideoParamWinDSVLT *vid, int paramName, int *value ); +int ar2VideoSetParamiWinDSVL ( AR2VideoParamWinDSVLT *vid, int paramName, int value ); +int ar2VideoGetParamdWinDSVL ( AR2VideoParamWinDSVLT *vid, int paramName, double *value ); +int ar2VideoSetParamdWinDSVL ( AR2VideoParamWinDSVLT *vid, int paramName, double value ); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/libs/include/AR/sys/videoWindowsDirectShow.h b/libs/include/AR/sys/videoWindowsDirectShow.h new file mode 100755 index 0000000..53be7b3 --- /dev/null +++ b/libs/include/AR/sys/videoWindowsDirectShow.h @@ -0,0 +1,85 @@ +/* + * videoWindowsDirectShow.h + * ARToolKit5 + * + * DirectShow video capture module. + * + * This file is part of ARToolKit. + * + * ARToolKit is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ARToolKit is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ARToolKit. If not, see . + * + * As a special exception, the copyright holders of this library give you + * permission to link this library with independent modules to produce an + * executable, regardless of the license terms of these independent modules, and to + * copy and distribute the resulting executable under terms of your choice, + * provided that you also meet, for each linked independent module, the terms and + * conditions of the license of that module. An independent module is a module + * which is neither derived from nor based on this library. If you modify this + * library, you may extend this exception to your version of the library, but you + * are not obligated to do so. If you do not wish to do so, delete this exception + * statement from your version. + * + * Copyright 2015 Daqri, LLC. + * Copyright 2005-2015 ARToolworks, Inc. + * + * Author(s): Hirokazu Kato, Philip Lamb + * + */ +/******************************************************* + * + * Author: Hirokazu Kato + * + * kato@sys.es.osaka-u.ac.jp + * + * Revision: 4.1 + * Date: 2005/08/26 + * + *******************************************************/ + +#ifndef AR_VIDEO_WIN_DS_H +#define AR_VIDEO_WIN_DS_H + +#include +#include +#include +#include +#include + + +#ifdef __cplusplus +extern "C" { +#endif + +typedef void AR2VideoParamWinDST; + +int ar2VideoDispOptionWinDS ( void ); +ARVideoSourceInfoListT *ar2VideoCreateSourceInfoListWinDS(const char *config); +AR2VideoParamWinDST *ar2VideoOpenWinDS ( const char *config ); +int ar2VideoCloseWinDS ( AR2VideoParamWinDST *vid ); +int ar2VideoGetIdWinDS ( AR2VideoParamWinDST *vid, ARUint32 *id0, ARUint32 *id1 ); +int ar2VideoGetSizeWinDS ( AR2VideoParamWinDST *vid, int *x,int *y ); +AR_PIXEL_FORMAT ar2VideoGetPixelFormatWinDS ( AR2VideoParamWinDST *vid ); +AR2VideoBufferT *ar2VideoGetImageWinDS ( AR2VideoParamWinDST *vid ); +int ar2VideoCapStartWinDS ( AR2VideoParamWinDST *vid ); +int ar2VideoCapStopWinDS ( AR2VideoParamWinDST *vid ); + +int ar2VideoGetParamiWinDS ( AR2VideoParamWinDST *vid, int paramName, int *value ); +int ar2VideoSetParamiWinDS ( AR2VideoParamWinDST *vid, int paramName, int value ); +int ar2VideoGetParamdWinDS ( AR2VideoParamWinDST *vid, int paramName, double *value ); +int ar2VideoSetParamdWinDS ( AR2VideoParamWinDST *vid, int paramName, double value ); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/libs/include/AR/sys/videoWindowsDragonFly.h b/libs/include/AR/sys/videoWindowsDragonFly.h new file mode 100755 index 0000000..1bf887c --- /dev/null +++ b/libs/include/AR/sys/videoWindowsDragonFly.h @@ -0,0 +1,97 @@ +/* + * videoWindowsDragonFly.h + * ARToolKit5 + * + * DragonFly/FlyCapture video capture module. + * + * This file is part of ARToolKit. + * + * ARToolKit is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ARToolKit is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ARToolKit. If not, see . + * + * As a special exception, the copyright holders of this library give you + * permission to link this library with independent modules to produce an + * executable, regardless of the license terms of these independent modules, and to + * copy and distribute the resulting executable under terms of your choice, + * provided that you also meet, for each linked independent module, the terms and + * conditions of the license of that module. An independent module is a module + * which is neither derived from nor based on this library. If you modify this + * library, you may extend this exception to your version of the library, but you + * are not obligated to do so. If you do not wish to do so, delete this exception + * statement from your version. + * + * Copyright 2015 Daqri, LLC. + * Copyright 2004-2015 ARToolworks, Inc. + * + * Author(s): Hirokazu Kato, Philip Lamb + * + */ +/******************************************************* + * + * Author: Hirokazu Kato + * + * kato@sys.im.hiroshima-cu.ac.jp + * + * Revision: 2.1 + * Date: 2004/01/01 + * Revised 2012-08-05, Philip Lamb. + * + *******************************************************/ + +#ifndef AR_VIDEO_WINDOWS_DRAGON_FLY_H +#define AR_VIDEO_WINDOWS_DRAGON_FLY_H + +#include +#include +#include +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define AR2VIDEO_WINDF_STATUS_IDLE 0 +#define AR2VIDEO_WINDF_STATUS_RUN 1 +#define AR2VIDEO_WINDF_STATUS_STOP 2 +#define AR2VIDEO_WINDF_STATUS_STOP2 3 + +typedef struct { + AR2VideoBufferT in; + AR2VideoBufferT wait; + AR2VideoBufferT out; + HANDLE buffMutex; +} AR2VideoBufferWinDFT; + +typedef struct _AR2VideoParamWinDFT AR2VideoParamWinDFT; + +int ar2VideoDispOptionWinDF ( void ); +AR2VideoParamWinDFT *ar2VideoOpenWinDF ( const char *config ); +int ar2VideoCloseWinDF ( AR2VideoParamWinDFT *vid ); +int ar2VideoGetIdWinDF ( AR2VideoParamWinDFT *vid, ARUint32 *id0, ARUint32 *id1 ); +int ar2VideoGetSizeWinDF ( AR2VideoParamWinDFT *vid, int *x,int *y ); +AR_PIXEL_FORMAT ar2VideoGetPixelFormatWinDF ( AR2VideoParamWinDFT *vid ); +AR2VideoBufferT *ar2VideoGetImageWinDF ( AR2VideoParamWinDFT *vid ); +int ar2VideoCapStartWinDF ( AR2VideoParamWinDFT *vid ); +int ar2VideoCapStopWinDF ( AR2VideoParamWinDFT *vid ); + +int ar2VideoGetParamiWinDF ( AR2VideoParamWinDFT *vid, int paramName, int *value ); +int ar2VideoSetParamiWinDF ( AR2VideoParamWinDFT *vid, int paramName, int value ); +int ar2VideoGetParamdWinDF ( AR2VideoParamWinDFT *vid, int paramName, double *value ); +int ar2VideoSetParamdWinDF ( AR2VideoParamWinDFT *vid, int paramName, double value ); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/libs/include/AR/sys/videoWindowsMediaCapture.h b/libs/include/AR/sys/videoWindowsMediaCapture.h new file mode 100755 index 0000000..9d46dcf --- /dev/null +++ b/libs/include/AR/sys/videoWindowsMediaCapture.h @@ -0,0 +1,70 @@ +/* + * videoWindowsMediaCapture.h + * ARToolKit5 + * + * This file is part of ARToolKit. + * + * ARToolKit is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ARToolKit is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ARToolKit. If not, see . + * + * As a special exception, the copyright holders of this library give you + * permission to link this library with independent modules to produce an + * executable, regardless of the license terms of these independent modules, and to + * copy and distribute the resulting executable under terms of your choice, + * provided that you also meet, for each linked independent module, the terms and + * conditions of the license of that module. An independent module is a module + * which is neither derived from nor based on this library. If you modify this + * library, you may extend this exception to your version of the library, but you + * are not obligated to do so. If you do not wish to do so, delete this exception + * statement from your version. + * + * Copyright 2015 Daqri, LLC. + * Copyright 2014-2015 ARToolworks, Inc. + * + * Author(s): Philip Lamb + * + */ + +#ifndef AR_VIDEO_WIN_MC_H +#define AR_VIDEO_WIN_MC_H + +#include + + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct _AR2VideoParamWinMCT AR2VideoParamWinMCT; + +int ar2VideoDispOptionWinMC (void); +AR2VideoParamWinMCT *ar2VideoOpenWinMC (const char *config); +int ar2VideoCloseWinMC (AR2VideoParamWinMCT *vid); +int ar2VideoGetIdWinMC (AR2VideoParamWinMCT *vid, ARUint32 *id0, ARUint32 *id1); +int ar2VideoGetSizeWinMC (AR2VideoParamWinMCT *vid, int *x,int *y); +AR_PIXEL_FORMAT ar2VideoGetPixelFormatWinMC (AR2VideoParamWinMCT *vid); +AR2VideoBufferT *ar2VideoGetImageWinMC (AR2VideoParamWinMCT *vid); +int ar2VideoCapStartWinMC (AR2VideoParamWinMCT *vid); +int ar2VideoCapStopWinMC (AR2VideoParamWinMCT *vid); + +int ar2VideoGetParamiWinMC (AR2VideoParamWinMCT *vid, const int paramName, int *value); +int ar2VideoSetParamiWinMC (AR2VideoParamWinMCT *vid, const int paramName, const int value); +int ar2VideoGetParamdWinMC (AR2VideoParamWinMCT *vid, const int paramName, double *value); +int ar2VideoSetParamdWinMC (AR2VideoParamWinMCT *vid, const int paramName, const double value); +int ar2VideoGetParamsWinMC (AR2VideoParamWinMCT *vid, const int paramName, char **value); +int ar2VideoSetParamsWinMC (AR2VideoParamWinMCT *vid, const int paramName, const char *value); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/libs/include/AR/sys/videoWindowsMediaFoundation.h b/libs/include/AR/sys/videoWindowsMediaFoundation.h new file mode 100755 index 0000000..c261720 --- /dev/null +++ b/libs/include/AR/sys/videoWindowsMediaFoundation.h @@ -0,0 +1,71 @@ +/* + * videoWindowsMediaFoundation.h + * ARToolKit5 + * + * This file is part of ARToolKit. + * + * ARToolKit is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ARToolKit is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ARToolKit. If not, see . + * + * As a special exception, the copyright holders of this library give you + * permission to link this library with independent modules to produce an + * executable, regardless of the license terms of these independent modules, and to + * copy and distribute the resulting executable under terms of your choice, + * provided that you also meet, for each linked independent module, the terms and + * conditions of the license of that module. An independent module is a module + * which is neither derived from nor based on this library. If you modify this + * library, you may extend this exception to your version of the library, but you + * are not obligated to do so. If you do not wish to do so, delete this exception + * statement from your version. + * + * Copyright 2015 Daqri, LLC. + * Copyright 2013-2015 ARToolworks, Inc. + * + * Author(s): Philip Lamb + * + */ + +#ifndef AR_VIDEO_WIN_MF_H +#define AR_VIDEO_WIN_MF_H + +#include + + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct _AR2VideoParamWinMFT AR2VideoParamWinMFT; + +int ar2VideoDispOptionWinMF (void); +ARVideoSourceInfoListT *ar2VideoCreateSourceInfoListWinMF(const char *config); +AR2VideoParamWinMFT *ar2VideoOpenWinMF (const char *config); +int ar2VideoCloseWinMF (AR2VideoParamWinMFT *vid); +int ar2VideoGetIdWinMF (AR2VideoParamWinMFT *vid, ARUint32 *id0, ARUint32 *id1); +int ar2VideoGetSizeWinMF (AR2VideoParamWinMFT *vid, int *x,int *y); +AR_PIXEL_FORMAT ar2VideoGetPixelFormatWinMF (AR2VideoParamWinMFT *vid); +AR2VideoBufferT *ar2VideoGetImageWinMF (AR2VideoParamWinMFT *vid); +int ar2VideoCapStartWinMF (AR2VideoParamWinMFT *vid); +int ar2VideoCapStopWinMF (AR2VideoParamWinMFT *vid); + +int ar2VideoGetParamiWinMF (AR2VideoParamWinMFT *vid, const int paramName, int *value); +int ar2VideoSetParamiWinMF (AR2VideoParamWinMFT *vid, const int paramName, const int value); +int ar2VideoGetParamdWinMF (AR2VideoParamWinMFT *vid, const int paramName, double *value); +int ar2VideoSetParamdWinMF (AR2VideoParamWinMFT *vid, const int paramName, const double value); +int ar2VideoGetParamsWinMF (AR2VideoParamWinMFT *vid, const int paramName, char **value); +int ar2VideoSetParamsWinMF (AR2VideoParamWinMFT *vid, const int paramName, const char *value); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/libs/include/AR/sys/videoiPhone.h b/libs/include/AR/sys/videoiPhone.h new file mode 100755 index 0000000..73f90d7 --- /dev/null +++ b/libs/include/AR/sys/videoiPhone.h @@ -0,0 +1,148 @@ +/* + * videoiPhone.h + * ARToolKit5 + * + * This file is part of ARToolKit. + * + * ARToolKit is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ARToolKit is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ARToolKit. If not, see . + * + * As a special exception, the copyright holders of this library give you + * permission to link this library with independent modules to produce an + * executable, regardless of the license terms of these independent modules, and to + * copy and distribute the resulting executable under terms of your choice, + * provided that you also meet, for each linked independent module, the terms and + * conditions of the license of that module. An independent module is a module + * which is neither derived from nor based on this library. If you modify this + * library, you may extend this exception to your version of the library, but you + * are not obligated to do so. If you do not wish to do so, delete this exception + * statement from your version. + * + * Copyright 2015 Daqri, LLC. + * Copyright 2008-2015 ARToolworks, Inc. + * + * Author(s): Philip Lamb + * + * Rev Date Who Changes + * 1.0.0 2008-05-04 PRL Written. + * + */ + +#ifndef AR_VIDEO_IPHONE_H +#define AR_VIDEO_IPHONE_H + +// This header is only ever included by other headers, so +// doesn't need to include or . + +#ifdef __cplusplus +extern "C" { +#endif + +enum { + AR_VIDEO_PARAM_IPHONE_WILL_CAPTURE_NEXT_FRAME, + AR_VIDEO_PARAM_IPHONE_IS_USING_COREVIDEO, + AR_VIDEO_PARAM_IOS_DEVICE, + AR_VIDEO_PARAM_IOS_FOCUS, + AR_VIDEO_PARAM_IOS_RECOMMENDED_CPARAM_NAME, // No longer supported. Use arVideoGetCParam() instead. + AR_VIDEO_PARAM_IOS_ASYNC, + AR_VIDEO_PARAM_IOS_CAMERA_POSITION +}; + +typedef enum { + AR_VIDEO_IOS_FOCUS_NONE = 0, + AR_VIDEO_IOS_FOCUS_MACRO, + AR_VIDEO_IOS_FOCUS_0_3M, + AR_VIDEO_IOS_FOCUS_1_0M, + AR_VIDEO_IOS_FOCUS_INF +} AR_VIDEO_IOS_FOCUS; + +typedef enum { + AR_VIDEO_IOS_CAMERA_POSITION_UNKNOWN = -1, + AR_VIDEO_IOS_CAMERA_POSITION_UNSPECIFIED = 0, + AR_VIDEO_IOS_CAMERA_POSITION_REAR, + AR_VIDEO_IOS_CAMERA_POSITION_FRONT, + AR_VIDEO_IOS_CAMERA_POSITION_REAR_STEREO_LEFT, + AR_VIDEO_IOS_CAMERA_POSITION_REAR_STEREO_RIGHT, + AR_VIDEO_IOS_CAMERA_POSITION_FRONT_STEREO_LEFT, + AR_VIDEO_IOS_CAMERA_POSITION_FRONT_STEREO_RIGHT +} AR_VIDEO_IOS_CAMERA_POSITION; + +typedef enum { + AR_VIDEO_IOS_DEVICE_IPHONE3G = 1, + AR_VIDEO_IOS_DEVICE_IPHONE3GS, + AR_VIDEO_IOS_DEVICE_IPHONE4, + AR_VIDEO_IOS_DEVICE_IPODTOUCH4, + AR_VIDEO_IOS_DEVICE_IPAD2, + AR_VIDEO_IOS_DEVICE_IPAD3, + AR_VIDEO_IOS_DEVICE_IPHONE_GENERIC, + AR_VIDEO_IOS_DEVICE_IPOD_GENERIC, + AR_VIDEO_IOS_DEVICE_IPAD_GENERIC, + AR_VIDEO_IOS_DEVICE_IPHONE4S, + AR_VIDEO_IOS_DEVICE_APPLETV_GENERIC, + AR_VIDEO_IOS_DEVICE_IPHONE5, + AR_VIDEO_IOS_DEVICE_IPODTOUCH5, + AR_VIDEO_IOS_DEVICE_IPAD4, + AR_VIDEO_IOS_DEVICE_IPADMINI, + AR_VIDEO_IOS_DEVICE_IPHONE5C, + AR_VIDEO_IOS_DEVICE_IPHONE5S, + AR_VIDEO_IOS_DEVICE_IPADAIR, + AR_VIDEO_IOS_DEVICE_IPADMINI2, + AR_VIDEO_IOS_DEVICE_IPADMINI3, + AR_VIDEO_IOS_DEVICE_IPADMINI4, + AR_VIDEO_IOS_DEVICE_IPADAIR2, + AR_VIDEO_IOS_DEVICE_IPHONE6, + AR_VIDEO_IOS_DEVICE_IPHONE6PLUS, + AR_VIDEO_IOS_DEVICE_IPHONE6S, + AR_VIDEO_IOS_DEVICE_IPHONE6SPLUS +} AR_VIDEO_IOS_DEVICE; + + +typedef struct _AR2VideoParamiPhoneT AR2VideoParamiPhoneT; + + +int ar2VideoDispOptioniPhone ( void ); +AR2VideoParamiPhoneT *ar2VideoOpeniPhone ( const char *config ); +int ar2VideoCloseiPhone ( AR2VideoParamiPhoneT *vid ); +int ar2VideoGetIdiPhone ( AR2VideoParamiPhoneT *vid, ARUint32 *id0, ARUint32 *id1 ); +int ar2VideoGetSizeiPhone ( AR2VideoParamiPhoneT *vid, int *x,int *y ); +int ar2VideoGetPixelFormatiPhone ( AR2VideoParamiPhoneT *vid ); +AR2VideoBufferT *ar2VideoGetImageiPhone ( AR2VideoParamiPhoneT *vid ); +int ar2VideoCapStartiPhone ( AR2VideoParamiPhoneT *vid ); +int ar2VideoCapStopiPhone ( AR2VideoParamiPhoneT *vid ); + +int ar2VideoGetParamiiPhone ( AR2VideoParamiPhoneT *vid, int paramName, int *value ); +int ar2VideoSetParamiiPhone ( AR2VideoParamiPhoneT *vid, int paramName, int value ); +int ar2VideoGetParamdiPhone ( AR2VideoParamiPhoneT *vid, int paramName, double *value ); +int ar2VideoSetParamdiPhone ( AR2VideoParamiPhoneT *vid, int paramName, double value ); +int ar2VideoGetParamsiPhone ( AR2VideoParamiPhoneT *vid, const int paramName, char **value ); +int ar2VideoSetParamsiPhone ( AR2VideoParamiPhoneT *vid, const int paramName, const char *value ); + +int ar2VideoSetBufferSizeiPhone(AR2VideoParamiPhoneT *vid, const int width, const int height); +int ar2VideoGetBufferSizeiPhone(AR2VideoParamiPhoneT *vid, int *width, int *height); +void ar2VideoSetGotImageFunctioniPhone(AR2VideoParamiPhoneT *vid, void (*gotImageFunc)(AR2VideoBufferT *, void *), void *userData); +void (*ar2VideoGetGotImageFunctioniPhone(AR2VideoParamiPhoneT *vid))(AR2VideoBufferT *, void *); + +int ar2VideoGetCParamiPhone (AR2VideoParamiPhoneT *vid, ARParam *cparam); +AR2VideoParamiPhoneT *ar2VideoOpenAsynciPhone (const char *config, void (*callback)(void *), void *userdata); + +// videoiPhone uses underlying native classes (CameraVideo, MovieVideo). +// This function retrieves a pointer, allowing direct access to the underlying native +// object instance. +#ifdef __OBJC__ +id ar2VideoGetNativeVideoInstanceiPhone(AR2VideoParamiPhoneT *vid); +#endif + +#ifdef __cplusplus +} +#endif +#endif diff --git a/libs/include/AR/video.h b/libs/include/AR/video.h new file mode 100755 index 0000000..9dd0230 --- /dev/null +++ b/libs/include/AR/video.h @@ -0,0 +1,464 @@ +/* + * video.h + * ARToolKit5 + * + * This file is part of ARToolKit. + * + * ARToolKit is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ARToolKit is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ARToolKit. If not, see . + * + * As a special exception, the copyright holders of this library give you + * permission to link this library with independent modules to produce an + * executable, regardless of the license terms of these independent modules, and to + * copy and distribute the resulting executable under terms of your choice, + * provided that you also meet, for each linked independent module, the terms and + * conditions of the license of that module. An independent module is a module + * which is neither derived from nor based on this library. If you modify this + * library, you may extend this exception to your version of the library, but you + * are not obligated to do so. If you do not wish to do so, delete this exception + * statement from your version. + * + * Copyright 2015 Daqri, LLC. + * Copyright 2002-2015 ARToolworks, Inc. + * + * Author(s): Hirokazu Kato, Atsishi Nakazawa, Philip Lamb + * + */ +/******************************************************* + * + * Author: Hirokazu Kato, Atsishi Nakazawa + * + * kato@sys.im.hiroshima-cu.ac.jp + * nakazawa@inolab.sys.es.osaka-u.ac.jp + * + * Revision: 4.3 + * Date: 2002/01/01 + * + *******************************************************/ + +#ifndef AR_VIDEO_H +#define AR_VIDEO_H + +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define AR_VIDEO_DEVICE_DUMMY 0 +#define AR_VIDEO_DEVICE_V4L 1 +#define AR_VIDEO_DEVICE_DV 2 +#define AR_VIDEO_DEVICE_1394CAM 3 +#define AR_VIDEO_DEVICE_SGI 4 +#define AR_VIDEO_DEVICE_WINDOWS_DIRECTSHOW 5 +#define AR_VIDEO_DEVICE_WINDOWS_DRAGONFLY 6 +#define AR_VIDEO_DEVICE_RESERVED1 7 +#define AR_VIDEO_DEVICE_RESERVED2 8 +#define AR_VIDEO_DEVICE_QUICKTIME 9 +#define AR_VIDEO_DEVICE_WINDOWS_DSVIDEOLIB 10 +#define AR_VIDEO_DEVICE_GSTREAMER 11 +#define AR_VIDEO_DEVICE_IPHONE 12 +#define AR_VIDEO_DEVICE_QUICKTIME7 13 +#define AR_VIDEO_DEVICE_IMAGE 14 +#define AR_VIDEO_DEVICE_ANDROID 15 +#define AR_VIDEO_DEVICE_WINDOWS_MEDIA_FOUNDATION 16 +#define AR_VIDEO_DEVICE_WINDOWS_MEDIA_CAPTURE 17 +#define AR_VIDEO_DEVICE_MAX 17 + + +#define AR_VIDEO_1394_BRIGHTNESS 65 +#define AR_VIDEO_1394_BRIGHTNESS_FEATURE_ON 66 +#define AR_VIDEO_1394_BRIGHTNESS_AUTO_ON 67 +#define AR_VIDEO_1394_BRIGHTNESS_MAX_VAL 68 +#define AR_VIDEO_1394_BRIGHTNESS_MIN_VAL 69 +#define AR_VIDEO_1394_EXPOSURE 70 +#define AR_VIDEO_1394_EXPOSURE_FEATURE_ON 71 +#define AR_VIDEO_1394_EXPOSURE_AUTO_ON 72 +#define AR_VIDEO_1394_EXPOSURE_MAX_VAL 73 +#define AR_VIDEO_1394_EXPOSURE_MIN_VAL 74 +#define AR_VIDEO_1394_WHITE_BALANCE 75 +#define AR_VIDEO_1394_WHITE_BALANCE_UB 76 +#define AR_VIDEO_1394_WHITE_BALANCE_VR 77 +#define AR_VIDEO_1394_WHITE_BALANCE_FEATURE_ON 78 +#define AR_VIDEO_1394_WHITE_BALANCE_AUTO_ON 79 +#define AR_VIDEO_1394_WHITE_BALANCE_MAX_VAL 80 +#define AR_VIDEO_1394_WHITE_BALANCE_MIN_VAL 81 +#define AR_VIDEO_1394_SHUTTER_SPEED 82 +#define AR_VIDEO_1394_SHUTTER_SPEED_FEATURE_ON 83 +#define AR_VIDEO_1394_SHUTTER_SPEED_AUTO_ON 84 +#define AR_VIDEO_1394_SHUTTER_SPEED_MAX_VAL 85 +#define AR_VIDEO_1394_SHUTTER_SPEED_MIN_VAL 86 +#define AR_VIDEO_1394_GAIN 87 +#define AR_VIDEO_1394_GAIN_FEATURE_ON 88 +#define AR_VIDEO_1394_GAIN_AUTO_ON 89 +#define AR_VIDEO_1394_GAIN_MAX_VAL 90 +#define AR_VIDEO_1394_GAIN_MIN_VAL 91 +#define AR_VIDEO_1394_FOCUS 92 +#define AR_VIDEO_1394_FOCUS_FEATURE_ON 93 +#define AR_VIDEO_1394_FOCUS_AUTO_ON 94 +#define AR_VIDEO_1394_FOCUS_MAX_VAL 95 +#define AR_VIDEO_1394_FOCUS_MIN_VAL 96 +#define AR_VIDEO_1394_GAMMA 97 +#define AR_VIDEO_1394_GAMMA_FEATURE_ON 98 +#define AR_VIDEO_1394_GAMMA_AUTO_ON 99 +#define AR_VIDEO_1394_GAMMA_MAX_VAL 100 +#define AR_VIDEO_1394_GAMMA_MIN_VAL 101 + +#define AR_VIDEO_WINDS_SHOW_PROPERTIES 129 + +#define AR_VIDEO_FOCUS_MODE 301 // i +#define AR_VIDEO_FOCUS_MANUAL_DISTANCE 302 // d +#define AR_VIDEO_FOCUS_POINT_OF_INTEREST_X 303 // d +#define AR_VIDEO_FOCUS_POINT_OF_INTEREST_Y 304 // d + +#define AR_VIDEO_GET_VERSION INT_MAX + +#define AR_VIDEO_FOCUS_MODE_FIXED 0 +#define AR_VIDEO_FOCUS_MODE_AUTO 1 +#define AR_VIDEO_FOCUS_MODE_POINT_OF_INTEREST 2 +#define AR_VIDEO_FOCUS_MODE_MANUAL 3 + +/*! + @typedef + @asbtract Structure which carries information about a frame retrieved by the video library. + @field buff A pointer to the packed video data for this video frame. The video data pixel + format is as specified by arVideoGetPixelFormat(). For multi-planar frames, + this pointer is a copy of bufPlanes[0]. + @field bufPlanes For multi-planar video frames, this must be an array of length bufPlaneCount + of (ARUint8*), into which will be copied pointers to the packed video data + for each plane. For single-plane formats, this will be NULL. + @field bufPlaneCount For multi-planar video frames, this is the number of frame planes. For + single-plane formats, this will be 0. + @field fillFlag Set non-zero when buff is valid. + @field time_sec Seconds portion of the time at which buff was filled. Epoch is OS-specific. + @field time_usec Microseconds portion of the time at which buff was filled. Epoch is OS-specific. + @seealso arVideoGetPixelFormat arVideoGetPixelFormat + */ +typedef struct { + ARUint8 *buff; + ARUint8 **bufPlanes; + unsigned int bufPlaneCount; + int fillFlag; + ARUint32 time_sec; + ARUint32 time_usec; +} AR2VideoBufferT; + +#define AR_VIDEO_POSITION_UNKNOWN 0x0000 // Camera physical position on device unknown. +#define AR_VIDEO_POSITION_FRONT 0x0008 // Camera is on front of device pointing towards user. +#define AR_VIDEO_POSITION_BACK 0x0010 // Camera is on back of device pointing away from user. +#define AR_VIDEO_POSITION_LEFT 0x0018 // Camera is on left of device pointing to user's left. +#define AR_VIDEO_POSITION_RIGHT 0x0020 // Camera is on right of device pointing to user's right. +#define AR_VIDEO_POSITION_TOP 0x0028 // Camera is on top of device pointing toward ceiling when device is held upright. +#define AR_VIDEO_POSITION_BOTTOM 0x0030 // Camera is on bottom of device pointing towards floor when device is held upright. +#define AR_VIDEO_POSITION_OTHER 0x0038 // Camera physical position on device is known but none of the above. + +#define AR_VIDEO_STEREO_MODE_MONO 0x0000 +#define AR_VIDEO_STEREO_MODE_LEFT 0x0040 +#define AR_VIDEO_STEREO_MODE_RIGHT 0x0080 +#define AR_VIDEO_STEREO_MODE_FRAME_SEQUENTIAL 0x00C0 +#define AR_VIDEO_STEREO_MODE_SIDE_BY_SIDE 0x0100 +#define AR_VIDEO_STEREO_MODE_OVER_UNDER 0x0140 +#define AR_VIDEO_STEREO_MODE_HALF_SIDE_BY_SIDE 0x0180 +#define AR_VIDEO_STEREO_MODE_OVER_UNDER_HALF_HEIGHT 0x01C0 +#define AR_VIDEO_STEREO_MODE_ROW_INTERLACED 0x0200 +#define AR_VIDEO_STEREO_MODE_COLUMN_INTERLACED 0x0240 +#define AR_VIDEO_STEREO_MODE_ROW_AND_COLUMN_INTERLACED 0x0280 +#define AR_VIDEO_STEREO_MODE_ANAGLYPH_RG 0x02C0 +#define AR_VIDEO_STEREO_MODE_ANAGLYPH_RB 0x0300 +#define AR_VIDEO_STEREO_MODE_RESERVED0 0x0340 +#define AR_VIDEO_STEREO_MODE_RESERVED1 0x0380 +#define AR_VIDEO_STEREO_MODE_RESERVED2 0x03C0 + +#define AR_VIDEO_SOURCE_INFO_FLAG_OFFLINE 0x0001 // 0 = unknown or not offline, 1 = offline. +#define AR_VIDEO_SOURCE_INFO_FLAG_IN_USE 0x0002 // 0 = unknown or not in use, 1 = in use. +#define AR_VIDEO_SOURCE_INFO_FLAG_OPEN_ASYNC 0x0004 // 0 = open normally, 1 = open async. +#define AR_VIDEO_SOURCE_INFO_POSITION_MASK 0x0038 // compare (value & AR_VIDEO_SOURCE_INFO_POSITION_MASK) against enums. +#define AR_VIDEO_SOURCE_INFO_STEREO_MODE_MASK 0x03C0 // compare (value & AR_VIDEO_SOURCE_INFO_STEREO_MODE_MASK) against enums. + +typedef struct { + char *name; // UTF-8 encoded string. + char *UID; // UTF-8 encoded string. + unsigned int flags; +} ARVideoSourceInfoT; + +typedef struct { + int count; + ARVideoSourceInfoT *info; +} ARVideoSourceInfoListT; + +typedef void (*AR_VIDEO_FRAME_READY_CALLBACK)(void *); + +#ifdef _WIN32 +# ifndef LIBARVIDEO_STATIC +# ifdef LIBARVIDEO_EXPORTS +# define AR_DLL_API __declspec(dllexport) +# else +# define AR_DLL_API __declspec(dllimport) +# endif +# else +# define AR_DLL_API extern +# endif +#else +# define AR_DLL_API +#endif + +#ifdef AR_INPUT_DUMMY +#include +#endif +#ifdef AR_INPUT_V4L +#include +#endif +#ifdef AR_INPUT_DV +#include +#endif +#ifdef AR_INPUT_1394CAM +#include +#endif +#ifdef AR_INPUT_SGI +#include +#endif +#ifdef AR_INPUT_WINDOWS_DIRECTSHOW +#include +#endif +#ifdef AR_INPUT_WINDOWS_DSVIDEOLIB +#include +#endif +#ifdef AR_INPUT_WINDOWS_DRAGONFLY +#include +#endif +#ifdef AR_INPUT_QUICKTIME +#include +#endif +#ifdef AR_INPUT_GSTREAMER +#include +#endif +#ifdef AR_INPUT_IPHONE +#include +#endif +#ifdef AR_INPUT_QUICKTIME7 +#include +#endif +#ifdef AR_INPUT_IMAGE +#include +#endif +#ifdef AR_INPUT_ANDROID +#include +#endif +#ifdef AR_INPUT_WINDOWS_MEDIA_FOUNDATION +#include +#endif +#ifdef AR_INPUT_WINDOWS_MEDIA_CAPTURE +#include +#endif + + +typedef union { +#ifdef AR_INPUT_DUMMY + AR2VideoParamDummyT *dummy; +#endif +#ifdef AR_INPUT_V4L + AR2VideoParamV4LT *v4l; +#endif +#ifdef AR_INPUT_DV + AR2VideoParamDVT *dv; +#endif +#ifdef AR_INPUT_1394CAM + AR2VideoParam1394T *cam1394; +#endif +#ifdef AR_INPUT_SGI + AR2VideoParamSGIT *sgi; +#endif +#ifdef AR_INPUT_WINDOWS_DIRECTSHOW + AR2VideoParamWinDST *winDS; +#endif +#ifdef AR_INPUT_WINDOWS_DSVIDEOLIB + AR2VideoParamWinDSVLT *winDSVL; +#endif +#ifdef AR_INPUT_WINDOWS_DRAGONFLY + AR2VideoParamWinDFT *winDF; +#endif +#ifdef AR_INPUT_QUICKTIME + AR2VideoParamQuickTimeT *quickTime; +#endif +#ifdef AR_INPUT_GSTREAMER + AR2VideoParamGStreamerT *gstreamer; +#endif +#ifdef AR_INPUT_IPHONE + AR2VideoParamiPhoneT *iPhone; +#endif +#ifdef AR_INPUT_QUICKTIME7 + AR2VideoParamQuickTime7T *quickTime7; +#endif +#ifdef AR_INPUT_IMAGE + AR2VideoParamImageT *image; +#endif +#ifdef AR_INPUT_ANDROID + AR2VideoParamAndroidT *android; +#endif +#ifdef AR_INPUT_WINDOWS_MEDIA_FOUNDATION + AR2VideoParamWinMFT *winMF; +#endif +#ifdef AR_INPUT_WINDOWS_MEDIA_CAPTURE + AR2VideoParamWinMCT *winMC; +#endif +} AR2VideoDeviceHandleT; + +typedef struct { + int deviceType; + AR2VideoDeviceHandleT device; +} AR2VideoParamT; + +AR_DLL_API int arVideoGetDefaultDevice(void); +AR_DLL_API int arVideoOpen (const char *config); +AR_DLL_API int arVideoOpenAsync (const char *config, void (*callback)(void *), void *userdata); +AR_DLL_API int arVideoClose (void); +AR_DLL_API int arVideoDispOption (void); +AR_DLL_API int arVideoGetDevice (void); +AR_DLL_API int arVideoGetId (ARUint32 *id0, ARUint32 *id1); +AR_DLL_API int arVideoGetSize (int *x, int *y); +AR_DLL_API int arVideoGetPixelSize (void); +AR_DLL_API AR_PIXEL_FORMAT arVideoGetPixelFormat (void); +AR_DLL_API ARUint8 *arVideoGetImage (void); +AR_DLL_API int arVideoCapStart (void); +AR_DLL_API int arVideoCapStartAsync (AR_VIDEO_FRAME_READY_CALLBACK callback, void *userdata); +AR_DLL_API int arVideoCapStop (void); +AR_DLL_API int arVideoGetParami (int paramName, int *value); +AR_DLL_API int arVideoSetParami (int paramName, int value); +AR_DLL_API int arVideoGetParamd (int paramName, double *value); +AR_DLL_API int arVideoSetParamd (int paramName, double value); +AR_DLL_API int arVideoGetParams (const int paramName, char *value); +AR_DLL_API int arVideoSetParams (const int paramName, const char *value); +AR_DLL_API int arVideoSaveParam (char *filename); +AR_DLL_API int arVideoLoadParam (char *filename); +AR_DLL_API int arVideoSetBufferSize (const int width, const int height); +AR_DLL_API int arVideoGetBufferSize (int *width, int *height); +AR_DLL_API int arVideoGetCParam (ARParam *cparam); +AR_DLL_API int arVideoGetCParamAsync (void (*callback)(const ARParam *, void *), void *userdata); + +AR_DLL_API int arVideoUtilGetPixelSize(const AR_PIXEL_FORMAT arPixelFormat); +AR_DLL_API const char *arVideoUtilGetPixelFormatName(const AR_PIXEL_FORMAT arPixelFormat); +#if !AR_ENABLE_MINIMIZE_MEMORY_FOOTPRINT +AR_DLL_API int arVideoSaveImageJPEG(int w, int h, AR_PIXEL_FORMAT pixFormat, ARUint8 *pixels, const char *filename, const int quality /* 0 to 100 */, const int flipV); +#endif // !AR_ENABLE_MINIMIZE_MEMORY_FOOTPRINT + +typedef enum { + AR_VIDEO_ASPECT_RATIO_1_1, // 1.0: + AR_VIDEO_ASPECT_RATIO_11_9, // 1.222: 176x144 (QCIF), 352x288 (CIF) + AR_VIDEO_ASPECT_RATIO_5_4, // 1.25: 1280x1024 (SXGA), 2560x2048 + AR_VIDEO_ASPECT_RATIO_4_3, // 1.333: 320x240 (QVGA), 480x360, 640x480 (VGA), 768x576 (576p), 800x600 (SVGA), 960x720, 1024x768 (XGA), 1152x864, 1280x960, 1400x1050, 1600x1200, 2048x1536 + AR_VIDEO_ASPECT_RATIO_3_2, // 1.5: 240x160, 480x320, 960x640, 720x480 (480p), 1152x768, 1280x854, 1440x960 + AR_VIDEO_ASPECT_RATIO_14_9, // 1.556: + AR_VIDEO_ASPECT_RATIO_8_5, // 1.6: 320x200, 1280x800, 1440x900, 1680x1050, 1920x1200, 2560x1600 + + AR_VIDEO_ASPECT_RATIO_5_3, // 1.667: 800x480, 1280x768, 1600x960 + AR_VIDEO_ASPECT_RATIO_16_9, // 1.778: 1280x720 (720p), 1920x1080 (1080p) + AR_VIDEO_ASPECT_RATIO_9_5, // 1.8: 864x480 + AR_VIDEO_ASPECT_RATIO_17_9, // 1.889: 2040x1080 + AR_VIDEO_ASPECT_RATIO_UNIQUE +} AR_VIDEO_ASPECT_RATIO; + +/*! + @function + @abstract Determine the approximate aspect ratio for a given image resolution. + @discussion + A convenience method which makes it easy to determine the approximate aspect ratio + of an image with the given resolution (expressed in pixel width and height). + Returns a symbolic constant for the aspect ratio, which makes it easy to determine + whether two different resolutions have the same aspect ratio. Assumes square pixels. + @param w Width in pixels + @param h Height in pixels + @result If a matching commonly-used aspect ratio can be found, returns symbolic constant for that aspect ratio. +*/ +AR_VIDEO_ASPECT_RATIO arVideoUtilFindAspectRatio(int w, int h); + +/*! + @function + @abstract Determine the approximate aspect ratio for a given image resolution. + @discussion + A convenience method which makes it easy to determine the approximate aspect ratio + of an image with the given resolution (expressed in pixel width and height). + Returns a string for the aspect ratio. Assumes square pixels. + @param w Width in pixels + @param h Height in pixels + @result If a matching commonly-used aspect ratio can be found, returns string name for that aspect ratio. This string must be free'd when finished with. +*/ +char *arVideoUtilFindAspectRatioName(int w, int h); + +/*! + @function arVideoGetVersion + @abstract Get the version of ARToolKit with which the arVideo library was built. + @discussion + It is highly recommended that + any calling program that depends on features in a certain + ARToolKit version, check at runtime that it is linked to a version + of ARToolKit that can supply those features. It is NOT sufficient + to check the ARToolKit SDK header versions, since with ARToolKit implemented + in dynamically-loaded libraries, there is no guarantee that the + version of ARToolKit installed on the machine at run-time will be as + recent as the version of the ARToolKit SDK which the host + program was compiled against. + @result + Returns the full version number of the ARToolKit version corresponding + to this video library, in binary coded decimal (BCD) format. + + BCD format allows simple tests of version number in the caller + e.g. if ((arGetVersion(NULL) >> 16) > 0x0272) printf("This release is later than 2.72\n"); + + The major version number is encoded in the most-significant byte + (bits 31-24), the minor version number in the second-most-significant + byte (bits 23-16), the tiny version number in the third-most-significant + byte (bits 15-8), and the build version number in the least-significant + byte (bits 7-0). + + If the returned value is equal to -1, it can be assumed that the actual + version is in the range 0x04000000 to 0x04040100. + @availability Available in ARToolKit v4.4.2 and later. The underlying + functionality can also be used when compiling against earlier versions of + ARToolKit (v4.0 to 4.4.1) with a slightly different syntax: replace + "arVideoGetVersion()" in your code with "arVideoGetParami(AR_VIDEO_GET_VERSION, NULL)". + */ +#define arVideoGetVersion() arVideoGetParami(AR_VIDEO_GET_VERSION, NULL) + +AR_DLL_API ARVideoSourceInfoListT *ar2VideoCreateSourceInfoList(const char *config); +AR_DLL_API void ar2VideoDeleteSourceInfoList(ARVideoSourceInfoListT **p); +AR_DLL_API AR2VideoParamT *ar2VideoOpen (const char *config); +AR_DLL_API AR2VideoParamT *ar2VideoOpenAsync (const char *config, void (*callback)(void *), void *userdata); +AR_DLL_API int ar2VideoClose (AR2VideoParamT *vid); +AR_DLL_API int ar2VideoDispOption (AR2VideoParamT *vid); +AR_DLL_API int ar2VideoGetDevice (AR2VideoParamT *vid); +AR_DLL_API int ar2VideoGetId (AR2VideoParamT *vid, ARUint32 *id0, ARUint32 *id1); +AR_DLL_API int ar2VideoGetSize (AR2VideoParamT *vid, int *x,int *y); +AR_DLL_API int ar2VideoGetPixelSize (AR2VideoParamT *vid); +AR_DLL_API AR_PIXEL_FORMAT ar2VideoGetPixelFormat (AR2VideoParamT *vid); +AR_DLL_API AR2VideoBufferT *ar2VideoGetImage (AR2VideoParamT *vid); +AR_DLL_API int ar2VideoCapStart (AR2VideoParamT *vid); +AR_DLL_API int ar2VideoCapStartAsync (AR2VideoParamT *vid, AR_VIDEO_FRAME_READY_CALLBACK callback, void *userdata); +AR_DLL_API int ar2VideoCapStop (AR2VideoParamT *vid); +AR_DLL_API int ar2VideoGetParami (AR2VideoParamT *vid, int paramName, int *value); +AR_DLL_API int ar2VideoSetParami (AR2VideoParamT *vid, int paramName, int value); +AR_DLL_API int ar2VideoGetParamd (AR2VideoParamT *vid, int paramName, double *value); +AR_DLL_API int ar2VideoSetParamd (AR2VideoParamT *vid, int paramName, double value); +AR_DLL_API int ar2VideoGetParams (AR2VideoParamT *vid, const int paramName, char **value); +AR_DLL_API int ar2VideoSetParams (AR2VideoParamT *vid, const int paramName, const char *value); +AR_DLL_API int ar2VideoSaveParam (AR2VideoParamT *vid, char *filename); +AR_DLL_API int ar2VideoLoadParam (AR2VideoParamT *vid, char *filename); +AR_DLL_API int ar2VideoSetBufferSize (AR2VideoParamT *vid, const int width, const int height); +AR_DLL_API int ar2VideoGetBufferSize (AR2VideoParamT *vid, int *width, int *height); +AR_DLL_API int ar2VideoGetCParam (AR2VideoParamT *vid, ARParam *cparam); +AR_DLL_API int ar2VideoGetCParamAsync (AR2VideoParamT *vid, void (*callback)(const ARParam *, void *), void *userdata); +#ifdef __cplusplus +} +#endif +#endif diff --git a/libs/include/AR/videoConfig.h b/libs/include/AR/videoConfig.h new file mode 100755 index 0000000..68c578c --- /dev/null +++ b/libs/include/AR/videoConfig.h @@ -0,0 +1,143 @@ +/* + * videoConfig.h + * ARToolKit5 + * + * This file is part of ARToolKit. + * + * ARToolKit is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ARToolKit is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ARToolKit. If not, see . + * + * As a special exception, the copyright holders of this library give you + * permission to link this library with independent modules to produce an + * executable, regardless of the license terms of these independent modules, and to + * copy and distribute the resulting executable under terms of your choice, + * provided that you also meet, for each linked independent module, the terms and + * conditions of the license of that module. An independent module is a module + * which is neither derived from nor based on this library. If you modify this + * library, you may extend this exception to your version of the library, but you + * are not obligated to do so. If you do not wish to do so, delete this exception + * statement from your version. + * + * Copyright 2015 Daqri, LLC. + * Copyright 2002-2015 ARToolworks, Inc. + * + * Author(s): Hirokazu Kato, Philip Lamb + * + */ + +#ifndef AR_CONFIG_H +#define AR_CONFIG_H + +#include + +#ifdef AR_INPUT_V4L +#define AR_VIDEO_V4L_MODE_PAL 0 +#define AR_VIDEO_V4L_MODE_NTSC 1 +#define AR_VIDEO_V4L_MODE_SECAM 2 +#define AR_VIDEO_V4L_DEFAULT_DEVICE "/dev/video0" +#define AR_VIDEO_V4L_DEFAULT_WIDTH 640 +#define AR_VIDEO_V4L_DEFAULT_HEIGHT 480 +#define AR_VIDEO_V4L_DEFAULT_CHANNEL 3 +#define AR_VIDEO_V4L_DEFAULT_MODE AR_VIDEO_V4L_MODE_NTSC +#endif + +#ifdef AR_INPUT_1394CAM +#define AR_VIDEO_1394_MODE_320x240_YUV422 32 +#define AR_VIDEO_1394_MODE_640x480_YUV411 33 +#define AR_VIDEO_1394_MODE_640x480_YUV411_HALF 34 +#define AR_VIDEO_1394_MODE_640x480_YUV422 35 +#define AR_VIDEO_1394_MODE_640x480_RGB 36 +#define AR_VIDEO_1394_MODE_640x480_MONO 37 +#define AR_VIDEO_1394_MODE_640x480_MONO_COLOR 38 +#define AR_VIDEO_1394_MODE_640x480_MONO_COLOR_HALF 39 +#define AR_VIDEO_1394_MODE_640x480_MONO_COLOR2 40 +#define AR_VIDEO_1394_MODE_640x480_MONO_COLOR_HALF2 41 +#define AR_VIDEO_1394_MODE_640x480_MONO_COLOR3 42 +#define AR_VIDEO_1394_MODE_640x480_MONO_COLOR_HALF3 43 +#define AR_VIDEO_1394_MODE_1024x768_MONO 44 +#define AR_VIDEO_1394_MODE_1024x768_MONO_COLOR 45 +#define AR_VIDEO_1394_MODE_1024x768_MONO_COLOR_HALF 46 +#define AR_VIDEO_1394_MODE_1024x768_MONO_COLOR2 47 +#define AR_VIDEO_1394_MODE_1024x768_MONO_COLOR_HALF2 48 +#define AR_VIDEO_1394_MODE_1024x768_MONO_COLOR3 49 +#define AR_VIDEO_1394_MODE_1024x768_MONO_COLOR_HALF3 50 +#define AR_VIDEO_1394_MODE_1280x720_MONO 51 +#define AR_VIDEO_1394_MODE_1280x720_MONO_COLOR 52 +#define AR_VIDEO_1394_MODE_1280x720_MONO_COLOR_HALF 53 +#define AR_VIDEO_1394_MODE_1280x720_MONO_COLOR2 54 +#define AR_VIDEO_1394_MODE_1280x720_MONO_COLOR_HALF2 55 +#define AR_VIDEO_1394_MODE_1280x720_MONO_COLOR3 56 +#define AR_VIDEO_1394_MODE_1280x720_MONO_COLOR_HALF3 57 +#define AR_VIDEO_1394_MODE_1600x900_MONO 58 +#define AR_VIDEO_1394_MODE_1600x900_MONO_COLOR 59 +#define AR_VIDEO_1394_MODE_1600x900_MONO_COLOR_HALF 60 +#define AR_VIDEO_1394_MODE_1600x900_MONO_COLOR2 61 +#define AR_VIDEO_1394_MODE_1600x900_MONO_COLOR_HALF2 62 +#define AR_VIDEO_1394_MODE_1600x900_MONO_COLOR3 63 +#define AR_VIDEO_1394_MODE_1600x900_MONO_COLOR_HALF3 64 +#define AR_VIDEO_1394_MODE_1600x1200_MONO 65 +#define AR_VIDEO_1394_MODE_1600x1200_MONO_COLOR 66 +#define AR_VIDEO_1394_MODE_1600x1200_MONO_COLOR_HALF 67 +#define AR_VIDEO_1394_MODE_1600x1200_MONO_COLOR2 68 +#define AR_VIDEO_1394_MODE_1600x1200_MONO_COLOR_HALF2 69 +#define AR_VIDEO_1394_MODE_1600x1200_MONO_COLOR3 70 +#define AR_VIDEO_1394_MODE_1600x1200_MONO_COLOR_HALF3 71 +#define AR_VIDEO_1394_FRAME_RATE_1_875 1 +#define AR_VIDEO_1394_FRAME_RATE_3_75 2 +#define AR_VIDEO_1394_FRAME_RATE_7_5 3 +#define AR_VIDEO_1394_FRAME_RATE_15 4 +#define AR_VIDEO_1394_FRAME_RATE_30 5 +#define AR_VIDEO_1394_FRAME_RATE_60 6 +#define AR_VIDEO_1394_FRAME_RATE_120 7 +#define AR_VIDEO_1394_FRAME_RATE_240 8 +#define AR_VIDEO_1394_SPEED_400 1 +#define AR_VIDEO_1394_SPEED_800 2 + +#if AR_INPUT_1394CAM_DEFAULT_PIXEL_FORMAT == AR_PIXEL_FORMAT_MONO +#if defined(AR_INPUT_1394CAM_USE_FLEA_XGA) +#define AR_VIDEO_1394_DEFAULT_MODE AR_VIDEO_1394_MODE_1024x768_MONO +#else +#define AR_VIDEO_1394_DEFAULT_MODE AR_VIDEO_1394_MODE_640x480_MONO +#endif +#else +#if defined(AR_INPUT_1394CAM_USE_DRAGONFLY) +#define AR_VIDEO_1394_DEFAULT_MODE AR_VIDEO_1394_MODE_640x480_MONO_COLOR +#elif defined(AR_INPUT_1394CAM_USE_DF_EXPRESS) +#define AR_VIDEO_1394_DEFAULT_MODE AR_VIDEO_1394_MODE_640x480_MONO_COLOR2 +#elif defined(AR_INPUT_1394CAM_USE_FLEA) +#define AR_VIDEO_1394_DEFAULT_MODE AR_VIDEO_1394_MODE_640x480_MONO_COLOR2 +#elif defined(AR_INPUT_1394CAM_USE_FLEA_XGA) +#define AR_VIDEO_1394_DEFAULT_MODE AR_VIDEO_1394_MODE_1024x768_MONO_COLOR +#elif defined(AR_INPUT_1394CAM_USE_DFK21AF04) +#define AR_VIDEO_1394_DEFAULT_MODE AR_VIDEO_1394_MODE_640x480_MONO_COLOR3 +#else +#define AR_VIDEO_1394_DEFAULT_MODE AR_VIDEO_1394_MODE_640x480_YUV411 +#endif +#endif +#define AR_VIDEO_1394_DEFAULT_FRAME_RATE AR_VIDEO_1394_FRAME_RATE_30 +#define AR_VIDEO_1394_DEFAULT_SPEED AR_VIDEO_1394_SPEED_400 +#define AR_VIDEO_1394_DEFAULT_PORT 0 +#endif + + +#ifdef AR_INPUT_WINDOWS_DIRECTSHOW +#endif + +#ifdef AR_INPUT_WINDOWS_DRAGONFLY +#endif + + +#ifdef AR_INPUT_QUICKTIME +#endif + +#endif // !AR_CONFIG_H diff --git a/libs/include/AR2/config.h b/libs/include/AR2/config.h new file mode 100755 index 0000000..71d1507 --- /dev/null +++ b/libs/include/AR2/config.h @@ -0,0 +1,143 @@ +/* + * AR2/config.h + * ARToolKit5 + * + * This file is part of ARToolKit. + * + * ARToolKit is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ARToolKit is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ARToolKit. If not, see . + * + * As a special exception, the copyright holders of this library give you + * permission to link this library with independent modules to produce an + * executable, regardless of the license terms of these independent modules, and to + * copy and distribute the resulting executable under terms of your choice, + * provided that you also meet, for each linked independent module, the terms and + * conditions of the license of that module. An independent module is a module + * which is neither derived from nor based on this library. If you modify this + * library, you may extend this exception to your version of the library, but you + * are not obligated to do so. If you do not wish to do so, delete this exception + * statement from your version. + * + * Copyright 2015 Daqri, LLC. + * Copyright 2006-2015 ARToolworks, Inc. + * + * Author(s): Hirokazu Kato, Philip Lamb + * + */ + +#ifndef AR2_CONFIG_H +#define AR2_CONFIG_H +#ifdef __cplusplus +extern "C" { +#endif + +// The MAJOR version number defines non-backwards compatible +// changes in the ARToolKit NFT API. Range: [0-99]. +#define AR2_HEADER_VERSION_MAJOR 4 + +// The MINOR version number defines additions to the ARToolKit NFT +// API, or (occsasionally) other significant backwards-compatible +// changes in runtime functionality. Range: [0-99]. +#define AR2_HEADER_VERSION_MINOR 0 + +// The TINY version number defines bug-fixes to existing +// functionality. Range: [0-99]. +#define AR2_HEADER_VERSION_TINY 0 + +// The BUILD version number will always be zero in releases, +// but may be non-zero in internal builds or in version-control +// repository-sourced code. Range: [0-99]. +#define AR2_HEADER_VERSION_BUILD 0 + +// The string representation below must match the major, minor +// and tiny release numbers. +#define AR2_HEADER_VERSION_STRING "4.0.0" + +// The macros below are convenience macros to enable use +// of certain ARToolKit NFT header functionality by the release +// version in which it appeared. +// Each time the major version number is incremented, all +// existing macros must be removed, and just one new one +// added for the new major version. +// Each time the minor version number is incremented, a new +// AR_HAVE_HEADER_VERSION_ macro definition must be added. +// Tiny version numbers (being bug-fix releases, by definition) +// are NOT included in the AR_HAVE_HEADER_VERSION_ system. +#define AR2_HAVE_HEADER_VERSION_4 +//#define AR2_HAVE_HEADER_VERSION_4_1 + + + +#define AR2_CAPABLE_ADAPTIVE_TEMPLATE 0 + +// Template scalefactor. +#define AR2_TEMP_SCALE 2 + +#if AR2_CAPABLE_ADAPTIVE_TEMPLATE +#define AR2_CONSTANT_BLUR 0 +#define AR2_ADAPTIVE_BLUR 2 +#define AR2_DEFAULT_BLUR_METHOD AR2_CONSTANT_BLUR +#define AR2_DEFAULT_BLUR_LEVEL 1 +#endif + + +#define AR2_THREAD_MAX 8 + +#define AR2_DEFAULT_SEARCH_SIZE 25 // Default radius of feature search window. + +#define AR2_DEFAULT_SEARCH_FEATURE_NUM 10 // May not be higher than AR2_SEARCH_FEATURE_MAX. + +#define AR2_DEFAULT_TS1 11 // Template size 1. Multiplied by AR2_TEMP_SCALE to give number of pixels outside centre pixel in negative x/y axis. +#define AR2_DEFAULT_TS2 11 // Template size 2. Multiplied by AR2_TEMP_SCALE to give number of pixels outside centre pixel in positive x/y axis. + +#define AR2_DEFAULT_SIM_THRESH 0.6F + +#define AR2_DEFAULT_TRACKING_THRESH 2.0F + + + +/* tracking.c */ +#define AR2_TRACKING_SURFACE_MAX 10 // Maximum number of surfaces per surface set (i.e. maximum number of discrete surfaces with fixed relationship to each other able to be combined into a surface set.) +#define AR2_TRACKING_CANDIDATE_MAX 200 // Maximum number of candidate feature points. + +/* tracking2d.c */ +#define AR2_DEFAULT_TRACKING_SD_THRESH 5.0F +#define AR2_SEARCH_FEATURE_MAX 40 + + +/* genFeatureSet.c */ +#define AR2_DEFAULT_MAX_SIM_THRESH_L0 0.80F +#define AR2_DEFAULT_MAX_SIM_THRESH_L1 0.85F +#define AR2_DEFAULT_MAX_SIM_THRESH_L2 0.90F +#define AR2_DEFAULT_MAX_SIM_THRESH_L3 0.98F +#define AR2_DEFAULT_MIN_SIM_THRESH_L0 0.70F +#define AR2_DEFAULT_MIN_SIM_THRESH_L1 0.65F +#define AR2_DEFAULT_MIN_SIM_THRESH_L2 0.55F +#define AR2_DEFAULT_MIN_SIM_THRESH_L3 0.45F +#define AR2_DEFAULT_SD_THRESH_L0 12.0F +#define AR2_DEFAULT_SD_THRESH_L1 10.0F +#define AR2_DEFAULT_SD_THRESH_L2 8.0F +#define AR2_DEFAULT_SD_THRESH_L3 6.0F +#define AR2_DEFAULT_OCCUPANCY_SIZE 24 + +/* genFeatureMap.c genFeatureSet.c */ +#define AR2_DEFAULT_GEN_FEATURE_MAP_SEARCH_SIZE1 10 +#define AR2_DEFAULT_GEN_FEATURE_MAP_SEARCH_SIZE2 2 +#define AR2_DEFAULT_MAX_SIM_THRESH2 0.95F +#define AR2_DEFAULT_SD_THRESH2 5.0F + + +#ifdef __cplusplus +} +#endif +#endif diff --git a/libs/include/AR2/coord.h b/libs/include/AR2/coord.h new file mode 100755 index 0000000..106ade2 --- /dev/null +++ b/libs/include/AR2/coord.h @@ -0,0 +1,72 @@ +/* + * AR2/coord.h + * ARToolKit5 + * + * This file is part of ARToolKit. + * + * ARToolKit is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ARToolKit is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ARToolKit. If not, see . + * + * As a special exception, the copyright holders of this library give you + * permission to link this library with independent modules to produce an + * executable, regardless of the license terms of these independent modules, and to + * copy and distribute the resulting executable under terms of your choice, + * provided that you also meet, for each linked independent module, the terms and + * conditions of the license of that module. An independent module is a module + * which is neither derived from nor based on this library. If you modify this + * library, you may extend this exception to your version of the library, but you + * are not obligated to do so. If you do not wish to do so, delete this exception + * statement from your version. + * + * Copyright 2015 Daqri, LLC. + * Copyright 2006-2015 ARToolworks, Inc. + * + * Author(s): Hirokazu Kato, Philip Lamb + * + */ + +#ifndef AR2_COORD_H +#define AR2_COORD_H + +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* coord.c */ +int ar2MarkerCoord2ScreenCoord( ARParamLT *cparamLT, float trans[3][4], float mx, float my, float *sx, float *sy ); +int ar2MarkerCoord2ScreenCoord2( ARParamLT *cparamLT, float trans[3][4], float mx, float my, float *sx, float *sy ); + +int ar2ScreenCoord2MarkerCoord( ARParamLT *cparamLT, float trans[3][4], float sx, float sy, float *mx, float *my ); + +int ar2MarkerCoord2ImageCoord( int xsize, int ysize, float dpi, float mx, float my, float *ix, float *iy ); + +int ar2ImageCoord2MarkerCoord2( int xsize, int ysize, float dpi, float ix, float iy, float *mx, float *my ); + +#if AR2_CAPABLE_ADAPTIVE_TEMPLATE +int ar2GetImageValue( ARParamLT *cparamLT, float trans[3][4], AR2ImageT *image, + float sx, float sy, int blurLevel, ARUint8 *pBW ); +int ar2GetImageValue2( ARParamLT *cparamLT, float trans[3][4], AR2ImageT *image, + float sx, float sy, int blurLevel, ARUint8 *pBW1, ARUint8 *pBW2, ARUint8 *pBW3 ); +#else +int ar2GetImageValue( ARParamLT *cparamLT, float trans[3][4], AR2ImageT *image, + float sx, float sy, ARUint8 *pBW ); +#endif + +#ifdef __cplusplus +} +#endif +#endif diff --git a/libs/include/AR2/featureSet.h b/libs/include/AR2/featureSet.h new file mode 100755 index 0000000..97b1d6f --- /dev/null +++ b/libs/include/AR2/featureSet.h @@ -0,0 +1,107 @@ +/* + * AR2/featureSet.h + * ARToolKit5 + * + * This file is part of ARToolKit. + * + * ARToolKit is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ARToolKit is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ARToolKit. If not, see . + * + * As a special exception, the copyright holders of this library give you + * permission to link this library with independent modules to produce an + * executable, regardless of the license terms of these independent modules, and to + * copy and distribute the resulting executable under terms of your choice, + * provided that you also meet, for each linked independent module, the terms and + * conditions of the license of that module. An independent module is a module + * which is neither derived from nor based on this library. If you modify this + * library, you may extend this exception to your version of the library, but you + * are not obligated to do so. If you do not wish to do so, delete this exception + * statement from your version. + * + * Copyright 2015 Daqri, LLC. + * Copyright 2006-2015 ARToolworks, Inc. + * + * Author(s): Hirokazu Kato, Philip Lamb + * + */ + +#ifndef AR2_FEATURE_SET_H +#define AR2_FEATURE_SET_H +#include +#include + + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct { + float *map; + int xsize; + int ysize; +} AR2FeatureMapT; + +typedef struct { + int x; + int y; + float mx; + float my; + float maxSim; +} AR2FeatureCoordT; + +// One AR2FeaturePointsT holds the feature coordinates for one scalefactor of one image. +typedef struct { + AR2FeatureCoordT *coord; + int num; + int scale; + float maxdpi; + float mindpi; +} AR2FeaturePointsT; + +// Structure to hold a set of one or more AR2FeaturePointsT structures for one image. +typedef struct { + AR2FeaturePointsT *list; + int num; +} AR2FeatureSetT; + + +AR2FeatureMapT *ar2GenFeatureMap( AR2ImageT *image, + int ts1, int ts2, + int search_size1, int search_size2, + float max_sim_thresh, float sd_thresh ); + +AR2FeatureMapT *ar2ReadFeatureMap( char *filename, char *ext ); + +int ar2SaveFeatureMap( char *filename, char *ext, AR2FeatureMapT *featureMap ); + +int ar2FreeFeatureMap( AR2FeatureMapT *featureMap ); + + +int ar2PrintFeatureInfo( AR2ImageT *image, AR2FeatureMapT *featureMap, int ts1, int ts2, int search_size2, int cx, int cy ); + +AR2FeatureCoordT *ar2SelectFeature( AR2ImageT *image, AR2FeatureMapT *featureMap, + int ts1, int ts2, int search_size2, int occ_size, + float max_sim_thresh, float min_sim_thresh, float sd_thresh, int *num ); + +AR2FeatureCoordT *ar2SelectFeature2( AR2ImageT *image, AR2FeatureMapT *featureMap, + int ts1, int ts2, int search_size2, int occ_size, + float max_sim_thresh, float min_sim_thresh, float sd_thresh, int *num ); + +AR2FeatureSetT *ar2ReadFeatureSet( char *filename, char *ext ); +int ar2SaveFeatureSet( char *filename, char *ext, AR2FeatureSetT *featureSet ); +int ar2FreeFeatureSet( AR2FeatureSetT **featureSet ); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/libs/include/AR2/imageFormat.h b/libs/include/AR2/imageFormat.h new file mode 100755 index 0000000..9b2e543 --- /dev/null +++ b/libs/include/AR2/imageFormat.h @@ -0,0 +1,69 @@ +/* + * AR2/imageFormat.h + * ARToolKit5 + * + * This file is part of ARToolKit. + * + * ARToolKit is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ARToolKit is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ARToolKit. If not, see . + * + * As a special exception, the copyright holders of this library give you + * permission to link this library with independent modules to produce an + * executable, regardless of the license terms of these independent modules, and to + * copy and distribute the resulting executable under terms of your choice, + * provided that you also meet, for each linked independent module, the terms and + * conditions of the license of that module. An independent module is a module + * which is neither derived from nor based on this library. If you modify this + * library, you may extend this exception to your version of the library, but you + * are not obligated to do so. If you do not wish to do so, delete this exception + * statement from your version. + * + * Copyright 2015 Daqri, LLC. + * Copyright 2006-2015 ARToolworks, Inc. + * + * Author(s): Hirokazu Kato, Philip Lamb + * + */ + +#ifndef AR2_IMAGE_FORMAT_H +#define AR2_IMAGE_FORMAT_H +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include + +#define AR2_DEFAULT_JPEG_IMAGE_QUALITY 80 + + +typedef struct { + ARUint8 *image; + int nc; + int xsize; + int ysize; + float dpi; +} AR2JpegImageT; + +/* jpeg.c */ + +AR2JpegImageT *ar2ReadJpegImage ( const char *filename, const char *ext ); +AR2JpegImageT *ar2ReadJpegImage2 ( FILE *fp ); +int ar2WriteJpegImage ( const char *filename, const char *ext, AR2JpegImageT *jpegImage, int quality ); +int ar2WriteJpegImage2( FILE *fp, AR2JpegImageT *jpegImage, int quality ); +int ar2FreeJpegImage ( AR2JpegImageT **jpegImage ); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/libs/include/AR2/imageSet.h b/libs/include/AR2/imageSet.h new file mode 100755 index 0000000..80363ad --- /dev/null +++ b/libs/include/AR2/imageSet.h @@ -0,0 +1,77 @@ +/* + * AR2/imageSet.h + * ARToolKit5 + * + * This file is part of ARToolKit. + * + * ARToolKit is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ARToolKit is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ARToolKit. If not, see . + * + * As a special exception, the copyright holders of this library give you + * permission to link this library with independent modules to produce an + * executable, regardless of the license terms of these independent modules, and to + * copy and distribute the resulting executable under terms of your choice, + * provided that you also meet, for each linked independent module, the terms and + * conditions of the license of that module. An independent module is a module + * which is neither derived from nor based on this library. If you modify this + * library, you may extend this exception to your version of the library, but you + * are not obligated to do so. If you do not wish to do so, delete this exception + * statement from your version. + * + * Copyright 2015 Daqri, LLC. + * Copyright 2006-2015 ARToolworks, Inc. + * + * Author(s): Hirokazu Kato, Philip Lamb + * + */ + +#ifndef AR2_IMAGE_SET_H +#define AR2_IMAGE_SET_H +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#if AR2_CAPABLE_ADAPTIVE_TEMPLATE +#define AR2_BLUR_IMAGE_MAX 5 +#endif + + +typedef struct { +#if AR2_CAPABLE_ADAPTIVE_TEMPLATE + ARUint8 *imgBWBlur[AR2_BLUR_IMAGE_MAX]; +#else + ARUint8 *imgBW; +#endif + int xsize; + int ysize; + float dpi; +} AR2ImageT; + +typedef struct { + AR2ImageT **scale; + int32_t num; +} AR2ImageSetT; + +/* image.c */ +AR2ImageSetT *ar2GenImageSet ( ARUint8 *image, int xsize, int ysize, int nc, float dpi, float dpi_list[], int dpi_num ); +AR2ImageSetT *ar2ReadImageSet ( char *filename ); +int ar2WriteImageSet ( char *filename, AR2ImageSetT *imageSet ); +int ar2FreeImageSet ( AR2ImageSetT **imageSet ); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/libs/include/AR2/marker.h b/libs/include/AR2/marker.h new file mode 100755 index 0000000..557da4d --- /dev/null +++ b/libs/include/AR2/marker.h @@ -0,0 +1,66 @@ +/* + * AR2/marker.h + * ARToolKit5 + * + * This file is part of ARToolKit. + * + * ARToolKit is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ARToolKit is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ARToolKit. If not, see . + * + * As a special exception, the copyright holders of this library give you + * permission to link this library with independent modules to produce an + * executable, regardless of the license terms of these independent modules, and to + * copy and distribute the resulting executable under terms of your choice, + * provided that you also meet, for each linked independent module, the terms and + * conditions of the license of that module. An independent module is a module + * which is neither derived from nor based on this library. If you modify this + * library, you may extend this exception to your version of the library, but you + * are not obligated to do so. If you do not wish to do so, delete this exception + * statement from your version. + * + * Copyright 2015 Daqri, LLC. + * Copyright 2006-2015 ARToolworks, Inc. + * + * Author(s): Hirokazu Kato, Philip Lamb + * + */ + +#ifndef AR2_MARKER_H +#define AR2_MARKER_H +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct { + float width; + int pattId; + float transI2M[3][4]; +} AR2MarkerT; + +typedef struct { + AR2MarkerT *marker; + int num; +} AR2MarkerSetT; + + +/* marker.c */ +AR2MarkerSetT *ar2ReadMarkerSet( char *filename, char *ext, ARPattHandle *pattHandle ); +int ar2FreeMarkerSet( AR2MarkerSetT **markerSet ); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/libs/include/AR2/searchPoint.h b/libs/include/AR2/searchPoint.h new file mode 100755 index 0000000..35c695c --- /dev/null +++ b/libs/include/AR2/searchPoint.h @@ -0,0 +1,59 @@ +/* + * AR2/searchPoint.h + * ARToolKit5 + * + * This file is part of ARToolKit. + * + * ARToolKit is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ARToolKit is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ARToolKit. If not, see . + * + * As a special exception, the copyright holders of this library give you + * permission to link this library with independent modules to produce an + * executable, regardless of the license terms of these independent modules, and to + * copy and distribute the resulting executable under terms of your choice, + * provided that you also meet, for each linked independent module, the terms and + * conditions of the license of that module. An independent module is a module + * which is neither derived from nor based on this library. If you modify this + * library, you may extend this exception to your version of the library, but you + * are not obligated to do so. If you do not wish to do so, delete this exception + * statement from your version. + * + * Copyright 2015 Daqri, LLC. + * Copyright 2006-2015 ARToolworks, Inc. + * + * Author(s): Hirokazu Kato, Philip Lamb + * + */ + +#ifndef AR2_SEARCH_POINT_H +#define AR2_SEARCH_POINT_H +#include +#include +#include + + +#ifdef __cplusplus +extern "C" { +#endif + +/* searchPoint.c */ +void ar2GetSearchPoint( ARParamLT *cparamLT, + float trans1[3][4], float trans2[3][4], float trans3[3][4], + AR2FeatureCoordT *feature, + int search[3][2] ); + + +#ifdef __cplusplus +} +#endif +#endif diff --git a/libs/include/AR2/template.h b/libs/include/AR2/template.h new file mode 100755 index 0000000..cd34969 --- /dev/null +++ b/libs/include/AR2/template.h @@ -0,0 +1,133 @@ +/* + * AR2/template.h + * ARToolKit5 + * + * This file is part of ARToolKit. + * + * ARToolKit is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ARToolKit is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ARToolKit. If not, see . + * + * As a special exception, the copyright holders of this library give you + * permission to link this library with independent modules to produce an + * executable, regardless of the license terms of these independent modules, and to + * copy and distribute the resulting executable under terms of your choice, + * provided that you also meet, for each linked independent module, the terms and + * conditions of the license of that module. An independent module is a module + * which is neither derived from nor based on this library. If you modify this + * library, you may extend this exception to your version of the library, but you + * are not obligated to do so. If you do not wish to do so, delete this exception + * statement from your version. + * + * Copyright 2015 Daqri, LLC. + * Copyright 2006-2015 ARToolworks, Inc. + * + * Author(s): Hirokazu Kato, Philip Lamb + * + */ + +#ifndef AR2_TEMPLATE_H +#define AR2_TEMPLATE_H +#include +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + + +#define AR2_TEMPLATE_NULL_PIXEL 0x1000 + + +typedef struct { + int xsize, ysize; /* template size */ + int xts1, xts2; /* template size */ + int yts1, yts2; /* template size */ + ARUint16 *img1; /* template for mode 0 */ + int vlen; /* length of vector *img */ + int sum; + int validNum; +} AR2TemplateT; + +#if AR2_CAPABLE_ADAPTIVE_TEMPLATE +typedef struct { + int xsize, ysize; /* template size */ + int xts1, xts2; /* template size */ + int yts1, yts2; /* template size */ + ARUint16 *img1[3]; /* template for mode 0 */ + int vlen[3]; /* length of vector *img */ + int sum[3]; + int validNum; +} AR2Template2T; +#endif + + +typedef struct { + int snum; + int level; + int num; + int flag; // Set to -1 to indicate that this candidate is the last candidate in the list/array (i.e. candidate count has reached AR2_TRACKING_CANDIDATE_MAX). 0 to indicate a valid candidate. Set to 1 to indicate that this template has been chosen as a candidate. + float sx, sy; +} AR2TemplateCandidateT; + + + +#if AR2_CAPABLE_ADAPTIVE_TEMPLATE +AR2TemplateT *ar2GenTemplate ( int ts1, int ts2 ); +AR2Template2T *ar2GenTemplate2 ( int ts1, int ts2 ); +int ar2FreeTemplate ( AR2TemplateT *templ ); +int ar2FreeTemplate2( AR2Template2T *templ2 ); + +int ar2SetTemplateSub ( ARParamLT *cparamLT, float trans[3][4], AR2ImageSetT *imageSet, + AR2FeaturePointsT *featurePoints, int num, int blurLevel, + AR2TemplateT *templ ); +int ar2SetTemplate2Sub( ARParamLT *cparamLT, float trans[3][4], AR2ImageSetT *imageSet, + AR2FeaturePointsT *featurePoints, int num, int blurLevel, + AR2Template2T *templ2 ); +#else +AR2TemplateT *ar2GenTemplate ( int ts1, int ts2 ); +int ar2FreeTemplate( AR2TemplateT *templ ); + +int ar2SetTemplateSub ( ARParamLT *cparamLT, float trans[3][4], AR2ImageSetT *imageSet, + AR2FeaturePointsT *featurePoints, int num, + AR2TemplateT *templ ); +#endif + + +int ar2GetBestMatching ( ARUint8 *img, ARUint8 *mfImage, int xsize, int ysize, AR_PIXEL_FORMAT pixFormat, + AR2TemplateT *mtemp, int rx, int ry, + int search[3][2], int *bx, int *by, float *val); + +#if AR2_CAPABLE_ADAPTIVE_TEMPLATE +int ar2GetBestMatching2( ARUint8 *img, ARUint8 *mfImage, int xsize, int ysize, AR_PIXEL_FORMAT pixFormat, + AR2Template2T *mtemp, int rx, int ry, + int search[3][2], int *bx, int *by, float *val, int *blurLevel); +#else +int ar2GetBestMatching2(void); +#endif + +int ar2GetResolution( ARParamLT *cparamLT, float trans[3][4], float pos[2], float dpi[2] ); +int ar2GetResolution2( ARParam *cparam, float trans[3][4], float pos[2], float dpi[2] ); + +// Returns -1 if no template selected, otherwise returns the 0-based index of the selected template +// and sets 'flag' of the template to 1. +int ar2SelectTemplate( AR2TemplateCandidateT *candidate, AR2TemplateCandidateT *prevFeature, int num, + float pos[4][2], int xsize, int ysize ); + + + +#ifdef __cplusplus +} +#endif +#endif diff --git a/libs/include/AR2/tracking.h b/libs/include/AR2/tracking.h new file mode 100755 index 0000000..a47010e --- /dev/null +++ b/libs/include/AR2/tracking.h @@ -0,0 +1,473 @@ +/* + * AR2/tracking.h + * ARToolKit5 + * + * This file is part of ARToolKit. + * + * ARToolKit is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ARToolKit is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ARToolKit. If not, see . + * + * As a special exception, the copyright holders of this library give you + * permission to link this library with independent modules to produce an + * executable, regardless of the license terms of these independent modules, and to + * copy and distribute the resulting executable under terms of your choice, + * provided that you also meet, for each linked independent module, the terms and + * conditions of the license of that module. An independent module is a module + * which is neither derived from nor based on this library. If you modify this + * library, you may extend this exception to your version of the library, but you + * are not obligated to do so. If you do not wish to do so, delete this exception + * statement from your version. + * + * Copyright 2015 Daqri, LLC. + * Copyright 2006-2015 ARToolworks, Inc. + * + * Author(s): Hirokazu Kato, Philip Lamb + * + */ +/*! + @header tracking + @abstract ARToolKit NFT core routines. + @discussion + This header declares essential types and API for the NFT portion of the + ARToolKit SDK. + + For compile-time per-machine and NFT configuration, see <AR2/config.h>. + @copyright 2015 Daqri, LLC. + */ + +#ifndef AR2_TRACKING_H +#define AR2_TRACKING_H +#include +#include +#include +#include +#include +#include +#include + +#define AR2_TRACKING_6DOF 1 +#define AR2_TRACKING_HOMOGRAPHY 2 + +#define AR2_TRACKING_DEFAULT_THREAD_NUM -1 + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct { + AR2ImageSetT *imageSet; + AR2FeatureSetT *featureSet; + AR2MarkerSetT *markerSet; + float trans[3][4]; + float itrans[3][4]; + char *jpegName; +} AR2SurfaceT; + +typedef struct { + AR2SurfaceT *surface; + int num; + float trans1[3][4]; + float trans2[3][4]; + float trans3[3][4]; + int contNum; + AR2TemplateCandidateT prevFeature[AR2_SEARCH_FEATURE_MAX+1]; +} AR2SurfaceSetT; + +typedef struct { + float sim; + float pos2d[2]; + float pos3d[3]; +#if AR2_CAPABLE_ADAPTIVE_TEMPLATE + int blurLevel; +#endif +} AR2Tracking2DResultT; + + +typedef struct _AR2HandleT AR2HandleT; +typedef struct _AR2Tracking2DParamT AR2Tracking2DParamT; + +// Structure to pass parameters to threads spawned to run ar2Tracking2d(). +struct _AR2Tracking2DParamT { + struct _AR2HandleT *ar2Handle; // Reference to parent AR2HandleT. + AR2SurfaceSetT *surfaceSet; + AR2TemplateCandidateT *candidate; + ARUint8 *dataPtr; // Input image. + ARUint8 *mfImage; // (Internally allocated buffer same size as input image). + AR2TemplateT *templ; +#if AR2_CAPABLE_ADAPTIVE_TEMPLATE + AR2Template2T *templ2; +#endif + AR2Tracking2DResultT result; + int ret; +}; + +struct _AR2HandleT { + int trackingMode; + int xsize; + int ysize; + ARParamLT *cparamLT; + ICPHandleT *icpHandle; + AR_PIXEL_FORMAT pixFormat; +#if AR2_CAPABLE_ADAPTIVE_TEMPLATE + int blurMethod; + int blurLevel; +#endif + int searchSize; + int templateSize1; + int templateSize2; + int searchFeatureNum; + float simThresh; + float trackingThresh; + /*--------------------------------*/ + float wtrans1[AR2_TRACKING_SURFACE_MAX][3][4]; + float wtrans2[AR2_TRACKING_SURFACE_MAX][3][4]; + float wtrans3[AR2_TRACKING_SURFACE_MAX][3][4]; + float pos[AR2_SEARCH_FEATURE_MAX+AR2_THREAD_MAX][2]; + float pos2d[AR2_SEARCH_FEATURE_MAX][2]; + float pos3d[AR2_SEARCH_FEATURE_MAX][3]; + AR2TemplateCandidateT candidate[AR2_TRACKING_CANDIDATE_MAX+1]; + AR2TemplateCandidateT candidate2[AR2_TRACKING_CANDIDATE_MAX+1]; + AR2TemplateCandidateT usedFeature[AR2_SEARCH_FEATURE_MAX]; + int threadNum; + struct _AR2Tracking2DParamT arg[AR2_THREAD_MAX]; + THREAD_HANDLE_T *threadHandle[AR2_THREAD_MAX]; +}; + + +/*! + @function + @abstract Perform NFT texture tracking on an image frame. + @discussion + Before the first call to this function, ar2SetInitTrans() must be called to set + the initial tracking transform. The initial transform may be obtained from NFT KPM + tracking, or via a fiducial marker embedded in the NFT image. The initial transform + must also be set after each loss of tracking (i.e. after each instance when this + function does not return 0. + @param ar2Handle Tracking settings structure, as returned via ar2CreateHandle. + @param surfaceSet Tracking surface set, as returned via ar2ReadSurfaceSet. + @param dataPtr Pointer to image data on which tracking will be performed. + @param trans Pointer to a float[3][4] array which will be filled out with the pose. + @param err On successful return, will be filled out with pose error value. + @result 0 in case of successful tracking, or < 0 in case of error. + Error codes:
+ -1: Bad parameter
+ -2: Tracking not initialised
+ -3: Insufficient texture features
+ -4: Pose error exceeds value set with ar2SetTrackingThresh() + @seealso ar2SetInitTrans ar2SetInitTrans + @seealso ar2SetTrackingThresh ar2SetTrackingThresh + @seealso ar2CreateHandle ar2CreateHandle + @seealso ar2ReadSurfaceSet ar2ReadSurfaceSet + */ +int ar2Tracking ( AR2HandleT *ar2Handle, AR2SurfaceSetT *surfaceSet, + ARUint8 *dataPtr, float trans[3][4], float *err ); +void *ar2Tracking2d ( THREAD_HANDLE_T *threadHandle ); +/* +int ar2Tracking2d ( AR2HandleT *ar2Handle, AR2SurfaceSetT *surfaceSet, + AR2TemplateCandidateT *candidate, + ARUint8 *dataPtr, AR2Tracking2DResultT *result ); +*/ + +/*! + @function + @abstract Read an NFT texture tracking surface set from file. + @discussion + Allocates, initialises and reads the contents of a surface set from storage. + The surface set is usually generated by the genTexData utility, or equivalent. + + Once the surface set is no longer required, it should be disposed of by calling ar2FreeSurfaceSet(). + @param filename Pathname of the surface set to be loaded, less any filename extension. + @param ext Filename extension of the surface set to be loaded. Ususally this will be "fset". + @param pattHandle If the surface set includes, template markers, a valid ARPattHandle is required + to be passed in this parameter. Otherwise, NULL may be passed. + @result A pointer to the loaded AR2SurfaceSetT, or NULL in case of error. + @seealso ar2FreeSurfaceSet ar2FreeSurfaceSet + */ +AR2SurfaceSetT *ar2ReadSurfaceSet ( const char *filename, const char *ext, ARPattHandle *pattHandle ); + +/*! + @function + @abstract Finalise and dispose of an NFT texture tracking surface set. + @discussion + Once a surface set (read by ar2ReadSurfaceSet()) is no longer required, it should be disposed + of by calling ar2FreeSurfaceSet(). + @param surfaceSet Pointer to a location pointing to an AR2SurfaceSetT. On return, + this pointer will be set to NULL. + @result 0 if successful, -1 otherwise. + @seealso ar2ReadSurfaceSet ar2ReadSurfaceSet + */ +int ar2FreeSurfaceSet ( AR2SurfaceSetT **surfaceSet ); + +/*! + @function + @abstract Sets initial transform for subsequent NFT texture tracking. + @discussion + Before the first call to ar2Tracking(), this function must be called to set + the initial tracking transform. The initial transform may be obtained from NFT KPM + tracking, or via a fiducial marker embedded in the NFT image. The initial transform + must also be set after each loss of tracking (i.e. after each instance when + ar2Tracking() does not return 0. + @param surfaceSet + @param trans Pointer to a float[3][4] array from which the initial transform will be copied. + @result 0 if successful, or -1 in case of error. + @seealso ar2Tracking ar2Tracking + */ +int ar2SetInitTrans ( AR2SurfaceSetT *surfaceSet, float trans[3][4] ); + +/*! + @function + @abstract Allocate and initialise essential structures for NFT texture tracking, using full six degree-of-freedom tracking. + @discussion + Full 6 degree-of-freedom tracking requires a calibrated camera lens model, and provides measurement + of surface position in all axes, as well as orientation. + @param cparamLT Pointer to an ARParamLT structure holding camera parameters in lookup-table form. + The pointer only is copied, and the ARParamLT structure itself is NOT copied, and must remain + valid for the lifetime of the AR2HandleT. + This structure also specifies the size of video frames which will be later supplied to the + ar2Tracking() function as cparamLT->param.xsize and cparamLT->param.ysize. + @param pixFormat Pixel format of video frames which will be later supplied to the ar2Tracking() function. + @param threadNum Number of threads to spawn for the NFT texture tracking task. + Use AR2_TRACKING_DEFAULT_THREAD_NUM to have ARToolKit calculate a sensible default. + @result Pointer to a newly allocated AR2HandleT structure, which holds the current state of the NFT + texture tracker, or NULL if an error occurred. + This structure must be deallocated via a call to ar2DeleteHandle() when no longer needed. + @seealso ar2CreateHandleHomography ar2CreateHandleHomography + @seealso ar2DeleteHandle ar2DeleteHandle + */ +AR2HandleT *ar2CreateHandle ( ARParamLT *cparamLT, AR_PIXEL_FORMAT pixFormat, int threadNum ); + +/*! + @function + @abstract Allocate and initialise essential structures for NFT texture tracking, using homography-only tracking. + @discussion + Homography tracking assumes that the camera has zero lens-distortion, and this does not depend on + camera parameters. It is therefore unable to provide correctly calibrated position measurements, + but the resulting pose is suitable for visual overlay purposes. + @param xsize Width of video frames which will be later supplied to the ar2Tracking() function. + @param ysize Height of video frames which will be later supplied to the ar2Tracking() function. + @param pixFormat Pixel format of video frames which will be later supplied to the ar2Tracking() function. + @param threadNum Number of threads to spawn for the NFT texture tracking task. + Use AR2_TRACKING_DEFAULT_THREAD_NUM to have ARToolKit calculate a sensible default. + @result Pointer to a newly allocated AR2HandleT structure, which holds the current state of the NFT + texture tracker, or NULL if an error occurred. + This structure must be deallocated via a call to ar2DeleteHandle() when no longer needed. + @seealso ar2CreateHandle ar2CreateHandle + @seealso ar2DeleteHandle ar2DeleteHandle + */ +AR2HandleT *ar2CreateHandleHomography ( int xsize, int ysize, AR_PIXEL_FORMAT pixFormat, int threadNum ); + +/*! + @function + @abstract Finalise and dispose of structures for NFT texture tracking. + @discussion + Once texture tracking processing has completed, this routine should be called to + dispose of memory allocated. + @param ar2Handle Pointer to a location which holds a pointer to a AR2HandleT structure. + On return, the location pointed to will be set to NULL. + @result -1 in case of error, or 0 otherwise. + @seealso ar2CreateHandle ar2CreateHandle + @seealso ar2CreateHandleHomography ar2CreateHandleHomography + */ +int ar2DeleteHandle ( AR2HandleT **ar2Handle ); + +#if AR2_CAPABLE_ADAPTIVE_TEMPLATE +int ar2SetBlurMethod ( AR2HandleT *ar2Handle, int blurMethod ); +int ar2GetBlurMethod ( AR2HandleT *ar2Handle, int *blurMethod ); +int ar2SetBlurLevel ( AR2HandleT *ar2Handle, int blurLevel ); +int ar2GetBlurLevel ( AR2HandleT *ar2Handle, int *blurLevel ); +#endif + +/*! + @function + @abstract Set feature point search window size. + @discussion + Sets the size of the window around a feature location from previous frame in which + the feature will be searched for in the next frame. Value is radius of the search + window, in pixels. I.e. searchSize pixels either size of the current feature position + will be searched for the new location of the feature. + + A larger search window allows for greater movement of a feature between frames + (e.g. faster optical motion, or same degree of optical motion but at a higher frame + resolution), at the cost of greater search effort. Search effort increases with + the square of the search radius. + + Default value is AR2_DEFAULT_SEARCH_SIZE, as defined in <AR2/config.h> + @param ar2Handle Tracking settings structure, as returned via ar2CreateHandle. + @param searchSize The new search size to use. + @result -1 in case of error, or 0 otherwise. + @seealso ar2GetSearchSize ar2GetSearchSize + */ +int ar2SetSearchSize ( AR2HandleT *ar2Handle, int searchSize ); + +/*! + @function + @abstract Get feature point search window size. + @discussion + See the discussion under ar2SetSearchSize. + + Default value is AR2_DEFAULT_SEARCH_SIZE, as defined in <AR2/config.h> + @param ar2Handle Tracking settings structure, as returned via ar2CreateHandle. + @param searchSize Pointer to an int, which on return will be filled with the current search size in use. + @result -1 in case of error, or 0 otherwise. + @seealso ar2SetSearchSize ar2SetSearchSize + */ +int ar2GetSearchSize ( AR2HandleT *ar2Handle, int *searchSize ); + +/*! + @function + @abstract + @discussion + @param ar2Handle Tracking settings structure, as returned via ar2CreateHandle. + @param templateSize1 + @result -1 in case of error, or 0 otherwise. + */ +int ar2SetTemplateSize1 ( AR2HandleT *ar2Handle, int templateSize1 ); + +/*! + @function + @abstract + @discussion + @param ar2Handle Tracking settings structure, as returned via ar2CreateHandle. + @param templateSize1 + @result -1 in case of error, or 0 otherwise. + */ +int ar2GetTemplateSize1 ( AR2HandleT *ar2Handle, int *templateSize1 ); + +/*! + @function + @abstract + @discussion + @param ar2Handle Tracking settings structure, as returned via ar2CreateHandle. + @param templateSize2 + @result -1 in case of error, or 0 otherwise. + */ +int ar2SetTemplateSize2 ( AR2HandleT *ar2Handle, int templateSize2 ); + +/*! + @function + @abstract + @discussion + @param ar2Handle Tracking settings structure, as returned via ar2CreateHandle. + @param templateSize2 + @result -1 in case of error, or 0 otherwise. + */ +int ar2GetTemplateSize2 ( AR2HandleT *ar2Handle, int *templateSize2 ); + +/*! + @function + @abstract + @discussion + @param ar2Handle Tracking settings structure, as returned via ar2CreateHandle. + @param searchTemplateMax + @result -1 in case of error, or 0 otherwise. + */ +int ar2SetSearchFeatureNum ( AR2HandleT *ar2Handle, int searchTemplateMax ); + +/*! + @function + @abstract + @discussion + @param ar2Handle Tracking settings structure, as returned via ar2CreateHandle. + @param searchTemplateMax + @result -1 in case of error, or 0 otherwise. + */ +int ar2GetSearchFeatureNum ( AR2HandleT *ar2Handle, int *searchTemplateMax ); + +/*! + @function + @abstract + @discussion + @param ar2Handle Tracking settings structure, as returned via ar2CreateHandle. + @param simThresh + @result -1 in case of error, or 0 otherwise. + */ +int ar2SetSimThresh ( AR2HandleT *ar2Handle, float simThresh ); + +/*! + @function + @abstract + @discussion + @param ar2Handle Tracking settings structure, as returned via ar2CreateHandle. + @param simThresh + @result -1 in case of error, or 0 otherwise. + */ +int ar2GetSimThresh ( AR2HandleT *ar2Handle, float *simThresh ); + +/*! + @function + @abstract Set threshold value for acceptable pose estimate error. + @discussion + During the final phase of a single tracking pass, the pose estimate is calculated, + along with an estimate of the error in this value (an uncertainty). A higher value + indicates less goodness-of-fit of the pose estimate to the data. If only high-quality + pose estimates are desired, this function can be used to lower the acceptable maximum + error value. + + The actual error value itself is reported in parameter 'err' of function ar2Tracking. + + Default value is AR2_DEFAULT_TRACKING_THRESH, as defined in <AR2/config.h> + @param ar2Handle Tracking settings structure, as returned via ar2CreateHandle. + @param trackingThresh floating point value to use as the new tracking threshold. + @result -1 in case of error, or 0 otherwise. + @seealso ar2GetTrackingThresh ar2GetTrackingThresh + @seealso ar2Tracking ar2Tracking + */ +int ar2SetTrackingThresh ( AR2HandleT *ar2Handle, float trackingThresh ); + +/*! + @function + @abstract Get threshold value for acceptable pose estimate error. + @discussion + See the discussion under ar2SetTrackingThresh. + + Default value is AR2_DEFAULT_TRACKING_THRESH, as defined in <AR2/config.h> + @param ar2Handle Tracking settings structure, as returned via ar2CreateHandle. + @param trackingThresh Pointer to a float, which on return will be filled with the threshold value. + @result -1 in case of error, or 0 otherwise. + @seealso ar2SetTrackingThresh ar2SetTrackingThresh +*/ +int ar2GetTrackingThresh ( AR2HandleT *ar2Handle, float *trackingThresh ); + +/*! + @function + @abstract Choose whether full 6 degree-of-freedom tracking is performed, or homography extraction only. + @discussion + Note that while it is possible to switch an AR2HandleT created in 6DOF mode (via ar2CreateHandle) to + HOMOGRAPHY mode and back to 6DOF ,an AR2HandleT created in HOMOGRAPHY mode (via ar2CreateHandleHomography) + cannot be switched to 6DOF mode. + @param ar2Handle Tracking settings structure, as returned via ar2CreateHandle. + @param trackingMode Either AR2_TRACKING_6DOF or AR2_TRACKING_HOMOGRAPHY. + @result -1 in case of error, or 0 otherwise. + @seealso ar2CreateHandle ar2CreateHandle + @seealso ar2CreateHandleHomography ar2CreateHandleHomography + @seealso ar2GetTrackingMode ar2GetTrackingMode + */ +int ar2SetTrackingMode ( AR2HandleT *ar2Handle, int trackingMode ); + +/*! + @function + @abstract Report whether an AR2HandleT is providing full 6 degree-of-freedom tracking or homography extraction only. + @discussion + @param ar2Handle Tracking settings structure, as returned via ar2CreateHandle. + @param trackingMode + @result -1 in case of error, or 0 otherwise. + @seealso ar2CreateHandle ar2CreateHandle + @seealso ar2CreateHandleHomography ar2CreateHandleHomography + @seealso ar2SetTrackingMode ar2SetTrackingMode + */ +int ar2GetTrackingMode ( AR2HandleT *ar2Handle, int *trackingMode ); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/libs/include/AR2/util.h b/libs/include/AR2/util.h new file mode 100755 index 0000000..aa5cd82 --- /dev/null +++ b/libs/include/AR2/util.h @@ -0,0 +1,54 @@ +/* + * AR2/util.h + * ARToolKit5 + * + * This file is part of ARToolKit. + * + * ARToolKit is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ARToolKit is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ARToolKit. If not, see . + * + * As a special exception, the copyright holders of this library give you + * permission to link this library with independent modules to produce an + * executable, regardless of the license terms of these independent modules, and to + * copy and distribute the resulting executable under terms of your choice, + * provided that you also meet, for each linked independent module, the terms and + * conditions of the license of that module. An independent module is a module + * which is neither derived from nor based on this library. If you modify this + * library, you may extend this exception to your version of the library, but you + * are not obligated to do so. If you do not wish to do so, delete this exception + * statement from your version. + * + * Copyright 2015 Daqri, LLC. + * Copyright 2006-2015 ARToolworks, Inc. + * + * Author(s): Hirokazu Kato, Philip Lamb + * + */ + +#ifndef AR2_UTIL_H +#define AR2_UTIL_H +#ifdef __cplusplus +extern "C" { +#endif + +#include + +/* util.c */ +int ar2UtilReplaceExt( char *filename, int n, char *ext ); +int ar2UtilRemoveExt ( char *filename ); +int ar2UtilDivideExt ( const char *filename, char *s1, char *s2 ); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/libs/include/ARWrapper/ARController.h b/libs/include/ARWrapper/ARController.h new file mode 100755 index 0000000..6b4fdec --- /dev/null +++ b/libs/include/ARWrapper/ARController.h @@ -0,0 +1,534 @@ +/* + * ARController.h + * ARToolKit5 + * + * A C++ class encapsulating core controller functionality of ARToolKit. + * + * This file is part of ARToolKit. + * + * ARToolKit is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ARToolKit is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ARToolKit. If not, see . + * + * As a special exception, the copyright holders of this library give you + * permission to link this library with independent modules to produce an + * executable, regardless of the license terms of these independent modules, and to + * copy and distribute the resulting executable under terms of your choice, + * provided that you also meet, for each linked independent module, the terms and + * conditions of the license of that module. An independent module is a module + * which is neither derived from nor based on this library. If you modify this + * library, you may extend this exception to your version of the library, but you + * are not obligated to do so. If you do not wish to do so, delete this exception + * statement from your version. + * + * Copyright 2015 Daqri, LLC. + * Copyright 2010-2015 ARToolworks, Inc. + * + * Author(s): Philip Lamb, Julian Looser. + * + */ + + +#ifndef ARCONTROLLER_H +#define ARCONTROLLER_H + +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#if HAVE_NFT +# include +# include +# include +#endif + + +#include +#include +#include +#include +#include +#if !defined(_WINRT) +# include +#else +# define pthread_mutex_t CRITICAL_SECTION +# define pthread_mutex_init(pm, a) InitializeCriticalSectionEx(pm, 4000, CRITICAL_SECTION_NO_DEBUG_INFO) +# define pthread_mutex_lock(pm) EnterCriticalSection(pm) +# define pthread_mutex_unlock(pm) LeaveCriticalSection(pm) +# define pthread_mutex_destroy(pm) DeleteCriticalSection(pm) +#endif +#define PAGES_MAX 64 + +/** + * Wrapper for ARToolKit functionality. This class handles ARToolKit initialisation, updates, + * and cleanup. It maintains a collection of markers, providing methods to add and remove them. + */ +class ARController { + +private: +#pragma mark Private types and instance variables + // ------------------------------------------------------------------------------ + // Private types and instance variables. + // ------------------------------------------------------------------------------ + + typedef enum { + NOTHING_INITIALISED, ///< No initialisation yet and no resources allocated. + BASE_INITIALISED, ///< Marker management initialised, markers can be added. + WAITING_FOR_VIDEO, ///< Waiting for video source to become ready. + DETECTION_RUNNING ///< Video running, additional initialisation occurred, marker detection running. + } ARToolKitState; + + ARToolKitState state; ///< Current state of operation, progress through initialisation + bool stateWaitingMessageLogged; + + char* versionString; ///< ARToolKit version string + + VideoSource *m_videoSource0; ///< VideoSource providing video frames for tracking + VideoSource *m_videoSource1; ///< VideoSource providing video frames for tracking + pthread_mutex_t m_videoSourceLock; + bool m_videoSourceIsStereo; + int m_videoSourceFrameStamp0; + int m_videoSourceFrameStamp1; + + // Virtual environment parameters. + ARdouble m_projectionNearPlane; ///< Near plane distance for projection matrix calculation + ARdouble m_projectionFarPlane; ///< Far plane distance for projection matrix calculation + ARdouble m_projectionMatrix0[16]; ///< OpenGL style projection matrix computed from camera parameters + ARdouble m_projectionMatrix1[16]; ///< OpenGL style projection matrix computed from camera parameters + bool m_projectionMatrixSet; ///< True once the projection matrix has been computed, which requires an open video source + + // ARToolKit configuration. These allow for configuration prior to starting ARToolKit. + int threshold; + AR_LABELING_THRESH_MODE thresholdMode; + int imageProcMode; + int labelingMode; + ARdouble pattRatio; + int patternDetectionMode; + AR_MATRIX_CODE_TYPE matrixCodeType; + bool debugMode; + + std::vector markers; ///< List of markers. + + bool doMarkerDetection; + // ARToolKit data. + ARHandle *m_arHandle0; ///< Structure containing general ARToolKit tracking information + ARHandle *m_arHandle1; ///< Structure containing general ARToolKit tracking information + ARPattHandle *m_arPattHandle; ///< Structure containing information about trained patterns + AR3DHandle *m_ar3DHandle; ///< Structure used to compute 3D poses from tracking data + ARdouble m_transL2R[3][4]; + AR3DStereoHandle *m_ar3DStereoHandle; + +#if HAVE_NFT + bool doNFTMarkerDetection; + bool m_nftMultiMode; + bool m_kpmRequired; + bool m_kpmBusy; + // NFT data. + THREAD_HANDLE_T *trackingThreadHandle; + AR2HandleT *m_ar2Handle; + KpmHandle *m_kpmHandle; + AR2SurfaceSetT *surfaceSet[PAGES_MAX]; // Weak-reference. Strong reference is now in ARMarkerNFT class. +#endif + + int m_error; + void setError(int error); + +#pragma mark Private methods. + // ------------------------------------------------------------------------------ + // Private methods. + // ------------------------------------------------------------------------------ + + void lockVideoSource(); + void unlockVideoSource(); + + // + // Internal marker management. + // + + /** + * Adds a marker to the collection. + * @param marker The marker to add + * @return true if the marker was added successfully, otherwise false + */ + bool addMarker(ARMarker* marker); + + /** + * Removes the specified marker. + * @param marker The marker to remove + * @return true if the marker was removed, false if an error occurred. + */ + bool removeMarker(ARMarker* marker); + + // + // Convenience initialisers. + // + + bool initAR(void); +#if HAVE_NFT + bool unloadNFTData(void); + bool loadNFTData(void); + bool initNFT(void); +#endif + +public: +#pragma mark Public API + // ------------------------------------------------------------------------------ + // Public API + // ------------------------------------------------------------------------------ + + /** + * Constructor. + */ + ARController(); + + /** + * Destructor. + */ + ~ARController(); + + static PFN_LOGCALLBACK logCallback; ///< Callback where log messages are passed to + +private: + static void logvBuf(va_list args, const char* format, char **bufPtr, int* lenPtr); + static void logvWriteBuf(char* buf, int len, const int logLevel); + +public: + static void logv(const int logLevel, const char* format, ...); + + /** + * If a log callback has been set, then this passes the formatted message to it. + * If no log callback has been set, then the message is discarded. + * @param msg The message to output. Follows the same formatting rules as printf(). + */ + static void logv(const char* msg, ...); + + /** + * Returns a string containing the ARToolKit version, such as "4.5.1". + * @return The ARToolKit version + */ + const char* getARToolKitVersion(); + + int getError(); + + /** + * Start marker management so markers can be added and removed. + * @param patternSize For any square template (pattern) markers, the number of rows and columns in the template. + * @param patternCountMax For any square template (pattern) markers, the maximum number of markers that may be loaded for a single matching pass. Must be > 0. + * @return true if initialisation was OK, false if an error occured. + */ + bool initialiseBase(const int patternSize = AR_PATT_SIZE1, const int patternCountMax = AR_PATT_NUM_MAX); + + /** + * Report whether a marker can be added. Markers can be added once basic + * initialisation has occurred. + * @return true if adding a marker is currently possible + */ + bool canAddMarker(); + + void setProjectionNearPlane(const ARdouble projectionNearPlane); + void setProjectionFarPlane(const ARdouble projectionFarPlane); + ARdouble projectionNearPlane(void); + ARdouble projectionFarPlane(void); + + /** + * Start video capture and marker detection. (AR/NFT initialisation will begin on a subsequent call to update().) + * @param vconf Video configuration string. + * @param cparaName Camera parameters filename, or NULL if camera parameters file not being used. + * @param cparaBuff A byte-buffer containing contents of a camera parameters file, or NULL if a camera parameters file is being used. + * @param cparaBuffLen Length (in bytes) of cparaBuffLen, or 0 if a camera parameters file is being used. + * @return true if video capture and marker detection was started, otherwise false. + */ + bool startRunning(const char* vconf, const char* cparaName, const char* cparaBuff, const long cparaBuffLen); + + /** + * Start stereo video capture and marker detection. (AR/NFT initialisation will begin on a subsequent call to update().) + * @param vconfL Video configuration string for the "left" video source. + * @param cparaNameL Camera parameters filename for the "left" video source, or NULL if camera parameters file not being used. + * @param cparaBuffL A byte-buffer containing contents of a camera parameters file for the "left" video source, or NULL if a camera parameters file is being used. + * @param cparaBuffLenL Length (in bytes) of cparaBuffLenL, or 0 if a camera parameters file is being used. + * @param vconfR Video configuration string for the "right" video source. + * @param cparaNameR Camera parameters filename for the "right" video source, or NULL if camera parameters file not being used. + * @param cparaBuffR A byte-buffer containing contents of a camera parameters file for the "right" video source, or NULL if a camera parameters file is being used. + * @param cparaBuffLenR Length (in bytes) of cparaBuffLenR, or 0 if a camera parameters file is being used. + * @param transL2RName Stereo calibration filename, or NULL if stereo calibration file not being used. + * @param transL2RBuff A byte-buffer containing contents of a stereo calibration file, or NULL if a stereo calibration file is being used. + * @param transL2RBuffLen Length (in bytes) of transL2RBuff, or 0 if a stereo calibration file is being used. + * @return true if video capture and marker detection was started, otherwise false. + */ + bool startRunningStereo(const char* vconfL, const char* cparaNameL, const char* cparaBuffL, const long cparaBuffLenL, + const char* vconfR, const char* cparaNameR, const char* cparaBuffR, const long cparaBuffLenR, + const char* transL2RName, const char* transL2RBuff, const long transL2RBuffLen); + +#if TARGET_PLATFORM_ANDROID + bool videoAcceptImage(JNIEnv* env, jobject obj, const int videoSourceIndex, jbyteArray pinArray, jint width, jint height, jint cameraIndex, jboolean cameraIsFrontFacing); +#endif + + /** + * Reports width, height and pixel format of a video source. + * To retrieve the size (in bytes) of each pixel, use arUtilGetPixelSize(*pixelFormat); + * To get a C-string with the name of the pixel format, use arUtilGetPixelFormatName(*pixelFormat); + * @param videoSourceIndex Index into an array of video sources, specifying which source should be queried. + * @param width Pointer to an int which will be filled with the width (in pixels) of the video frame, or NULL if this information is not required. + * @param height Pointer to an int which will be filled with the height (in pixels) of the video frame, or NULL if this information is not required. + * @param pixelFormat Pointer to an AR_PIXEL_FORMAT which will be filled with the pixel format of the video frame, or NULL if this information is not required. + * @return true if the video source(s) is/are open and returning frames, otherwise false. + */ + bool videoParameters(const int videoSourceIndex, int *width, int *height, AR_PIXEL_FORMAT *pixelFormat); + + /** + * Returns true if video capture and marker detection is running. + * @return true if the video source(s) is/are open and returning frames, otherwise false. + */ + bool isRunning(); + + /** + * Video capture and marker detection stops, but markers are still valid and can be configured. + * @return true if video capture and marker detection was stopped, otherwise false. + */ + bool stopRunning(); + + /** + * Stop, if running. Remove all markers, clean up all memory. + * Starting again from this state requires initialiseBase() to be called again. + * @return true if shutdown was successful, otherwise false + */ + bool shutdown(); + + /** + * Populates the provided array with the ARToolKit projection matrix. The projection matrix is computed + * once the video source has been opened, and camera parameters become available. If this method is called + * before this happens, then the passed array is untouched and the method will return false. + * @param videoSourceIndex Index into an array of video sources, specifying which source should be queried. + * @param proj Array to populate with OpenGL compatible projection matrix + * @return true if the projection matrix has been computed, otherwise false + */ + bool getProjectionMatrix(const int videoSourceIndex, ARdouble proj[16]); + + /** + * Adds a marker as specified in the given configuration string. The format of the string can be + * one of: + * + * - Single marker: "single;pattern_file;pattern_width", e.g. "single;data/patt.hiro;80" + * - Multi marker: "multi;config_file", e.g. "multi;data/multi/marker.dat" + * - NFT marker: "nft;nft_dataset_pathname", e.g. "nft;gibraltar" + * + * @param cfg The configuration string + * @return The UID of the marker instantiated based on the configuration string, or -1 if an error occurred. + */ + int addMarker(const char* cfg); + + /** + * Removes the marker with the given ID. + * @param UID The UID of the marker to remove + * @return true if the marker was removed, false if an error occurred. + */ + bool removeMarker(int UID); + + /** + * Clears the collection of markers. + * @return The number of markers removed + */ + int removeAllMarkers(); + + /** + * Returns the number of currently loaded markers. + * @return The number of currently loaded markers. + */ + unsigned int countMarkers(); + + /** + * Searches the collection of markers for the given ID. + * @param UID The UID of the marker to find + * @return The found marker, or NULL if no matching ID was found. + */ + ARMarker* findMarker(int UID); + + bool capture(); + + /** + * Asks the video source to push the most recent frame into the passed-in buffer. + * @param videoSourceIndex Index into an array of video sources, specifying which source should be queried. + * @param buffer Pointer to a buffer of pixels (of type 'Color') to be filled. It is the caller's responsibility to ensure that the buffer is of sufficient size. + */ + bool updateTexture(const int videoSourceIndex, Color* buffer); + + /** + * Asks the video source to push the most recent frame into the passed-in buffer. + * @param videoSourceIndex Index into an array of video sources, specifying which source should + * be queried. + * @param buffer Pointer to a buffer of pixels (of type 'uint32_t') to be filled. It is the + * caller's responsibility to ensure that the buffer is of sufficient size. The pixels are + * RGBA in little-endian systems, or ABGR in big-endian systems. + */ + bool updateTexture32(const int videoSourceIndex, uint32_t *buffer); + +#ifndef _WINRT + /** + * Asks the video source to push the most recent frame into the OpenGL texture with the passed-in ID/name. + * Must be called on a thread with a valid OpenGL context and a valid OpenGL 2D texture with the given ID/name. + * @param videoSourceIndex Index into an array of video sources, specifying which source should be queried. + * @param textureID OpenGL texture ID/name of the initialised texture to push the video frame to. It is the caller's responsibility to ensure that the texture is valid and of correct size and format. + */ + bool updateTextureGL(const int videoSourceIndex, const int textureID); +#endif // !_WINRT + + /** + * Performs marker detection and updates all markers. The latest frame from the current + * video source is retrieved and analysed. Each marker in the collection is updated with + * new tracking information. The marker info array is + * iterated over, and detected markers are matched up with those in the marker collection. Each matched + * marker is updated with visibility and transformation information. Any markers not detected are considered + * not currently visible. + * + * @return true if update completed successfully, false if an error occurred + */ + bool update(); + + /** + * Enables or disables debug mode in the tracker. When enabled, a black and white debug + * image is generated during marker detection. The debug image is useful for visualising + * the binarization process and choosing a threshold value. + * @param debug true to enable debug mode, false to disable debug mode + * @see getDebugMode() + */ + void setDebugMode(bool debug); + + /** + * Returns whether debug mode is currently enabled. + * @return true when debug mode is enabled, false when debug mode is disabled + * @see setDebugMode() + */ + bool getDebugMode() const; + + void setImageProcMode(int mode); + + int getImageProcMode() const; + + /** + * Sets the threshold value used for image binarization. + * @param thresh The new threshold value to use + * @see getThreshold() + */ + void setThreshold(int thresh); + + /** + * Returns the current threshold value used for image binarization. + * @return The current threshold value + * @see setThreshold() + */ + int getThreshold() const; + + /** + * Sets the thresholding mode to use. + * @param mode The new thresholding mode to use. + * @see getThresholdMode() + */ + void setThresholdMode(int mode); + + /** + * Returns the current thresholding mode. + * @return The current thresholding mode. + * @see setThresholdMode() + */ + int getThresholdMode() const; + + /** + * Sets the labeling mode to use. + * @param mode The new labeling mode to use. + * @see getLabelingMode() + */ + void setLabelingMode(int mode); + + /** + * Returns the current labeling mode. + * @return The current labeling mode. + * @see setLabelingMode() + */ + int getLabelingMode() const; + + void setPatternDetectionMode(int mode); + + int getPatternDetectionMode() const; + + void setPattRatio(float ratio); + + float getPattRatio() const; + + void setMatrixCodeType(int type); + + int getMatrixCodeType() const; + + void setNFTMultiMode(bool on); + + bool getNFTMultiMode() const; + + /** + * Populates the provided color buffer with the current contents of the debug image. + * @param videoSourceIndex Index into an array of video sources, specifying which source should be queried. + * @param buffer Pointer to a buffer of pixels (of type 'Color') to be filled. It is the caller's responsibility to ensure that the buffer is of sufficient size. + * @return true if successful, false if an error occurred + */ + bool updateDebugTexture(const int videoSourceIndex, Color* buffer); + + /** + * Populates the provided buffer with the current contents of the debug image. + * @param videoSourceIndex Index into an array of video sources, specifying which source should + * be queried. + * @param buffer Pointer to a buffer of pixels (of type 'uint32_t') to be filled. It is the + * caller's responsibility to ensure that the buffer is of sufficient size. The pixels are + * RGBA in little-endian systems, or ABGR in big-endian systems. + */ + bool updateDebugTexture32(const int videoSourceIndex, uint32_t* buffer); + + /** + * Populates the provided color buffer with the image for the specified pattern. + * @param patternID The ARToolKit pattern ID to use + * @param buffer The color buffer to populate + * @return true if successful, false if an error occurred + */ + bool getPatternImage(int patternID, Color* buffer); + + /** + * Loads an optical parameters structure from file or from buffer. + * + * @param optical_param_name If supplied, points to a buffer specifying the path + * to the optical parameters file (as generated by the calib_optical utility.) + * @param optical_param_buff If optical_param_name is NULL, the contents of this + * buffer will be interpreted as containing the contents of an optical + * parameters file. + * @param optical_param_buffLen Length of the buffer specified in optical_param_buff. + * Ignored if optical_param_buff is NULL. + * @param fovy_p Pointer to an ARdouble, which will be filled with the + * field-of-view (Y axis) component of the optical parameters. + * @param aspect_p Pointer to an ARdouble, which will be filled with the + * aspect ratio (width / height) component of the optical parameters. + * @param m Pointer to an array of 16 ARdoubles, which will be filled with the + * transformation matrix component of the optical parameters. Note that the + * position vector (m[12], m[13], m[14]) will be scaled by the viewScale + * value supplued in startRunning(). + * @param p (Optional) May be NULL, or a pointer to an array of 16 ARdoubles, + * which will be filled with the perspective matrix calculated from fovy and aspect + * combined with the near and far projection values supplied in startRunning(). + */ + bool loadOpticalParams(const char *optical_param_name, const char *optical_param_buff, const long optical_param_buffLen, ARdouble *fovy_p, ARdouble *aspect_p, ARdouble m[16], ARdouble p[16]); + +}; + + +#endif // !ARCONTROLLER_H diff --git a/libs/include/ARWrapper/ARMarker.h b/libs/include/ARWrapper/ARMarker.h new file mode 100755 index 0000000..a1caade --- /dev/null +++ b/libs/include/ARWrapper/ARMarker.h @@ -0,0 +1,139 @@ +/* + * ARMarker.h + * ARToolKit5 + * + * This file is part of ARToolKit. + * + * ARToolKit is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ARToolKit is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ARToolKit. If not, see . + * + * As a special exception, the copyright holders of this library give you + * permission to link this library with independent modules to produce an + * executable, regardless of the license terms of these independent modules, and to + * copy and distribute the resulting executable under terms of your choice, + * provided that you also meet, for each linked independent module, the terms and + * conditions of the license of that module. An independent module is a module + * which is neither derived from nor based on this library. If you modify this + * library, you may extend this exception to your version of the library, but you + * are not obligated to do so. If you do not wish to do so, delete this exception + * statement from your version. + * + * Copyright 2015 Daqri, LLC. + * Copyright 2010-2015 ARToolworks, Inc. + * + * Author(s): Julian Looser, Philip Lamb + * + */ + +#ifndef ARMARKER_H +#define ARMARKER_H + +#include +#include + +#include +#include + +#include + +class ARController; // Forward declaration of owner. + +/** + * Base class for supported marker types. + */ +class ARMarker { + +private: + ARFilterTransMatInfo *m_ftmi; + ARdouble m_filterCutoffFrequency; + ARdouble m_filterSampleRate; + +protected: + ARdouble trans[3][4]; ///< Transformation from camera to this marker. If stereo, transform from left camera to this marker. + /** + * Allocates space for patterns within this marker. + * @param count The number of patterns to allocate + */ + void allocatePatterns(int count); + + /** + * Frees allocated patterns and resets the pattern count to zero. + */ + void freePatterns(); + + ARdouble m_positionScaleFactor; + +public: + + enum MarkerType { + SINGLE, ///< A standard single square marker + MULTI, ///< A composite marker made up of multiple single markers + NFT ///< A rectangular textured marker backed by an NFT data set. + }; + + int UID; ///< Internal unique ID (note: not the same as ARToolKit pattern ID) + MarkerType type; ///< Type of marker: single, multi, ... + + // Factory methods. + static std::vector newFromConfigDataFile(const char *markersConfigDataFilePath, ARPattHandle *arPattHandle, int *patternDetectionMode_out); + static ARMarker* newWithConfig(const char* cfg, ARPattHandle *arPattHandle); + + + // Inputs from subclasses. + bool visiblePrev; ///< Whether or not the marker was visible prior to last update. + bool visible; ///< Whether or not the marker is visible at current time. + + // Output. + ARdouble transformationMatrix[16]; ///< Transformation suitable for use in OpenGL + ARdouble transformationMatrixR[16]; ///< Transformation suitable for use in OpenGL + + int patternCount; ///< Number of patterns in this marker (1 for single) + ARPattern** patterns; ///< Array of pointers to patterns + + /** + * Constructor takes the type of this marker. + */ + ARMarker(MarkerType type); + + virtual ~ARMarker(); + + void setPositionScalefactor(ARdouble scale); + ARdouble positionScalefactor(); + + /** + * Completes an update begun in the parent class, performing filtering, generating + * OpenGL view matrix and notifying listeners (just a log message at the moment). + * Subclasses should first do their required updates, set visible, visiblePrev, + * and trans[3][4] then call ARMarker::update(). + * @return true if successful, false if an error occurred + */ + virtual bool update(ARdouble transL2R[3][4] = NULL); + + /** + * Returns the specified pattern within this marker. + * @param n The pattern to retrieve + */ + ARPattern* getPattern(int n); + + // Filter control. + void setFiltered(bool flag); + bool isFiltered(); + ARdouble filterSampleRate(); + void setFilterSampleRate(ARdouble rate); + ARdouble filterCutoffFrequency(); + void setFilterCutoffFrequency(ARdouble freq); + +}; + + +#endif // !ARMARKER_H diff --git a/libs/include/ARWrapper/ARMarkerMulti.h b/libs/include/ARWrapper/ARMarkerMulti.h new file mode 100755 index 0000000..e41887d --- /dev/null +++ b/libs/include/ARWrapper/ARMarkerMulti.h @@ -0,0 +1,78 @@ +/* + * ARMarkerMulti.h + * ARToolKit5 + * + * This file is part of ARToolKit. + * + * ARToolKit is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ARToolKit is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ARToolKit. If not, see . + * + * As a special exception, the copyright holders of this library give you + * permission to link this library with independent modules to produce an + * executable, regardless of the license terms of these independent modules, and to + * copy and distribute the resulting executable under terms of your choice, + * provided that you also meet, for each linked independent module, the terms and + * conditions of the license of that module. An independent module is a module + * which is neither derived from nor based on this library. If you modify this + * library, you may extend this exception to your version of the library, but you + * are not obligated to do so. If you do not wish to do so, delete this exception + * statement from your version. + * + * Copyright 2015 Daqri, LLC. + * Copyright 2010-2015 ARToolworks, Inc. + * + * Author(s): Philip Lamb. + * + */ + +#ifndef ARMARKERMULTI_H +#define ARMARKERMULTI_H + +#include + +#include + +/** + * Multiple marker type of ARMarker. + */ +class ARMarkerMulti : public ARMarker { + +private: + bool m_loaded; + +protected: + bool unload(); + +public: + + ARMultiMarkerInfoT *config; ///< Structure holding information about the multimarker patterns + bool robustFlag; ///< Flag specifying which pose estimation approach to use + + ARMarkerMulti(); + ~ARMarkerMulti(); + + bool load(const char *multiConfig, ARPattHandle *arPattHandle); + + /** + * Updates the marker with new tracking info. + * Then calls ARMarker::update() + * @param markerInfo Array containing detected marker information + * @param markerNum Number of items in the array + * @param ar3DHandle AR3DHandle used to extract marker pose. + */ + bool updateWithDetectedMarkers(ARMarkerInfo *markerInfo, int markerNum, AR3DHandle *ar3DHandle); + + bool updateWithDetectedMarkersStereo(ARMarkerInfo* markerInfoL, int markerNumL, ARMarkerInfo* markerInfoR, int markerNumR, AR3DStereoHandle *handle, ARdouble transL2R[3][4]); +}; + +#endif // !ARMARKERMULTI_H diff --git a/libs/include/ARWrapper/ARMarkerNFT.h b/libs/include/ARWrapper/ARMarkerNFT.h new file mode 100755 index 0000000..29158fd --- /dev/null +++ b/libs/include/ARWrapper/ARMarkerNFT.h @@ -0,0 +1,78 @@ +/* + * ARMarkerNFT.h + * ARToolKit5 + * + * This file is part of ARToolKit. + * + * ARToolKit is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ARToolKit is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ARToolKit. If not, see . + * + * As a special exception, the copyright holders of this library give you + * permission to link this library with independent modules to produce an + * executable, regardless of the license terms of these independent modules, and to + * copy and distribute the resulting executable under terms of your choice, + * provided that you also meet, for each linked independent module, the terms and + * conditions of the license of that module. An independent module is a module + * which is neither derived from nor based on this library. If you modify this + * library, you may extend this exception to your version of the library, but you + * are not obligated to do so. If you do not wish to do so, delete this exception + * statement from your version. + * + * Copyright 2015 Daqri, LLC. + * Copyright 2011-2015 ARToolworks, Inc. + * + * Author(s): Philip Lamb + * + */ + +#ifndef ARMARKERNFT_H +#define ARMARKERNFT_H + +#include +#include + +#include "Platform.h" +#if HAVE_NFT + +/** + * NFT marker type of ARMarker. + */ +class ARMarkerNFT : public ARMarker { + +private: + bool m_loaded; + float m_nftScale; + +protected: + bool unload(); + +public: + bool robustFlag; ///< Flag specifying which pose estimation approach to use + int pageNo; + char *datasetPathname; + AR2SurfaceSetT *surfaceSet; + + ARMarkerNFT(); + ~ARMarkerNFT(); + + bool load(const char* dataSetPathname_in); + + bool updateWithNFTResults(int detectedPage, float trackingTrans[3][4], ARdouble transL2R[3][4] = NULL); + + void setNFTScale(const float scale); + float getNFTScale(); +}; + +#endif // HAVE_NFT + +#endif // !ARMARKERNFT_H diff --git a/libs/include/ARWrapper/ARMarkerSquare.h b/libs/include/ARWrapper/ARMarkerSquare.h new file mode 100755 index 0000000..203b6bc --- /dev/null +++ b/libs/include/ARWrapper/ARMarkerSquare.h @@ -0,0 +1,92 @@ +/* + * ARMarkerSquare.h + * ARToolKit5 + * + * This file is part of ARToolKit. + * + * ARToolKit is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ARToolKit is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ARToolKit. If not, see . + * + * As a special exception, the copyright holders of this library give you + * permission to link this library with independent modules to produce an + * executable, regardless of the license terms of these independent modules, and to + * copy and distribute the resulting executable under terms of your choice, + * provided that you also meet, for each linked independent module, the terms and + * conditions of the license of that module. An independent module is a module + * which is neither derived from nor based on this library. If you modify this + * library, you may extend this exception to your version of the library, but you + * are not obligated to do so. If you do not wish to do so, delete this exception + * statement from your version. + * + * Copyright 2015 Daqri, LLC. + * Copyright 2011-2015 ARToolworks, Inc. + * + * Author(s): Julian Looser, Philip Lamb + * + */ + +#ifndef ARMARKERSQUARE_H +#define ARMARKERSQUARE_H + +#include + +#define AR_PATTERN_TYPE_TEMPLATE 0 +#define AR_PATTERN_TYPE_MATRIX 1 + +/** + * Single marker type of ARMarker. + */ +class ARMarkerSquare : public ARMarker { + +private: + bool m_loaded; + +protected: + ARPattHandle *m_arPattHandle; + ARdouble m_width; + ARdouble m_cf; + ARdouble m_cfMin; + + bool unload(); + +public: + + int patt_id; ///< Unique pattern ID provided by ARToolKit + int patt_type; + + ARMarkerSquare(); + ~ARMarkerSquare(); + + bool useContPoseEstimation; + ARdouble getConfidence(); + ARdouble getConfidenceCutoff(); + void setConfidenceCutoff(ARdouble value); + + bool initWithPatternFile(const char* path, ARdouble width, ARPattHandle *arPattHandle); + bool initWithPatternFromBuffer(const char* buffer, ARdouble width, ARPattHandle *arPattHandle); + bool initWithBarcode(int barcodeID, ARdouble width); + + /** + * Updates the marker with new tracking info. + * Then calls ARMarker::update() + * @param markerInfo Array containing detected marker information + * @param markerNum Number of items in the array + * @param ar3DHandle AR3DHandle used to extract marker pose. + */ + bool updateWithDetectedMarkers(ARMarkerInfo* markerInfo, int markerNum, AR3DHandle *ar3DHandle); + + bool updateWithDetectedMarkersStereo(ARMarkerInfo* markerInfoL, int markerNumL, ARMarkerInfo* markerInfoR, int markerNumR, AR3DStereoHandle *handle, ARdouble transL2R[3][4]); +}; + + +#endif // !ARMARKERSQUARE_H diff --git a/libs/include/ARWrapper/ARPattern.h b/libs/include/ARWrapper/ARPattern.h new file mode 100755 index 0000000..357abaa --- /dev/null +++ b/libs/include/ARWrapper/ARPattern.h @@ -0,0 +1,95 @@ +/* + * ARPattern.h + * ARToolKit5 + * + * This file is part of ARToolKit. + * + * ARToolKit is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ARToolKit is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ARToolKit. If not, see . + * + * As a special exception, the copyright holders of this library give you + * permission to link this library with independent modules to produce an + * executable, regardless of the license terms of these independent modules, and to + * copy and distribute the resulting executable under terms of your choice, + * provided that you also meet, for each linked independent module, the terms and + * conditions of the license of that module. An independent module is a module + * which is neither derived from nor based on this library. If you modify this + * library, you may extend this exception to your version of the library, but you + * are not obligated to do so. If you do not wish to do so, delete this exception + * statement from your version. + * + * Copyright 2015 Daqri, LLC. + * Copyright 2010-2015 ARToolworks, Inc. + * + * Author(s): Julian Looser, Philip Lamb + * + */ + +#ifndef ARPATTERN_H +#define ARPATTERN_H + +#include +#if HAVE_NFT +# include +#endif +#include + +/** + * Encapsulates information about a sub-component of a marker useful for + * presentation to a user. For a single square marker, there will be one + * pattern per marker. For a multimarker (multiple square markers), there + * will be one or more patterns per marker. + * + * Currently, the encapsulated information is the pose relative to the marker + * origin, and (for template markers only) the visual appearance of the pattern. + */ +class ARPattern { + +public: + + enum PATTERN_TYPE { + PATTERN_TYPE_NONE = 0, + PATTERN_TYPE_TEMPLATE, + PATTERN_TYPE_MATRIX, + PATTERN_TYPE_ISET + }; + + ARPattern(); + ~ARPattern(); + + bool loadTemplate(int patternID, const ARPattHandle *arPattHandle, float width); + bool loadMatrix(int barcodeID, AR_MATRIX_CODE_TYPE type, float width); +#if HAVE_NFT + bool loadISet(const AR2ImageSetT *imageSet, float nftScale); +#endif + + ARdouble m_matrix[16]; ///< Transform of the pattern from origin. + float m_width; ///< Width of the pattern in mm. + float m_height; ///< Height of the pattern in mm. + int m_imageSizeX; + int m_imageSizeY; + Color *m_image; ///< Image of the pattern + +private: + + PATTERN_TYPE m_pattType; + + bool loadImage(ARPattHandle *arPattHandle); + void freeImage(); + + // Template/matrix. + int m_patternID; ///< ID of the pattern (ARToolKit internal ID) + +}; + +#endif // !ARPATTERN_H diff --git a/libs/include/ARWrapper/ARToolKitVideoSource.h b/libs/include/ARWrapper/ARToolKitVideoSource.h new file mode 100755 index 0000000..7e812b4 --- /dev/null +++ b/libs/include/ARWrapper/ARToolKitVideoSource.h @@ -0,0 +1,72 @@ +/* + * ARToolKitVideoSource.h + * ARToolKit5 + * + * This file is part of ARToolKit. + * + * ARToolKit is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ARToolKit is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ARToolKit. If not, see . + * + * As a special exception, the copyright holders of this library give you + * permission to link this library with independent modules to produce an + * executable, regardless of the license terms of these independent modules, and to + * copy and distribute the resulting executable under terms of your choice, + * provided that you also meet, for each linked independent module, the terms and + * conditions of the license of that module. An independent module is a module + * which is neither derived from nor based on this library. If you modify this + * library, you may extend this exception to your version of the library, but you + * are not obligated to do so. If you do not wish to do so, delete this exception + * statement from your version. + * + * Copyright 2015 Daqri, LLC. + * Copyright 2010-2015 ARToolworks, Inc. + * + * Author(s): Julian Looser, Philip Lamb + * + */ + +#ifndef ARTOOLKITVIDEOSOURCE_H +#define ARTOOLKITVIDEOSOURCE_H + +#include + +#if !TARGET_PLATFORM_ANDROID + +/** + * Video source implementation using the ARToolKit arVideo module. This video source uses ARToolKit's + * built in video capture functions, and can therefore be used on any platform on which arVideo works, + * including Windows, Linux and OSX. + */ +class ARToolKitVideoSource : public VideoSource { + +protected: + + AR2VideoParamT *gVid; + +public: + + ARToolKitVideoSource(); + + virtual const char* getName(); + + virtual bool open(); + + virtual bool captureFrame(); + + virtual bool close(); + +}; + +#endif + +#endif // !#ifndef ARTOOLKITVIDEOSOURCE_H diff --git a/libs/include/ARWrapper/ARToolKitWrapperExportedAPI.h b/libs/include/ARWrapper/ARToolKitWrapperExportedAPI.h new file mode 100755 index 0000000..e9fc3ca --- /dev/null +++ b/libs/include/ARWrapper/ARToolKitWrapperExportedAPI.h @@ -0,0 +1,553 @@ +/* + * ARToolKitWrapperExportedAPI.h + * ARToolKit5 + * + * This file is part of ARToolKit. + * + * ARToolKit is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ARToolKit is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ARToolKit. If not, see . + * + * As a special exception, the copyright holders of this library give you + * permission to link this library with independent modules to produce an + * executable, regardless of the license terms of these independent modules, and to + * copy and distribute the resulting executable under terms of your choice, + * provided that you also meet, for each linked independent module, the terms and + * conditions of the license of that module. An independent module is a module + * which is neither derived from nor based on this library. If you modify this + * library, you may extend this exception to your version of the library, but you + * are not obligated to do so. If you do not wish to do so, delete this exception + * statement from your version. + * + * Copyright 2015 Daqri, LLC. + * Copyright 2010-2015 ARToolworks, Inc. + * + * Author(s): Philip Lamb, Julian Looser. + * + */ + +#ifndef ARTOOLKITWRAPPEREXPORTEDAPI_H +#define ARTOOLKITWRAPPEREXPORTEDAPI_H + +#include +#include +#include + +/** + * \file ARToolKitWrapperExportedAPI.h + * Defines functions that provide a C-compatible API. These functions are accessible to + * other C applications, as well as languages like C#. + */ +extern "C" { + + /** + * Registers a callback function to use when a message is logged. + * If the callback is to become invalid, be sure to call this function with NULL + * first so that the callback is unregistered. + */ + EXPORT_API void arwRegisterLogCallback(PFN_LOGCALLBACK callback); + + // ---------------------------------------------------------------------------------------------------- +#pragma mark ARToolKit lifecycle functions + // ---------------------------------------------------------------------------------------------------- + /** + * Initialises the ARToolKit. + * For any square template (pattern) markers, the number of rows and columns in the template defaults to AR_PATT_SIZE1 and the maximum number of markers that may be loaded for a single matching pass defaults to AR_PATT_NUM_MAX. + * @return true if successful, false if an error occurred + * @see arwShutdownAR() + */ + EXPORT_API bool arwInitialiseAR(); + + /** + * Initialises the ARToolKit with non-default options for size and number of square markers. + * @param pattSize For any square template (pattern) markers, the number of rows and columns in the template. May not be less than 16 or more than AR_PATT_SIZE1_MAX. Pass AR_PATT_SIZE1 for the same behaviour as arwInitialiseAR(). + * @param pattCountMax For any square template (pattern) markers, the maximum number of markers that may be loaded for a single matching pass. Must be > 0. Pass AR_PATT_NUM_MAX for the same behaviour as arwInitialiseAR(). + * @return true if successful, false if an error occurred + * @see arwShutdownAR() + */ + EXPORT_API bool arwInitialiseARWithOptions(const int pattSize, const int pattCountMax); + + /** + * Gets the ARToolKit version as a string, such as "4.5.1". + * Must not be called prior to arwInitialiseAR(). + * @param buffer The character buffer to populate + * @param length The maximum number of characters to set in buffer + * @return true if successful, false if an error occurred + */ + EXPORT_API bool arwGetARToolKitVersion(char *buffer, int length); + + /** + * Return error information + * Returns the value of the error flag. Each detectable error + * is assigned a numeric code and symbolic name. When an error occurs, + * the error flag is set to the appropriate error code value. No other + * errors are recorded until arwGetError is called, the error code is + * returned, and the flag is reset to AR_ERROR_NONE. If a call to + * arwGetError returns AR_ERROR_NONE, there has been no detectable error + * since the last call to arwGetError, or since the the library was initialized. + * + * To allow for distributed implementations, there may be several error + * flags. If any single error flag has recorded an error, the value of + * that flag is returned and that flag is reset to AR_ERROR_NONE when + * arwGetError is called. If more than one flag has recorded an error, + * arwGetError returns and clears an arbitrary error flag value. Thus, + * arwGetError should always be called in a loop, until it returns + * AR_ERROR_NONE, if all error flags are to be reset. + * + * Initially, all error flags are set to AR_ERROR_NONE. + * @return enum with error code. + */ + EXPORT_API int arwGetError(); + + /** + * Changes the working directory to the resources directory used by ARToolKit. + * Normally, this would be called immediately after arwInitialiseAR() + * @return true if successful, false if an error occurred + * @see arwInitialiseAR() + */ + EXPORT_API bool arwChangeToResourcesDir(const char *resourcesDirectoryPath); + + /** + * Initialises and starts video capture. + * @param vconf The video configuration string + * @param cparaName The camera parameter file, which is used to form the projection matrix + * @param nearPlane The distance to the near plane of the viewing frustum formed by the camera parameters. + * @param farPlane The distance to the far plane of the viewing frustum formed by the camera parameters. + * @return true if successful, false if an error occurred + * @see arwStopRunning() + */ + EXPORT_API bool arwStartRunning(const char *vconf, const char *cparaName, const float nearPlane, const float farPlane); + + /** + * Initialises and starts video capture. + * @param vconf The video configuration string + * @param cparaBuff A string containing the contents of a camera parameter file, which is used to form the projection matrix. + * @param cparaBuffLen Number of characters in cparaBuff. + * @param nearPlane The distance to the near plane of the viewing frustum formed by the camera parameters. + * @param farPlane The distance to the far plane of the viewing frustum formed by the camera parameters. + * @return true if successful, false if an error occurred + * @see arwStopRunning() + */ + EXPORT_API bool arwStartRunningB(const char *vconf, const char *cparaBuff, const int cparaBuffLen, const float nearPlane, const float farPlane); + + EXPORT_API bool arwStartRunningStereo(const char *vconfL, const char *cparaNameL, const char *vconfR, const char *cparaNameR, const char *transL2RName, const float nearPlane, const float farPlane); + + EXPORT_API bool arwStartRunningStereoB(const char *vconfL, const char *cparaBuffL, const int cparaBuffLenL, const char *vconfR, const char *cparaBuffR, int cparaBuffLenR, const char *transL2RBuff, const int transL2RBuffLen, const float nearPlane, const float farPlane); + + /** + * Returns true if ARToolKit is running, i.e. detecting markers. + * @return true when running, otherwise false + */ + EXPORT_API bool arwIsRunning(); + + /** + * Stops video capture and frees video capture resources. + * @return true if successful, false if an error occurred + * @see arwStartRunning() + */ + EXPORT_API bool arwStopRunning(); + + /** + * Shuts down the ARToolKit and frees all resources. + * N.B.: If this is being called from the destructor of the same module which + * supplied the log callback, be sure to set the logCallback = NULL + * prior to calling this function. + * @return true if successful, false if an error occurred + * @see arwInitialiseAR() + */ + EXPORT_API bool arwShutdownAR(); + + // ---------------------------------------------------------------------------------------------------- +#pragma mark Video stream management + // ---------------------------------------------------------------------------------------------------- + + /** + * Populates the given float array with the projection matrix computed from camera parameters for the video source. + * @param p Float array to populate with OpenGL compatible projection matrix. + * @return true if successful, false if an error occurred + */ + EXPORT_API bool arwGetProjectionMatrix(float p[16]); + + /** + * Populates the given float arrays with the projection matrices computed from camera parameters for each of the stereo video sources. + * @param pL Float array to populate with OpenGL compatible projection matrix for the left camera of the stereo video pair. + * @param pR Float array to populate with OpenGL compatible projection matrix for the right camera of the stereo video pair. + * @return true if successful, false if an error occurred + */ + EXPORT_API bool arwGetProjectionMatrixStereo(float pL[16], float pR[16]); + + /** + * Returns the parameters of the video source frame. + * @param width Pointer to an int which will be filled with the width (in pixels) of the video frame, or NULL if this information is not required. + * @param height Pointer to an int which will be filled with the height (in pixels) of the video frame, or NULL if this information is not required. + * @param pixelSize Pointer to an int which will be filled with the numbers of bytes per pixel of the source frame. + * @param pixelFormatStringBuffer Pointer to a buffer which will be filled with the symolic name of the pixel format (as a nul-terminated C-string) of the video frame, or NULL if this information is not required. The name will be of the form "AR_PIXEL_FORMAT_xxx". + * @param pixelFormatStringBufferLen Length (in bytes) of pixelFormatStringBuffer, or 0 if this information is not required. + * @return True if the values were returned OK, false if there is currently no video source or an error int[] . + * @see arwGetVideoParamsStereo + */ + EXPORT_API bool arwGetVideoParams(int *width, int *height, int *pixelSize, char *pixelFormatStringBuffer, int pixelFormatStringBufferLen); + + /** + * Returns the parameters of the video source frames. + * @param widthL Pointer to an int which will be filled with the width (in pixels) of the video frame, or NULL if this information is not required. + * @param widthR Pointer to an int which will be filled with the width (in pixels) of the video frame, or NULL if this information is not required. + * @param heightL Pointer to an int which will be filled with the height (in pixels) of the video frame, or NULL if this information is not required. + * @param heightR Pointer to an int which will be filled with the height (in pixels) of the video frame, or NULL if this information is not required. + * @param pixelSizeL Pointer to an int which will be filled with the numbers of bytes per pixel of the source frame, or NULL if this information is not required. + * @param pixelSizeR Pointer to an int which will be filled with the numbers of bytes per pixel of the source frame, or NULL if this information is not required. + * @param pixelFormatStringBufferL Pointer to a buffer which will be filled with the symbolic name of the pixel format (as a nul-terminated C-string) of the video frame, or NULL if this information is not required. The name will be of the form "AR_PIXEL_FORMAT_xxx". + * @param pixelFormatStringBufferR Pointer to a buffer which will be filled with the symbolic name of the pixel format (as a nul-terminated C-string) of the video frame, or NULL if this information is not required. The name will be of the form "AR_PIXEL_FORMAT_xxx". + * @param pixelFormatStringBufferLenL Length (in bytes) of pixelFormatStringBufferL, or 0 if this information is not required. + * @param pixelFormatStringBufferLenR Length (in bytes) of pixelFormatStringBufferR, or 0 if this information is not required. + * @return True if the values were returned OK, false if there is currently no stereo video source or an error int[] . + * @see arwGetVideoParams + */ + EXPORT_API bool arwGetVideoParamsStereo(int *widthL, int *heightL, int *pixelSizeL, char *pixelFormatStringBufferL, int pixelFormatStringBufferLenL, int *widthR, int *heightR, int *pixelSizeR, char *pixelFormatStringBufferR, int pixelFormatStringBufferLenR); + + /** + * Captures a newest frame from the video source. + * @return true if successful, false if an error occurred + */ + EXPORT_API bool arwCapture(); + + /** + * Performs detection and marker updates. The newest frame from the video source is retrieved and + * analysed. All loaded markers are updated. + * @return true if successful, false if an error occurred + */ + EXPORT_API bool arwUpdateAR(); + + /** + * Populates the provided floating-point color buffer with the current video frame. + * @param buffer The color buffer to fill with video + * @return true if successful, false if an error occurred + */ + EXPORT_API bool arwUpdateTexture(Color *buffer); + + EXPORT_API bool arwUpdateTexture32(unsigned int *buffer); + + EXPORT_API bool arwUpdateTextureStereo(Color *bufferL, Color *bufferR); + + EXPORT_API bool arwUpdateTexture32Stereo(unsigned int *bufferL, unsigned int *bufferR); + + /** + * Enables or disables debug mode in the tracker. When enabled, a black and white debug + * image is generated during marker detection. The debug image is useful for visualising + * the binarization process and choosing a threshold value. + * @param debug true to enable debug mode, false to disable debug mode + * @see arwGetVideoDebugMode() + */ + EXPORT_API void arwSetVideoDebugMode(bool debug); + + /** + * Returns whether debug mode is currently enabled. + * @return true when debug mode is enabled, false when debug mode is disabled + * @see arwSetVideoDebugMode() + */ + EXPORT_API bool arwGetVideoDebugMode(); + + /** + * Populates the provided color buffer with the current contents of the debug image. + * @param buffer Pointer to a buffer of pixels (of type 'Color') to be filled. It is the caller's responsibility to ensure that the buffer is of sufficient size. + * @return true if successful, false if an error occurred + */ + EXPORT_API bool arwUpdateDebugTexture(Color *buffer); + + + /** + * Populates the provided buffer with the current contents of the debug image. + * @param buffer Pointer to a buffer of pixels (of type 'uint32_t') to be filled. It is the + * caller's responsibility to ensure that the buffer is of sufficient size. The pixels are + * RGBA in little-endian systems, or ABGR in big-endian systems. + */ + EXPORT_API bool arwUpdateDebugTexture32(unsigned int *buffer); + +#if !TARGET_PLATFORM_WINRT + /** + * Uses OpenGL to directly updated the specified texture with the current video frame. + * @param textureID The OpenGL texture ID to upload texture data to + * @return true if successful, false if an error occurred + */ + EXPORT_API bool arwUpdateTextureGL(const int textureID); + + EXPORT_API bool arwUpdateTextureGLStereo(const int textureID_L, const int textureID_R); +#endif // !TARGET_PLATFORM_WINRT + + // ---------------------------------------------------------------------------------------------------- +#pragma mark Unity-specific API + // ---------------------------------------------------------------------------------------------------- + + enum { + ARW_UNITY_RENDER_EVENTID_NOP = 0, // No operation (does nothing). +#if !TARGET_PLATFORM_WINRT + ARW_UNITY_RENDER_EVENTID_UPDATE_TEXTURE_GL = 1, + ARW_UNITY_RENDER_EVENTID_UPDATE_TEXTURE_GL_STEREO = 2, +#endif // !TARGET_PLATFORM_WINRT + }; + + /** + When ARWrapper is loaded as a plugin into the Unity 3D environment, this function will be + called for Unity GL.IssuePluginEvent script calls. + The function will be called on a rendering thread; note that when multithreaded rendering is used, + the rendering thread WILL BE DIFFERENT from the thread that all scripts & other game logic happens. + It is up to the user to ensure any synchronization with other plugin script calls. + */ + EXPORT_API void UnityRenderEvent(int eventID); + +#if !TARGET_PLATFORM_WINRT + /** + * Uses OpenGL to directly updated the specified texture with the current video frame. + * @param textureID The OpenGL texture ID to upload texture data to + * @return true if successful, false if an error occurred + */ + EXPORT_API void arwSetUnityRenderEventUpdateTextureGLTextureID(int textureID); + + EXPORT_API void arwSetUnityRenderEventUpdateTextureGLStereoTextureIDs(int textureID_L, int textureID_R); +#endif // !TARGET_PLATFORM_WINRT + + // ---------------------------------------------------------------------------------------------------- +#pragma mark Tracking configuration + // ---------------------------------------------------------------------------------------------------- + /** + * Sets the threshold value used for image binarization. + * @param threshold The new threshold value to use + * @see arwGetVideoThreshold() + */ + EXPORT_API void arwSetVideoThreshold(int threshold); + + /** + * Returns the current threshold value used for image binarization. + * @return The current threshold value + * @see arwSetVideoThreshold() + */ + EXPORT_API int arwGetVideoThreshold(); + + /** + * Sets the current threshold mode used for image binarization. + * @param mode The new threshold mode + * @see arwSetVideoThresholdMode() + */ + EXPORT_API void arwSetVideoThresholdMode(int mode); + + /** + * Gets the current threshold mode used for image binarization. + * @return The current threshold mode + * @see arwGetVideoThresholdMode() + */ + EXPORT_API int arwGetVideoThresholdMode(); + + EXPORT_API void arwSetLabelingMode(int mode); + + EXPORT_API int arwGetLabelingMode(); + + EXPORT_API void arwSetPatternDetectionMode(int mode); + + EXPORT_API int arwGetPatternDetectionMode(); + + EXPORT_API void arwSetBorderSize(float size); + + EXPORT_API float arwGetBorderSize(); + + EXPORT_API void arwSetMatrixCodeType(int type); + + EXPORT_API int arwGetMatrixCodeType(); + + EXPORT_API void arwSetImageProcMode(int mode); + + EXPORT_API int arwGetImageProcMode(); + + EXPORT_API void arwSetNFTMultiMode(bool on); + + EXPORT_API bool arwGetNFTMultiMode(); + + // ---------------------------------------------------------------------------------------------------- +#pragma mark Marker management + // ---------------------------------------------------------------------------------------------------- + /** + * Adds a marker as specified in the given configuration string. The format of the string can be + * one of: + * - Single marker: "single;pattern_file;pattern_width", e.g. "single;data/patt.hiro;80" + * - Multi marker: "multi;config_file", e.g. "multi;data/multi/marker.dat" + * - NFT marker: "nft;nft_dataset_pathname", e.g. "nft;gibraltar" + * @param cfg The configuration string + * @return The unique identifier (UID) of the marker instantiated based on the configuration string, or -1 if an error occurred + */ + EXPORT_API int arwAddMarker(const char *cfg); + + /** + * Removes the marker with the given unique identifier (UID). + * @param markerUID The unique identifier (UID) of the marker to remove + * @return true if the marker was removed, false if an error occurred + */ + EXPORT_API bool arwRemoveMarker(int markerUID); + + /** + * Clears the collection of markers. + * @return The number of markers removed + */ + EXPORT_API int arwRemoveAllMarkers(); + + /** + * Returns the visibility status of the specified marker. After a call to arwUpdate, all marker + * information will be current. Any marker can then be checked for visibility in the current frame. + * @param markerUID The unique identifier (UID) of the marker to query + * @return true if the specified marker is visible, false if not, or an error occurred + */ + EXPORT_API bool arwQueryMarkerVisibility(int markerUID); + + /** + * Populates the provided float array with the current transformation for the specified marker. After + * a call to arwUpdate, all marker information will be current. Marker transformations can then be + * checked. If the specified marker is not found the last good transformation is used, and false is + * returned. + * @param markerUID The unique identifier (UID) of the marker to query + * @param matrix The float array to populate with an OpenGL compatible transformation matrix + * @return true if the specified marker is visible, false if not, or an error occurred + */ + EXPORT_API bool arwQueryMarkerTransformation(int markerUID, float matrix[16]); + + /** + * Populates the provided float arrays with the current transformations for the specified marker. After + * a call to arwUpdate, all marker information will be current. Marker transformations can then be + * checked. If the specified marker is not found the last good transformation is used, and false is + * returned. + * @param markerUID The unique identifier (UID) of the marker to query + * @param matrixL The float array to populate with an OpenGL compatible transformation matrix for the left camera. + * @param matrixR The float array to populate with an OpenGL compatible transformation matrix for the right camera. + * @return true if the specified marker is visible, false if not, or an error occurred + */ + EXPORT_API bool arwQueryMarkerTransformationStereo(int markerUID, float matrixL[16], float matrixR[16]); + + /** + * Returns the number of pattern images associated with the specified marker. A single marker has one pattern + * image. A multimarker has one or more pattern images. + * Images of NFT markers are not currently supported, so at present this function will return 0 for NFT markers. + * @param markerUID The unique identifier (UID) of the marker + * @return The number of pattern images + */ + EXPORT_API int arwGetMarkerPatternCount(int markerUID); + + /** + * Gets configuration of a pattern associated with a marker. + * @param markerUID The unique identifier (UID) of the marker + * @param patternID The id of the pattern within the marker, in range from 0 to arwGetMarkerPatternCount() - 1, inclusive. Ignored for single markers and NFT markers (i.e. 0 assumed). + * @param matrix The float array to populate with the 4x4 transformation matrix of the pattern (column-major order). + * @param width Float value to set to the width of the pattern + * @param height Float value to set to the height of the pattern. + * @param imageSizeX Int value to set to the width of the pattern image (in pixels). + * @param imageSizeY Int value to set to the height of the pattern image (in pixels). + * @return true if successful, false if an error occurred + */ + EXPORT_API bool arwGetMarkerPatternConfig(int markerUID, int patternID, float matrix[16], float *width, float *height, int *imageSizeX, int *imageSizeY); + + /** + * Gets a pattern image associated with a marker. The provided color buffer is populated with the image of the + * pattern for the specified marker. If the marker is a multimarker, then the pattern image specified by patternID is + * used. + * Images of NFT markers are not currently supported, so at present this function will return no image for NFT markers. + * @param markerUID The unique identifier (UID) of the marker + * @param patternID The id for the pattern within that marker. Ignored for single markers and NFT markers. + * @param buffer Color array to populate with pattern image. Use arwGetMarkerPatternConfig to get the required size of this array (imageSizeX * imageSizeY elements). + * @return true if successful, false if an error occurred + */ + EXPORT_API bool arwGetMarkerPatternImage(int markerUID, int patternID, Color *buffer); + + /** + * Constants for use with marker option setters/getters. + */ + enum { + ARW_MARKER_OPTION_FILTERED = 1, ///< bool, true for filtering enabled. + ARW_MARKER_OPTION_FILTER_SAMPLE_RATE = 2, ///< float, sample rate for filter calculations. + ARW_MARKER_OPTION_FILTER_CUTOFF_FREQ = 3, ///< float, cutoff frequency of filter. + ARW_MARKER_OPTION_SQUARE_USE_CONT_POSE_ESTIMATION = 4, ///< bool, true to use continuous pose estimate. + ARW_MARKER_OPTION_SQUARE_CONFIDENCE = 5, ///< float, confidence value of most recent marker match + ARW_MARKER_OPTION_SQUARE_CONFIDENCE_CUTOFF = 6, ///< float, minimum allowable confidence value used in marker matching. + ARW_MARKER_OPTION_NFT_SCALE = 7 ///< float, scale factor applied to NFT marker size. + }; + + /** + * Set boolean options associated with a marker. + * @param markerUID The unique identifier (UID) of the marker + * @param option Symbolic constant identifying marker option to set. + * @param value The value to set it to. + */ + EXPORT_API void arwSetMarkerOptionBool(int markerUID, int option, bool value); + + /** + * Set integer options associated with a marker. + * @param markerUID The unique identifier (UID) of the marker + * @param option Symbolic constant identifying marker option to set. + * @param value The value to set it to. + */ + EXPORT_API void arwSetMarkerOptionInt(int markerUID, int option, int value); + + /** + * Set floating-point options associated with a marker. + * @param markerUID The unique identifier (UID) of the marker + * @param option Symbolic constant identifying marker option to set. + * @param value The value to set it to. + */ + EXPORT_API void arwSetMarkerOptionFloat(int markerUID, int option, float value); + + /** + * Get boolean options associated with a marker. + * @param markerUID The unique identifier (UID) of the marker + * @param option Symbolic constant identifying marker option to get. + * @return true if option is set, false if option is not set or an error occurred. + */ + EXPORT_API bool arwGetMarkerOptionBool(int markerUID, int option); + + /** + * Get integer options associated with a marker. + * @param markerUID The unique identifier (UID) of the marker + * @param option Symbolic constant identifying marker option to get. + * @return integer value of option, or INT_MIN if an error occurred. + */ + EXPORT_API int arwGetMarkerOptionInt(int markerUID, int option); + + /** + * Get floating-point options associated with a marker. + * @param markerUID The unique identifier (UID) of the marker + * @param option Symbolic constant identifying marker option to get. + * @return floating-point value of option, or NAN if an error occurred. + */ + EXPORT_API float arwGetMarkerOptionFloat(int markerUID, int option); + + // ---------------------------------------------------------------------------------------------------- +#pragma mark Utility + // ---------------------------------------------------------------------------------------------------- + /** + * Loads an optical parameters structure from file or from buffer. + * + * @param optical_param_name If supplied, points to a buffer specifying the path + * to the optical parameters file (as generated by the calib_optical utility.) + * @param optical_param_buff If optical_param_name is NULL, the contents of this + * buffer will be interpreted as containing the contents of an optical + * parameters file. + * @param optical_param_buffLen Length of the buffer specified in optical_param_buff. + * Ignored if optical_param_buff is NULL. + * @param fovy_p Pointer to a float, which will be filled with the + * field-of-view (Y axis) component of the optical parameters, in degrees. + * @param aspect_p Pointer to a float, which will be filled with the + * aspect ratio (width / height) component of the optical parameters. + * @param m Pointer to an array of 16 floats, which will be filled with the + * transformation matrix component of the optical parameters. + * @param p (Optional) May be NULL, or a pointer to an array of 16 floats, + * which will be filled with the perspective matrix calculated from fovy and aspect + * combined with the near and far projection values supplied in arwStartRunning(). + */ + + EXPORT_API bool arwLoadOpticalParams(const char *optical_param_name, const char *optical_param_buff, const int optical_param_buffLen, float *fovy_p, float *aspect_p, float m[16], float p[16]); +} + +#endif // !ARTOOLKITWRAPPEREXPORTEDAPI_H diff --git a/libs/include/ARWrapper/AndroidFeatures.h b/libs/include/ARWrapper/AndroidFeatures.h new file mode 100755 index 0000000..2f22f44 --- /dev/null +++ b/libs/include/ARWrapper/AndroidFeatures.h @@ -0,0 +1,53 @@ +/* + * AndroidFeatures.h + * ARToolKit5 + * + * This file is part of ARToolKit. + * + * ARToolKit is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ARToolKit is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ARToolKit. If not, see . + * + * As a special exception, the copyright holders of this library give you + * permission to link this library with independent modules to produce an + * executable, regardless of the license terms of these independent modules, and to + * copy and distribute the resulting executable under terms of your choice, + * provided that you also meet, for each linked independent module, the terms and + * conditions of the license of that module. An independent module is a module + * which is neither derived from nor based on this library. If you modify this + * library, you may extend this exception to your version of the library, but you + * are not obligated to do so. If you do not wish to do so, delete this exception + * statement from your version. + * + * Copyright 2015 Daqri, LLC. + * Copyright 2010-2015 ARToolworks, Inc. + * + * Author(s): Julian Looser + * + */ + +#ifndef ANDROIDFEATURES_H +#define ANDROIDFEATURES_H + +#include + +#if TARGET_PLATFORM_ANDROID + +# include +# include +# include + +long nanoTime(); + +#endif + +#endif // !ANDROIDFEATURES_H diff --git a/libs/include/ARWrapper/AndroidVideoSource.h b/libs/include/ARWrapper/AndroidVideoSource.h new file mode 100755 index 0000000..f543134 --- /dev/null +++ b/libs/include/ARWrapper/AndroidVideoSource.h @@ -0,0 +1,95 @@ +/* + * AndroidVideoSource.h + * ARToolKit5 + * + * This file is part of ARToolKit. + * + * ARToolKit is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ARToolKit is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ARToolKit. If not, see . + * + * As a special exception, the copyright holders of this library give you + * permission to link this library with independent modules to produce an + * executable, regardless of the license terms of these independent modules, and to + * copy and distribute the resulting executable under terms of your choice, + * provided that you also meet, for each linked independent module, the terms and + * conditions of the license of that module. An independent module is a module + * which is neither derived from nor based on this library. If you modify this + * library, you may extend this exception to your version of the library, but you + * are not obligated to do so. If you do not wish to do so, delete this exception + * statement from your version. + * + * Copyright 2015 Daqri, LLC. + * Copyright 2010-2015 ARToolworks, Inc. + * + * Author(s): Julian Looser, Philip Lamb + * + */ + +#ifndef ANDROIDVIDEOSOURCE_H +#define ANDROIDVIDEOSOURCE_H + +#include +#include + +#if TARGET_PLATFORM_ANDROID + +/** + * Video input implementation for Android. On Android, video capture occurs in Java, and the frame data + * is passed across to the native code using JNI. Therefore, ARToolKit cannot open the camera and + * initiate video capture in the same way as it does on other platforms. Instead, the video source remains + * closed until the first frame arrives over JNI. + */ +class AndroidVideoSource : public VideoSource { + +private: + + bool newFrameArrived; + ARUint8 *localFrameBuffer; + size_t frameBufferSize; + + static void getVideoReadyAndroidCparamCallback(const ARParam *cparam_p, void *userdata); + bool getVideoReadyAndroid2(const ARParam *cparam_p); + +protected: + + AR2VideoParamT *gVid; + int gCameraIndex; + bool gCameraIsFrontFacing; + +public: + + AndroidVideoSource(); + + bool getVideoReadyAndroid(const int width, const int height, const int cameraIndex, const bool cameraIsFrontFacing); + + virtual bool open(); + + /** + * Returns the size of current frame. + * @return Size of the buffer containing the current video frame + */ + size_t getFrameSize(); + + void acceptImage(ARUint8* ptr); + + virtual bool captureFrame(); + + virtual bool close(); + + virtual const char* getName(); + +}; + +#endif + +#endif // !ANDROIDVIDEOSOURCE_H diff --git a/libs/include/ARWrapper/ColorConversion.h b/libs/include/ARWrapper/ColorConversion.h new file mode 100755 index 0000000..007bcfb --- /dev/null +++ b/libs/include/ARWrapper/ColorConversion.h @@ -0,0 +1,43 @@ +/* + * ColorConversion.h + * ARToolKit5 + * + * This file is part of ARToolKit. + * + * ARToolKit is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ARToolKit is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ARToolKit. If not, see . + * + * As a special exception, the copyright holders of this library give you + * permission to link this library with independent modules to produce an + * executable, regardless of the license terms of these independent modules, and to + * copy and distribute the resulting executable under terms of your choice, + * provided that you also meet, for each linked independent module, the terms and + * conditions of the license of that module. An independent module is a module + * which is neither derived from nor based on this library. If you modify this + * library, you may extend this exception to your version of the library, but you + * are not obligated to do so. If you do not wish to do so, delete this exception + * statement from your version. + * + * Copyright 2015 Daqri, LLC. + * Copyright 2010-2015 ARToolworks, Inc. + * + * Author(s): Julian Looser, Philip Lamb + * + */ + +#ifndef COLORCONVERSION_H +#define COLORCONVERSION_H + +void color_convert_common(unsigned char *pY, unsigned char *pUV, int width, int height, unsigned char *buffer); + +#endif // !COLORCONVERSION_H diff --git a/libs/include/ARWrapper/Error.h b/libs/include/ARWrapper/Error.h new file mode 100755 index 0000000..522fe21 --- /dev/null +++ b/libs/include/ARWrapper/Error.h @@ -0,0 +1,70 @@ +/* + * Error.h + * ARToolKit5 + * + * This file is part of ARToolKit. + * + * ARToolKit is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ARToolKit is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ARToolKit. If not, see . + * + * As a special exception, the copyright holders of this library give you + * permission to link this library with independent modules to produce an + * executable, regardless of the license terms of these independent modules, and to + * copy and distribute the resulting executable under terms of your choice, + * provided that you also meet, for each linked independent module, the terms and + * conditions of the license of that module. An independent module is a module + * which is neither derived from nor based on this library. If you modify this + * library, you may extend this exception to your version of the library, but you + * are not obligated to do so. If you do not wish to do so, delete this exception + * statement from your version. + * + * Copyright 2015 Daqri, LLC. + * Copyright 2014-2015 ARToolworks, Inc. + * + * Author(s): Philip Lamb + * + */ + +#ifndef ARWRAPPER_ERROR_H +#define ARWRAPPER_ERROR_H + +/** + * \file Error.h + * Defines error codes used in the ARWrapper library. + */ + +#ifdef __cplusplus +extern "C" { +#endif + + enum { + ARW_ERROR_NONE = 0, + ARW_ERROR_GENERIC = -1, + ARW_ERROR_OUT_OF_MEMORY = -2, + ARW_ERROR_OVERFLOW = -3, + ARW_ERROR_NODATA = -4, + ARW_ERROR_IOERROR = -5, + ARW_ERROR_EOF = -6, + ARW_ERROR_TIMEOUT = -7, + ARW_ERROR_INVALID_COMMAND = -8, + ARW_ERROR_INVALID_ENUM = -9, + ARW_ERROR_THREADS = -10, + ARW_ERROR_FILE_NOT_FOUND = -11, + ARW_ERROR_LENGTH_UNAVAILABLE = -12, + ARW_ERROR_DEVICE_UNAVAILABLE = -13 + }; + +#ifdef __cplusplus +} +#endif +#endif // !ARWRAPPER_ERROR_H diff --git a/libs/include/ARWrapper/Image.h b/libs/include/ARWrapper/Image.h new file mode 100755 index 0000000..07d6f00 --- /dev/null +++ b/libs/include/ARWrapper/Image.h @@ -0,0 +1,51 @@ +/* + * Image.h + * ARToolKit5 + * + * This file is part of ARToolKit. + * + * ARToolKit is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ARToolKit is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ARToolKit. If not, see . + * + * As a special exception, the copyright holders of this library give you + * permission to link this library with independent modules to produce an + * executable, regardless of the license terms of these independent modules, and to + * copy and distribute the resulting executable under terms of your choice, + * provided that you also meet, for each linked independent module, the terms and + * conditions of the license of that module. An independent module is a module + * which is neither derived from nor based on this library. If you modify this + * library, you may extend this exception to your version of the library, but you + * are not obligated to do so. If you do not wish to do so, delete this exception + * statement from your version. + * + * Copyright 2015 Daqri, LLC. + * Copyright 2011-2015 ARToolworks, Inc. + * + * Author(s): Julian Looser, Philip Lamb + * + */ + +#ifndef IMAGE_H +#define IMAGE_H + +/** + * Simple color representation using four float values. + */ +struct Color { + float r; ///< Red component + float g; ///< Green component + float b; ///< Blue component + float a; ///< Alpha component +}; + +#endif // !IMAGE_H diff --git a/libs/include/ARWrapper/Platform.h b/libs/include/ARWrapper/Platform.h new file mode 100755 index 0000000..677f6e9 --- /dev/null +++ b/libs/include/ARWrapper/Platform.h @@ -0,0 +1,142 @@ +/* + * Platform.h + * ARToolKit5 + * + * This file is part of ARToolKit. + * + * ARToolKit is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ARToolKit is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ARToolKit. If not, see . + * + * As a special exception, the copyright holders of this library give you + * permission to link this library with independent modules to produce an + * executable, regardless of the license terms of these independent modules, and to + * copy and distribute the resulting executable under terms of your choice, + * provided that you also meet, for each linked independent module, the terms and + * conditions of the license of that module. An independent module is a module + * which is neither derived from nor based on this library. If you modify this + * library, you may extend this exception to your version of the library, but you + * are not obligated to do so. If you do not wish to do so, delete this exception + * statement from your version. + * + * Copyright 2015 Daqri, LLC. + * Copyright 2011-2015 ARToolworks, Inc. + * + * Author(s): Julian Looser, Philip Lamb + * + */ + +#ifndef PLATFORM_H +#define PLATFORM_H + +// Determine the platform on which the code is being built + +#if defined _WIN32 || defined _WIN64 + +// Include Windows API. +# ifndef WIN32_LEAN_AND_MEAN +# define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers +# endif +# include // Minimum supported version. See http://msdn.microsoft.com/en-us/library/windows/desktop/aa383745.aspx +# include +# if defined(WINAPI_FAMILY) +# if (WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP) // Windows Phone 8.1 and later. +# if (_WIN32_WINNT >= 0x0603) // (_WIN32_WINNT_WINBLUE) +# define TARGET_PLATFORM_WINRT 1 +# else +# error ARToolKit for Windows Phone requires Windows Phone 8.1 or later. Please compile with Visual Studio 2013 or later with Windows Phone 8.1 SDK installed and with _WIN32_WINNT=0x0603 in your project compiler settings (setting /D_WIN32_WINNT=0x0603). +# endif +# elif (WINAPI_FAMILY == WINAPI_FAMILY_PC_APP) // Windows Store 8.1 and later. +# if (_WIN32_WINNT >= 0x0603) // (_WIN32_WINNT_WINBLUE) +# define TARGET_PLATFORM_WINRT 1 +# else +# error ARToolKit for Windows Store requires Windows 8.1 or later. Please compile with Visual Studio 2013 or later with Windows 8.1 SDK installed and with _WIN32_WINNT=0x0603 in your project compiler settings (setting /D_WIN32_WINNT=0x0603). +# endif +# else +# define TARGET_PLATFORM_WINDOWS 1 +# endif +# else +# define TARGET_PLATFORM_WINDOWS 1 +# endif + +#elif __APPLE__ + +# include +# include +# if TARGET_IPHONE_SIMULATOR +# elif TARGET_OS_IPHONE +# define TARGET_PLATFORM_IOS 1 +# elif TARGET_OS_MAC +# define TARGET_PLATFORM_OSX 1 +# endif + +#elif defined ANDROID + +# define TARGET_PLATFORM_ANDROID 1 + +#elif __linux__ + +# define TARGET_PLATFORM_LINUX 1 + +#else + +# error Unsupported platform. + +#endif + +// Configure preprocessor definitions for current platform + +#if TARGET_PLATFORM_WINDOWS + +# define EXPORT_API __declspec(dllexport) +# define CALL_CONV __stdcall +# define LOGI(...) fprintf(stdout, __VA_ARGS__) +# define LOGE(...) fprintf(stderr, __VA_ARGS__) + +#elif TARGET_PLATFORM_WINRT + +# ifndef LIBARWRAPPER_STATIC +# ifdef LIBARWRAPPER_EXPORTS +# define EXPORT_API __declspec(dllexport) +# else +# define EXPORT_API __declspec(dllimport) +# endif +# else +# define EXPORT_API extern +# endif +# define CALL_CONV __stdcall +# define LOGI(...) fprintf(stdout, __VA_ARGS__) +# define LOGE(...) fprintf(stderr, __VA_ARGS__) + +#elif TARGET_PLATFORM_OSX || TARGET_PLATFORM_IOS || TARGET_PLATFORM_LINUX + +# define EXPORT_API +# define CALL_CONV +# define LOGI(...) fprintf(stdout, __VA_ARGS__) +# define LOGE(...) fprintf(stderr, __VA_ARGS__) + +#elif TARGET_PLATFORM_ANDROID + +# define EXPORT_API +# define CALL_CONV +# define LOGI(...) __android_log_print(ANDROID_LOG_INFO,"libARWrapper",__VA_ARGS__) +# define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,"libARWrapper",__VA_ARGS__) + +// Utility preprocessor directive so only one change needed if Java class name changes +# define JNIFUNCTION(sig) Java_org_artoolkit_ar_base_NativeInterface_##sig + +#endif + +typedef void (CALL_CONV *PFN_LOGCALLBACK)(const char* msg); + + +#endif // !PLATFORM_H diff --git a/libs/include/ARWrapper/VideoSource.h b/libs/include/ARWrapper/VideoSource.h new file mode 100755 index 0000000..ca948c2 --- /dev/null +++ b/libs/include/ARWrapper/VideoSource.h @@ -0,0 +1,221 @@ +/* + * VideoSource.h + * ARToolKit5 + * + * This file is part of ARToolKit. + * + * ARToolKit is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ARToolKit is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ARToolKit. If not, see . + * + * As a special exception, the copyright holders of this library give you + * permission to link this library with independent modules to produce an + * executable, regardless of the license terms of these independent modules, and to + * copy and distribute the resulting executable under terms of your choice, + * provided that you also meet, for each linked independent module, the terms and + * conditions of the license of that module. An independent module is a module + * which is neither derived from nor based on this library. If you modify this + * library, you may extend this exception to your version of the library, but you + * are not obligated to do so. If you do not wish to do so, delete this exception + * statement from your version. + * + * Copyright 2015 Daqri, LLC. + * Copyright 2010-2015 ARToolworks, Inc. + * + * Author(s): Julian Looser, Philip Lamb + * + */ + +#ifndef VIDEOSOURCE_H +#define VIDEOSOURCE_H + +#include "Platform.h" + +#include +#include + +#include + +#ifndef _WINRT +# if TARGET_PLATFORM_ANDROID || TARGET_PLATFORM_IOS +# include +# else +# include + #endif +#endif + +/** + * Base class for different video source implementations. A video source provides video frames to the + * ARToolKit tracking module. Video sources contain information about the video, such as size and pixel + * format, camera parameters for distortion compensation, as well as the raw video data itself. Different + * video source implementations are required to provide a standard interface for video input, even though + * different platforms handle video input quite differently. + */ +class VideoSource { + +protected: + + typedef enum { + DEVICE_CLOSED, ///< Device is closed. + DEVICE_OPEN, ///< Device is open. + DEVICE_GETTING_READY, ///< Device is moving from open to running. + DEVICE_RUNNING ///< Device is open and able to be queried. + } DeviceState; + + DeviceState deviceState; ///< Current state of the video device + + char* cameraParam; ///< Camera parameter filename + char* cameraParamBuffer; + size_t cameraParamBufferLen; + ARParamLT *cparamLT; ///< Camera paramaters + + char* videoConfiguration; ///< Video configuration string + + int videoWidth; ///< Width of the video frame in pixels + int videoHeight; ///< Height of the video frame in pixels + + AR_PIXEL_FORMAT pixelFormat; ///< Pixel format from ARToolKit enumeration. +#if defined(HAVE_ARM_NEON) || defined(HAVE_ARM64_NEON) + int m_fastPath; +#endif +#ifndef _WINRT + GLenum glPixIntFormat; + GLenum glPixFormat; + GLenum glPixType; +#endif + + ARUint8 *frameBuffer; ///< Pointer to latest frame. Set by concrete subclass to point to frame data. + ARUint8 *frameBuffer2; ///< For bi-planar formats, pointer to plane 2 of latest frame. Set by concrete subclass to point to frame data. + int frameStamp; ///< Latest framestamp. Incremented in the concrete subclass when a new frame arrives. + + int m_error; + void setError(int error); + + /** + * The constructor is not public because instances are created using a factory method. + * @see newVideoSource() + */ + VideoSource(); + +public: + + /** + * Returns the correct VideoSource subclass for use on the current platform. + * @return New instance of an appropriate VideoSource + */ + static VideoSource* newVideoSource(); + + virtual ~VideoSource(); + + int getError(); + + /** + * Returns true if the video source is open + * @return true if the video source is open + */ + bool isOpen(); + + /** + * Returns true if the video source is open and ready to be queried. + * @return true if the video source is open and frame details are known + */ + bool isRunning(); + + /** + * Sets initial parameters which will be used when the video source + * is opened. + */ + void configure(const char* vconf, const char* cparaName, const char* cparaBuff, size_t cparaBuffLen); + + + /** + * Returns the camera parameters for the video source. + * @return the camera parameters + */ + ARParamLT* getCameraParameters(); + + /** + * Returns the width of the video in pixels. + * @return Width of the video in pixels + */ + int getVideoWidth(); + + /** + * Returns the height of the video in pixels. + * @return Height of the video in pixels + */ + int getVideoHeight(); + + /** + * Returns the pixel format of the video. + * @return Pixel format of the video + */ + AR_PIXEL_FORMAT getPixelFormat(); + + /** + * Returns the name of this video source variation. This method must be provided by + * the subclass. + * @return Name of the video source + */ + virtual const char* getName() = 0; + + /** + * Opens the video source. This method must be provided by the subclass. + * @return true if the video source was opened successfully, false if a fatal error occured. + */ + virtual bool open() = 0; + + /** + * Closes the video source. This method must be provided by the subclass. + * @return true if the video source was closed successfully, otherwise false. + */ + virtual bool close() = 0; + + /** + * Asks the video source to capture a frame. This method must be provided by the subclass. + * @return true if the video source captured a frame, otherwise false + */ + virtual bool captureFrame() = 0; + + /** + * Returns the current frame. + * @return Pointer to the buffer containing the current video frame + */ + ARUint8* getFrame(); + + /** + * Returns the current frame stamp. If the returned value has changed since the last + * time this function was called, then the caller can assume a new frame is available. + * @return The current frame stamp, incremented on each new frame arrival + */ + int getFrameStamp(); + + /** + * Populates the provided color buffer with the current video frame. + * @param buffer The color buffer to populate with frame data + * @return true if the buffer was updated successfully, otherwise false + */ + bool updateTexture(Color* buffer); + + bool fastPath(); + bool updateTexture32(uint32_t *buffer); + +#ifndef _WINRT + /** + * Updates the specified OpenGL texture with the current video frame + * @param textureID The OpenGL texture ID to which the video frame should be uploaded + */ + void updateTextureGL(int textureID); +#endif +}; + +#endif // !VIDEOSOURCE_H diff --git a/libs/include/Eden/Eden.h b/libs/include/Eden/Eden.h new file mode 100755 index 0000000..a9b53e0 --- /dev/null +++ b/libs/include/Eden/Eden.h @@ -0,0 +1,233 @@ +// +// Eden.h +// +// Compiler and platform specific constants, needed for entire projects. +// This file should be included with the project as a prefix header +// (i.e., implicitly included from every source file.) +// +// Copyright (c) 2001-2013 Philip Lamb (PRL) phil@eden.net.nz. All rights reserved. +// +// Rev Date Who Changes +// 1.0.0 2001-10-12 PRL Initial version for The SRMS simulator. +// 1.0.1 2004-04-27 PRL Many changes over many moons. +// 1.0.2 2004-08-05 PRL Moved out of SRMSsim. +// + +// @@BEGIN_EDEN_LICENSE_HEADER@@ +// +// This file is part of The Eden Library. +// +// The Eden Library is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// The Eden Library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with The Eden Library. If not, see . +// +// As a special exception, the copyright holders of this library give you +// permission to link this library with independent modules to produce an +// executable, regardless of the license terms of these independent modules, and to +// copy and distribute the resulting executable under terms of your choice, +// provided that you also meet, for each linked independent module, the terms and +// conditions of the license of that module. An independent module is a module +// which is neither derived from nor based on this library. If you modify this +// library, you may extend this exception to your version of the library, but you +// are not obligated to do so. If you do not wish to do so, delete this exception +// statement from your version. +// +// @@END_EDEN_LICENSE_HEADER@@ + +#ifndef __Eden_h__ +#define __Eden_h__ + +// +// Keep it simple: define compiler, platform and architecture capabilities here +// rather than using a configure script. +// + +#include +#ifndef _WIN32 // errno is defined in stdlib.h on Windows. +# include +#endif +#ifdef __ANDROID__ +# include +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef __ANDROID__ +# define EDEN_LOG(...) __android_log_print(ANDROID_LOG_INFO, "libeden", __VA_ARGS__); +# define EDEN_LOGe(...) __android_log_print(ANDROID_LOG_ERROR, "libeden", __VA_ARGS__); +# define EDEN_LOGperror(s) __android_log_print(ANDROID_LOG_ERROR, "libeden", (s ? "%s: %s\n" : "%s%s\n"), (s ? s : ""), strerror(errno)) +#else +# define EDEN_LOG(...) printf(__VA_ARGS__) +# define EDEN_LOGe(...) fprintf(stderr, __VA_ARGS__) +# define EDEN_LOGperror(s) fprintf(stderr, (s ? "%s: %s\n" : "%s%s\n"), (s ? s : ""), strerror(errno)) +#endif + +// Check architecture endianess using gcc's macro, or assume little-endian by default. +// Also, define attribute to produce a tightly packed structure (i.e. all structures +// byte-aligned.) +// I don't know how to do this in compilers other than GCC at the moment. +#if defined(__GNUC__) +# if defined(__BIG_ENDIAN__) +# define EDEN_BIGENDIAN // Most Significant Byte has greatest address in memory. +# endif +# define EDEN_INLINE_H extern inline +# define EDEN_INLINE_C +# define EDEN_PACKED __attribute__ ((__packed__)) +#else +# define EDEN_PACKED +#endif + +// GCC on Mac OS X. +#if defined(__APPLE__) +# define EDEN_UNIX +# define EDEN_HAVE_PTHREAD_RELATIVE_TIMEDWAIT +# include +# include +# if TARGET_RT_BIG_ENDIAN +# define EDEN_BIGENDIAN // Most Significant Byte has greatest address in memory (ppc). +# elif TARGET_RT_LITTLE_ENDIAN +# undef EDEN_BIGENDIAN +# else +# error +# endif + +# if TARGET_OS_IPHONE +# define EDEN_IPHONEOS +# define EDEN_OPENGLES +# endif + +# if !defined(DARWINONLY) && !TARGET_OS_IPHONE +# define EDEN_MACOSX // Running under Mac OS X. +//# define EDEN_HAVE_HID // Has HID API available (for joystick). +//# define EDEN_HAVE_ARTOOLKIT +# define EDEN_HAVE_MACOSX_CGL +# if !defined(__LP64__) +# define EDEN_HAVE_CARBON +# endif +# endif + +# define EDEN_HAVE_LIBJPEG +# define EDEN_HAVE_OPENAL + +// GCC on Android (NDK) +#elif defined(__ANDROID__) +# define EDEN_UNIX +# define EDEN_OPENGLES +# define EDEN_HAVE_LIBJPEG +# ifndef ANDROID +# define ANDROID +# endif + +// GCC on Cygnus GNU for Windows. +#elif defined(__CYGWIN__) +# define EDEN_UNIX // Its a Unix system too! +# define EDEN_SERIAL_POSIX_ONLY // Use only POSIX-compliant serial calls. + +// GCC on Linux. +#elif defined(__linux__) +# define EDEN_UNIX // Its a Unix-like system. +//# define EDEN_HAVE_ARTOOLKIT + +// GCC on NetBSD. +#elif defined(__NetBSD__) +# define EDEN_UNIX + +// MrC on Mac OS Classic. +#elif defined(__MRC__) +# define EDEN_MACOS +# define EDEN_BIGENDIAN // Most Significant Byte is highest in memory. +# define EDEN_HAVE_HID // Has HID API available (for joystick). +# define EDEN_HAVE_CARBON +# define EDEN_INLINE_H +# define EDEN_INLINE_C + +// Microsoft C++ on Windows. +#elif defined(_MSC_VER) +# include // Is this correct? +# undef EDEN_BIGENDIAN // Least Significant Byte is highest in memory. +# define EDEN_HAVE_LIBJPEG +//# define EDEN_HAVE_OPENAL +//# define EDEN_HAVE_ARTOOLKIT +# pragma warning (disable:4068) // Disable bogus unknown pragma warnings. +# pragma warning (disable:4244) // Disable bogus conversion warnings. +# pragma warning (disable:4305) // Disable bogus conversion warnings. +# define EDEN_INLINE_H __inline +# define EDEN_INLINE_C __inline + +// Generic POSIX-compliant Unix. +#elif defined(_POSIX) +# define EDEN_UNIX +# define EDEN_SERIAL_POSIX_ONLY // Use only POSIX-compliant serial calls. +# define EDEN_INLINE_H +# define EDEN_INLINE_C + +// Irix on SGI hardware. +#elif defined(__sgi) +# define EDEN_BIGENDIAN // Most Significant Byte is highest in memory. +# define EDEN_UNIX // Its a Unix system. +//# define EDEN_HAVE_ARTOOLKIT +# define EDEN_INLINE_H +# define EDEN_INLINE_C + +#else +# error Unrecognised compiler in __FILE__. +#endif + + +// +// Application code which is dependent on platform capabilities. +// + +// Features common to all our supported Unix platforms. +#ifdef EDEN_UNIX +# define EDEN_HAVE_STRINGS_H +# define EDEN_HAVE_CTIME_R_IN_TIME_H +#endif // EDEN_UNIX + +// +// Miscellany. +// + +// Use these definitions rather than those in . +typedef int EDEN_BOOL; +#define EDEN_BOOL_DEFINED +#ifndef TRUE +# define TRUE 1 +#else +# if (TRUE != 1) +# error 'TRUE incorrectly defined somewhere other than __FILE__.' +# endif +#endif +#ifndef FALSE +# define FALSE 0 +#else +# if (FALSE != 0) +# error 'FALSE incorrectly defined somewhere other than __FILE__.' +# endif +#endif + +// ASCII keycodes. +#define EDEN_ASCII_ESC 27 +#define EDEN_ASCII_TAB 9 +#define EDEN_ASCII_BS 8 +#define EDEN_ASCII_CR 13 +#define EDEN_ASCII_DEL 127 + + +#ifdef __cplusplus +} +#endif + +#endif // !__Eden_h__ + diff --git a/libs/include/Eden/EdenError.h b/libs/include/Eden/EdenError.h new file mode 100755 index 0000000..0e45d08 --- /dev/null +++ b/libs/include/Eden/EdenError.h @@ -0,0 +1,210 @@ +// +// EdenError.h +// +// Copyright (c) 2004-2012 Philip Lamb (PRL) phil@eden.net.nz. All rights reserved. +// +// Rev Date Who Changes +// 1.0.0 2004-06-01 PRL Pulled together from other headers. +// +// + +// @@BEGIN_EDEN_LICENSE_HEADER@@ +// +// This file is part of The Eden Library. +// +// The Eden Library is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// The Eden Library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with The Eden Library. If not, see . +// +// As a special exception, the copyright holders of this library give you +// permission to link this library with independent modules to produce an +// executable, regardless of the license terms of these independent modules, and to +// copy and distribute the resulting executable under terms of your choice, +// provided that you also meet, for each linked independent module, the terms and +// conditions of the license of that module. An independent module is a module +// which is neither derived from nor based on this library. If you modify this +// library, you may extend this exception to your version of the library, but you +// are not obligated to do so. If you do not wish to do so, delete this exception +// statement from your version. +// +// @@END_EDEN_LICENSE_HEADER@@ + +// HeaderDoc documentation included. See http://developer.apple.com/darwin/projects/headerdoc/ + +/*! + @header EdenError + @abstract Error codes and error reporting for the Eden library. + @version 1.0.0 + @updated 2004-06-01 + @discussion +*/ + +#ifndef __EdenError_h__ +#define __EdenError_h__ + +// ============================================================================ +// Includes +// ============================================================================ + +#ifndef __Eden_h__ +# include +#endif +#include // stderr, fprintf(), vfprintf() + +#ifdef __cplusplus +extern "C" { +#endif + +// ============================================================================ +// Public defines +// ============================================================================ + +/*! + @enum EDEN_E_* + @abstract Symbolic codes for errors reported by routines in the Eden Library. + @discussion + As the actual numerical values for certain errors may change from time + to time, these symbolic codes should be used instead. + @constant EDEN_E_NONE No error. + @constant EDEN_E_GENERIC Error. + @constant EDEN_E_OUT_OF_MEMORY Out of memory. + @constant EDEN_E_OVERFLOW Overflow. + @constant EDEN_E_NODATA Data was requested but none was available. + @constant EDEN_E_IOERROR Error during input / output operation. + @constant EDEN_E_EOF End of file reached. + @constant EDEN_E_TIMEOUT Timed out. + @constant EDEN_E_INVALID_COMMAND Invalid command. + @constant EDEN_E_INVALID_ENUM Invalid enumeration. + @constant EDEN_E_THREADS An error occured during a thread-management operation. + @constant EDEN_E_FILE_NOT_FOUND File not found. + @constant EDEN_E_LENGTH_UNAVAILABLE Length not available. + @constant EDEN_E_GENERIC_TOOLBOX Error returned from System tool. + @constant EDEN_E_LIBRARY_NOT_AVAILABLE A required library is not installed. + @constant EDEN_E_LIBRARY_TOO_OLD The minimum version requirement of a library was not met. + @constant EDEN_E_LIBRARY_TOO_NEW The maximum version requirement of a library was not met. + @constant EDEN_E_HARDWARE_GENERIC Hardware error. + @constant EDEN_E_HARDWARE_NOT_AVAILABLE Required hardware is not available. + @constant EDEN_E_BIRD_CONFIGURATION The bird hardware is incorrectly configured. + @constant EDEN_E_BIRD_PHASEERROR Data from the bird was lost and arrived from the bird out-of-phase. + @constant EDEN_E_NET_GENERIC Network error. + @constant EDEN_E_NET_NOT_AVAILABLE Network not available. + @constant EDEN_E_NET_NOT_CONNECTED Network not connected. + */ +enum { + EDEN_E_NONE = 0, + EDEN_E_GENERIC = -1, + EDEN_E_OUT_OF_MEMORY = -2, + EDEN_E_OVERFLOW = -3, + EDEN_E_NODATA = -4, + EDEN_E_IOERROR = -5, + EDEN_E_EOF = -6, + EDEN_E_TIMEOUT = -7, + EDEN_E_INVALID_COMMAND = -8, + EDEN_E_INVALID_ENUM = -9, + EDEN_E_THREADS = -10, + EDEN_E_FILE_NOT_FOUND = -11, + EDEN_E_LENGTH_UNAVAILABLE = -12, + EDEN_E_GENERIC_TOOLBOX = -10001, + EDEN_E_LIBRARY_NOT_AVAILABLE = -10002, + EDEN_E_LIBRARY_TOO_OLD = -10003, + EDEN_E_LIBRARY_TOO_NEW = -10004, + EDEN_E_HARDWARE_GENERIC = -11001, + EDEN_E_HARDWARE_NOT_AVAILABLE = -11002, + EDEN_E_BIRD_CONFIGURATION = -11202, + EDEN_E_BIRD_PHASEERROR = -11203, + EDEN_E_NET_GENERIC = -12001, + EDEN_E_NET_NOT_AVAILABLE = -12002, + EDEN_E_NET_NOT_CONNECTED = -12003, +}; + +// ============================================================================ +// Public types. +// ============================================================================ +/*! + @typedef EDEN_E_t + @abstract Return type of routines in the Eden Library. + @discussion + Zero and positive values are used to report success, and possibly, return data. + An error is indicated by a value less than zero. Symbolic values for the error + codes are available. +*/ +typedef signed int EDEN_E_t; + +// ============================================================================ +// Public globals. +// ============================================================================ + +// ============================================================================ +// Public functions. +// ============================================================================ + +/*! + @function + @abstract Produce an error string from an Eden Library error code. + @discussion + Produces a null-terminated ASCII string with a description of the error + represented by the supplied code, followed by the code itself, in brackets. + See also EdenError_strerror_r, EdenError_perror. + @param code The code to produce the string for, as returned by various routines + in the Eden Library. + @result Pointer to a null-terminated constant character string. + @seealso EdenError_strerror_r EdenError_strerror_r + */ +const char *EdenError_strerror(const EDEN_E_t code); + +/*! + @function + @abstract Produce an error string from an Eden Library error code. + @discussion + Produces an ASCII string with a description of the error + corresponding to the supplied code, and copies up to buflen + characters of the string into strerrbuf + See also EdenError_strerror, EdenError_perror. + @param code The code to produce the string for, as returned by various routines + in the Eden Library. + @param strerrbuf Buffer to copy the error string into. + @param buflen Number of characters available in strerrbuf. The null + terminator counts as one character. + @result + Returns 0 on success. + If the error number is not recognized, returns EINVAL as a warning. + If insufficient storage is provided in strerrbuf (as specified in buflen) + to contain the error string, returns ERANGE and strerrbuf + will contain an error message that has been truncated and NUL terminated + to fit the length specified by buflen. + @seealso EdenError_strerror EdenError_strerror + */ +int EdenError_strerror_r(const EDEN_E_t code, char *strerrbuf, const size_t buflen); + +/*! + @function + @abstract Print an Eden Library error message and code to stderr, with optional string. + @discussion + Finds the error message corresponding to the supplied code, + and writes it, followed by a newline, to the standard error file + descriptor. If the argument string is non-NULL and does not point + to the null character, this string is prepended to the message string + and separated from it by a colon and space (": "); otherwise, only + the error message string is printed. + @param code The code to produce the string for, as returned by various routines + in the Eden Library. + @seealso EdenError_strerror EdenError_strerror + @seealso EdenError_strerror_r EdenError_strerror_r + */ +void EdenError_perror(const EDEN_E_t code, const char *string); + +#ifdef __cplusplus +} +#endif + +#endif // !__EdenError_h__ + diff --git a/libs/include/Eden/EdenGLFont.h b/libs/include/Eden/EdenGLFont.h new file mode 100755 index 0000000..e659187 --- /dev/null +++ b/libs/include/Eden/EdenGLFont.h @@ -0,0 +1,443 @@ +// +// EdenGLFont.h +// The Eden Library +// +// Copyright (c) 2001-2013 Philip Lamb (PRL) phil@eden.net.nz. All rights reserved. +// Some portions of font loading code based on code by Jeff Molofee, 1999, http://nehe.gamedev.net/ +// +// Rev Date Who Changes +// + +// @@BEGIN_EDEN_LICENSE_HEADER@@ +// +// This file is part of The Eden Library. +// +// The Eden Library is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// The Eden Library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with The Eden Library. If not, see . +// +// As a special exception, the copyright holders of this library give you +// permission to link this library with independent modules to produce an +// executable, regardless of the license terms of these independent modules, and to +// copy and distribute the resulting executable under terms of your choice, +// provided that you also meet, for each linked independent module, the terms and +// conditions of the license of that module. An independent module is a module +// which is neither derived from nor based on this library. If you modify this +// library, you may extend this exception to your version of the library, but you +// are not obligated to do so. If you do not wish to do so, delete this exception +// statement from your version. +// +// @@END_EDEN_LICENSE_HEADER@@ + +// HeaderDoc documentation included. See http://developer.apple.com/darwin/projects/headerdoc/ + +/*! + @header EdenGLFont + @abstract Handle font-related operations under OpenGL. + @version 1.0.0 + @updated 2013-11-12 + @discussion + @copyright 2001-2013 Philip Lamb + */ + + +#ifndef __EdenGLFont_h__ +#define __EdenGLFont_h__ + +#ifdef __cplusplus +extern "C" { +#endif + +// ============================================================================ +// Includes. +// ============================================================================ +#ifndef __Eden_h__ +# include +#endif + +#include // EDEN_E_t + +// ============================================================================ +// Defines and types. +// ============================================================================ + +typedef struct _EDEN_GL_FONT_INFO_t EDEN_GL_FONT_INFO_t; + +extern EDEN_GL_FONT_INFO_t *const EDEN_GL_FONT_ID_Stroke_Roman; +extern EDEN_GL_FONT_INFO_t *const EDEN_GL_FONT_ID_Stroke_MonoRoman; +extern EDEN_GL_FONT_INFO_t *const EDEN_GL_FONT_ID_Bitmap16_Geneva; +extern EDEN_GL_FONT_INFO_t *const EDEN_GL_FONT_ID_Bitmap16_OCR_B_10; + +typedef enum { + H_OFFSET_VIEW_LEFT_EDGE_TO_TEXT_LEFT_EDGE, + H_OFFSET_TEXT_RIGHT_EDGE_TO_VIEW_RIGHT_EDGE, + H_OFFSET_VIEW_CENTER_TO_TEXT_CENTER +} H_OFFSET_TYPE; + +typedef enum { + V_OFFSET_VIEW_TEXT_TOP_TO_VIEW_TOP, + V_OFFSET_VIEW_BOTTOM_TO_TEXT_BASELINE, + V_OFFSET_VIEW_CENTER_TO_TEXT_CENTER +} V_OFFSET_TYPE; + +// ============================================================================ +// Functions. +// ============================================================================ + +/*! + @function + @abstract Initialise the font library. + @discussion + Must be called before any access to EdenGLFont*() functions. + @param contextsActiveCount Maximum number of OpenGL contexts. + @result TRUE if succcessful, FALSE in case of error. +*/ +EDEN_BOOL EdenGLFontInit(const int contextsActiveCount); + +/*! + @function + @abstract Finalise the font library. + @discussion + Should be called after no more EdenGLFont*() functions need be called. + @result TRUE if succcessful, FALSE in case of error. +*/ +EDEN_BOOL EdenGLFontFinal(void); + +/*! + @function + @abstract Create a texture font for later use. + @discussion + Creates font info required to use the font contained in the texture file + named at pathname. + + Each character in the texture occupies 16 pixels x 16 pixels. Its width + and height should be stretched to 16 even if this introduces perspective + distortion- this will guarantee the best onscreen resolution. + Each character from the font will be scaled to naturalWidth pixels wide, + naturalHeight pixels tall. + + Note that this function does not load the actual texture resources into + OpenGL and does not require a valid OpenGL context. OpenGL resource + loading is achieved by calling EdenGLFontLoadTextureFontForContext(). + @param fontName A short descriptive name for the font, suitable for presentation to a user, e.g. in a font menu. + @param naturalHeight The height in pixels at which each character, drawn unscaled, will occupy. + @param naturalWidth The width in pixels at which each character, drawn unscaled, will occupy. + @param pathname Pathname (absolute, or relative to current working directory) to font texture file. + @result Pointer to a EDEN_GL_FONT_INFO_t opaque structure. This pointer can be used with other + EdenGLFont functions just as if it was a built-in font. + @seealso EdenGLFontDeleteTextureFont EdenGLFontDeleteTextureFont + @seealso EdenGLFontLoadTextureFontForContext EdenGLFontLoadTextureFontForContext +*/ +EDEN_GL_FONT_INFO_t *EdenGLFontNewTextureFont(const char *fontName, const char *pathname, const float naturalHeight, const float naturalWidth); + +/*! + @function + @abstract Delete a previously created texture font. + @discussion (description) + @param fontInfo_p Pointer to a pointer to EDEN_GL_FONT_INFO_t opaque structure + previously returned from EdenGLFontLoadBitmapFont(). On return, the location + pointed to will be set to NULL. + + Note that this function does not unload the actual texture resources from + OpenGL and does not require a valid OpenGL context. OpenGL resource + loading is achieved by calling EdenGLFontLoadTextureFontForContext() PRIOR + to calling this function. + @seealso EdenGLFontNewTextureFont EdenGLFontNewTextureFont + @seealso EdenGLFontUnloadTextureFontForContext EdenGLFontUnloadTextureFontForContext +*/ +void EdenGLFontDeleteTextureFont(EDEN_GL_FONT_INFO_t **fontInfo_p); + +/*! + @function + @abstract Set the font to be used for subsequent draw calls. + @discussion + Drawing by default uses the font EDEN_GL_FONT_ID_Stroke_MonoRoman. + This function changes the font for subsequent drawing calls. + @param font Pointer to a EDEN_GL_FONT_INFO_t opaque structure, either for one + of the built-in fonts, or previously returned from EdenGLFontNewTextureFont() + @seealso EdenGLFontNewTextureFont EdenGLFontNewTextureFont + @seealso EdenGLFontLoadTextureFontForContext EdenGLFontLoadTextureFontForContext + */ +void EdenGLFontSetFont(EDEN_GL_FONT_INFO_t *font); + +/*! + @function + @abstract Get the font to be used for subsequent draw calls. + @discussion + @result Pointer to a EDEN_GL_FONT_INFO_t opaque structure, either for one + of the built-in fonts, or previously returned from EdenGLFontNewTextureFont() + */ +EDEN_GL_FONT_INFO_t * EdenGLFontGetFont(void); + +/*! + @function + @abstract Set the font size. + @discussion + @param points Font size in points. Default is 16 point. + */ +void EdenGLFontSetSize(const float points); + +/*! + @function + @abstract Get the currently set font size. + @discussion + @result Font size in points. Default is 16 point. + */ +float EdenGLFontGetSize(void); + +/*! + @function + @abstract Set character spacing (i.e. "kerning"). + @discussion + Character spacing is the spacing between the edges of adjacent characters. + @param spacing Spacing expressed as a percentage of the font size. Default is 0.0625f (i.e. 1/16). + */ +void EdenGLFontSetCharacterSpacing(const float spacing); + +/*! + @function + @abstract Get character spacing (i.e. "kerning"). + @discussion + Character spacing is the spacing between the edges of adjacent characters. + @result Spacing expressed as a percentage of the font size. Default is 0.0625f (i.e. 1/16). + */ +float EdenGLFontGetCharacterSpacing(void); + +/*! + @function + @abstract Set line spacing (i.e. "leading"). + @discussion + Default is to 1.125f (i.e. 9/8). + @param spacing Line spacing. + */ +void EdenGLFontSetLineSpacing(const float spacing); + +/*! + @function + @abstract Get line spacing (i.e. "leading"). + @discussion + Default is to 1.125f (i.e. 9/8). + @result Line spacing. + */ +float EdenGLFontGetLineSpacing(void); + +/*! + @function + @abstract Set word spacing (i.e. adjust width of the space character). + @discussion + Word spacing is the spacing between adjacent words. + + This adjustment applies only to non-monospaced fonts. + @param spacing Spacing expressed as a percentage of the normal width of the space character size. Default is 1.0. + */ +void EdenGLFontSetWordSpacing(const float spacing); + +/*! + @function + @abstract Get word spacing (i.e. adjust width of the space character). + @discussion + Word spacing is the spacing between adjacent words. + + This adjustment applies only to non-monospaced fonts. + @result pacing expressed as a percentage of the normal width of the space character size. Default is 1.0. + */ +float EdenGLFontGetWordSpacing(void); + +/*! + @function + @abstract Set set display resolution. + @discussion + The display resolition is used to calculate font heights in pixels. + Default is 72.0f, at which a 16-point font will occupy 16 pixels. + @param pixelsPerInch Display resolution, in pixels per inch. + */ +void EdenGLFontSetDisplayResolution(const float pixelsPerInch); // Pixels per inch. Used to calculate font heights in pixels. Default is 72.0f, at which a 16-point font will occupy 16 pixels. + +/*! + @function + @abstract Get previously set display resolution. + @discussion + The display resolition is used to calculate font heights in pixels. + Default is 72.0f, at which a 16-point font will occupy 16 pixels. + @result Previously set display resolution, in pixels per inch. + */ +float EdenGLFontGetDisplayResolution(void); // Pixels per inch. + +/*! + @function + @abstract Tell the font library about the view size. + @discussion + Normally, this will be called during the windowing system's reshape callback. + @param widthInPixels Width of the view, in pixels. + @param heightInPixels Height of the view, in pixels. +*/ +void EdenGLFontSetViewSize(const float widthInPixels, const float heightInPixels); + +/*! + @function + @abstract Gets the height (in pixels) of the currently selected font. + @discussion + Takes into account font size (in points) and display resolution (in pixels per inch). + @result Height in pixels. + */ +float EdenGLFontGetHeight(void); + +/*! + @function + @abstract Gets the width (in pixels) of a chracter of the currently selected font. + @discussion + Takes into account font size (in points) and display resolution (in pixels per inch). + Does not include any inter-character spacing. + @param c ASCII character code of the character. For texture fonts, the full 8 buts of c are considered. + @result Width in pixels. + */ +float EdenGLFontGetCharacterWidth(const unsigned char c); + +/*! + @function + @abstract Gets the width (in pixels) of a line of characters of the currently selected font. + @discussion + Takes into account font size (in points) and display resolution (in pixels per inch). + Includes inter-character spacing. + @param line A null-terminated (C string) of the characters to measure. + @result Width in pixels. + */ +float EdenGLFontGetLineWidth(const unsigned char *line); + +/*! + @function + @abstract Calculate the width of a block of text (i.e. the width of the widest line) in pixels. + @discussion + Includes inter-character spacing. + @param lines An array of C strings (i.e. an array of (char *)). Each item in the array points to a null-terminated C string. + @param lineCount Number of strings in array 'lines'. + @result Width in pixels. + */ +float EdenGLFontGetBlockWidth(const unsigned char **lines, const unsigned int lineCount); // Returns width in pixels, taking into account font, font size, display resolution, and character spacing. + +/*! + @function + @abstract Calculate the height of a block of text in pixels. + @discussion + Includes effects of line spacing greater than 1.0. + @param lines An array of C strings (i.e. an array of (char *)). Each item in the array points to a null-terminated C string. + @param lineCount Number of strings in array 'lines'. + @result Height in pixels. + */ +float EdenGLFontGetBlockHeight(const unsigned char **lines, const unsigned int lineCount); // Returns height in pixels, taking into account font, font size, display resolution, and line spacing. + +/*! + @function + @abstract + @discussion + Requires a valid OpenGL context at the time of the call. + Make sure EdenSurfacesInit() has been previously called with a valid number of contexts. + @param contextIndex + @param fontInfo + @result + */ +EDEN_BOOL EdenGLFontLoadTextureFontForContext(const int contextIndex, EDEN_GL_FONT_INFO_t *fontInfo); + +/*! + @function + @abstract + @discussion + Requires a valid OpenGL context at the time of the call. + @param contextIndex + @param fontInfo + @result + */ +EDEN_BOOL EdenGLFontUnloadTextureFontForContext(const int contextIndex, EDEN_GL_FONT_INFO_t *fontInfo); + +/*! + @function + @abstract Draw a single line of text into the framebuffer. + @discussion + Should be called once per frame, generally after all other drawing is complete. + Requires a valid OpenGL context at the time of the call. + + Drawing functions respect current projection and modelview matrices, + and depth mode and lighting/color settings, and these are unmodified on return. + Typically however, the aim is to draw window-aligned text, and this function + should be called with the projection matrix set to a 2D orthographic projection + in window coordinates and with the modelview matrix set to identity, i.e. +
+        glMatrixMode(GL_PROJECTION);
+        glOrtho(0.0, windowWidth, 0.0, windowHeight, -1.0, 1.0);
+        glMatrixMode(GL_MODELVIEW);
+        glLoadIdentity();
+        
+ + Texture font use modifies blend settings, texturing enable settings, + and vertex, texture coordinate pointers, and enabled client state of vertex, texture + and normal arrays. It also leaves texture matrix indeterminate on return. + @param contextIndex (description) + @param line null-terminated string of characters to draw. + @param hOffset Horizontal offset (in OpenGL coordinates) between the reference points + specified in hOffsetType. + + E.g. when hOffsetType = H_OFFSET_VIEW_LEFT_EDGE_TO_TEXT_LEFT_EDGE, passing 0.0f + will place the text against the left-hand edge of the window. + @param vOffset Vertical offset (in OpenGL coordinates) between the reference points + specified in vOffsetType. + + E.g. when vOffsetType = V_OFFSET_VIEW_BOTTOM_TO_TEXT_BASELINE, passing 0.0f + will place the text against the bottom edge of the window. + @param hOffsetType Specifies left, centered, or right alignment horizontal alignment. + @param vOffsetType Specifies top, centered, or bottom alignment vertical alignment. +*/ +void EdenGLFontDrawLine(const int contextIndex, const unsigned char *line, const float hOffset, const float vOffset, H_OFFSET_TYPE hOffsetType, V_OFFSET_TYPE vOffsetType); + +/*! + @function + @abstract Draw a block of multiple lines of text into the framebuffer. + @discussion + Should be called once per frame, generally after all other drawing is complete. + Requires a valid OpenGL context at the time of the call. + + Drawing functions respect current projection and modelview matrices, + and depth mode and lighting/color settings, and these are unmodified on return. + Typically however, the aim is to draw window-aligned text, and this function + should be called with the projection matrix set to a 2D orthographic projection + in window coordinates and with the modelview matrix set to identity, i.e. +
+        glMatrixMode(GL_PROJECTION);
+        glOrtho(0.0, windowWidth, 0.0, windowHeight, -1.0, 1.0);
+        glMatrixMode(GL_MODELVIEW);
+        glLoadIdentity();
+        
+ + Texture font use modifies blend settings, texturing enable settings, + and vertex, texture coordinate pointers, and enabled client state of vertex, texture + and normal arrays. It also leaves texture matrix indeterminate on return. + @param contextIndex (description) + @param lines Array of null-terminated string of characters to draw. + @param lineCount Number of strings in array 'lines'. + @param hOffset Horizontal offset (in OpenGL coordinates) between the reference points + specified in hOffsetType. + + E.g. when hOffsetType = H_OFFSET_VIEW_LEFT_EDGE_TO_TEXT_LEFT_EDGE, passing 0.0f + will place the text against the left-hand edge of the window. + @param vOffset Vertical offset (in OpenGL coordinates) between the reference points + specified in vOffsetType. + + E.g. when vOffsetType = V_OFFSET_VIEW_BOTTOM_TO_TEXT_BASELINE, passing 0.0f + will place the text against the bottom edge of the window. + @param hOffsetType Specifies left, centered, or right alignment horizontal alignment. + @param vOffsetType Specifies top, centered, or bottom alignment vertical alignment. +*/ +void EdenGLFontDrawBlock(const int contextIndex, const unsigned char **lines, const unsigned int lineCount, const float hOffset, const float vOffset, H_OFFSET_TYPE hOffsetType, V_OFFSET_TYPE vOffsetType); + +#ifdef __cplusplus +} +#endif +#endif // !__EdenGLFont_h__ diff --git a/libs/include/Eden/EdenMath.h b/libs/include/Eden/EdenMath.h new file mode 100755 index 0000000..527dad4 --- /dev/null +++ b/libs/include/Eden/EdenMath.h @@ -0,0 +1,577 @@ +/* + * EdenMath.h + * The Eden Library + * + * Copyright (c) 2001-2013 Philip Lamb (PRL) phil@eden.net.nz. All rights reserved. + * + * Rev Date Who Changes + * 1.0.0 2001-07-28 PRL Initial version. + * + */ + +// @@BEGIN_EDEN_LICENSE_HEADER@@ +// +// This file is part of The Eden Library. +// +// The Eden Library is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// The Eden Library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with The Eden Library. If not, see . +// +// As a special exception, the copyright holders of this library give you +// permission to link this library with independent modules to produce an +// executable, regardless of the license terms of these independent modules, and to +// copy and distribute the resulting executable under terms of your choice, +// provided that you also meet, for each linked independent module, the terms and +// conditions of the license of that module. An independent module is a module +// which is neither derived from nor based on this library. If you modify this +// library, you may extend this exception to your version of the library, but you +// are not obligated to do so. If you do not wish to do so, delete this exception +// statement from your version. +// +// @@END_EDEN_LICENSE_HEADER@@ + +/*! + @header EdenMath + @abstract Math utilities. + @discussion + EdenMath forms one part of the Eden library. + @copyright 2001-2013 Philip Lamb + */ + +#ifndef __EdenMath_h__ +#define __EdenMath_h__ + +// ============================================================================ +// Public includes +// ============================================================================ +#ifndef __Eden_h__ +# include +#endif + +#if defined(_WIN32) && !defined(_USE_MATH_DEFINES) +# define _USE_MATH_DEFINES // Make Win32 math.h define M_... constants. +#endif +#include + +// Fixes for missing floating point function declarations in Win32 ISO C. +#if defined(_WIN32) && defined(_MSC_VER) && !defined(__cplusplus) && _MSC_VER < 1600 +# define sinf(x) sin(x) +# define cosf(x) cos(x) +# define tanf(x) tan(x) +# define asinf(x) asin(x) +# define acosf(x) acos(x) +# define atanf(x) atan(x) +# define atan2f(y,x) atan2(y,x) +# define sinhf(x) sinh(x) +# define coshf(x) cosh(x) +# define tanhf(x) tanh(x) +# define expf(x) exp(x) +# define logf(x) log(x) +# define log10f(x) log10(x) +# define modff(x,ip) modf(x,ip) +# define powf(x,y) pow(x,y) +# define sqrtf(x) sqrtf(x) +# define ceilf(x) ceil(x) +# define fabsf(x) fabs(x) +# define floorf(x) floor(x) +# define fmodf(x,y) fmod(x,y) +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +// ============================================================================ +// Defines +// ============================================================================ + +#ifndef M_PI +/*! + @defined M_PI + @abstract Value of PI. + @discussion + Defined only if not already defined in math.h. +*/ +#define M_PI 3.141592653589793238462643 +#endif + +/*! + @defined PI + @abstract Value of PI. +*/ +#define PI M_PI + +/*! + @defined TWOPI + @abstract (description) + @discussion (description) +*/ +#define TWOPI (2*M_PI) + +/*! + @defined HALFPI + @abstract (description) + @discussion (description) +*/ +#define HALFPI (0.5*M_PI) + +/*! + @defined DTOR + @abstract Convert degrees to radians. + @discussion + Multiply an angle in degrees by this constant to + get the value of the angle in radians. +*/ +#define DTOR 0.0174532925 + +/*! + @defined RTOD + @abstract Convert radians to degrees. + @discussion + Multiply an angle in radians by this constant to + get the value of the angle in degrees. +*/ +#define RTOD 57.2957795 + +/*! + @defined MIN + @abstract Determine minimum of two values. +*/ +#ifndef MIN +#define MIN(x,y) (x < y ? x : y) +#endif + +/*! + @defined MAX + @abstract Determine maximum of two values. +*/ +#ifndef MAX +#define MAX(x,y) (x > y ? x : y) +#endif + +/*! + @defined CROSS + @abstract Vector cross-product in R3. + @discussion + 6 multiplies + 3 subtracts. + Vector cross product calculates a vector with direction + orthogonal to plane formed by the other two vectors, and length + equal to the area of the parallelogram formed by the other two + vectors. + Right hand rule for vector cross products: Point thumb of right + hand in direction of v1, fingers together in direction of v2, + then palm faces in the direction of dest. + */ +#define CROSS(dest,v1,v2) {dest[0] = v1[1]*v2[2] - v1[2]*v2[1]; dest[1] = v1[2]*v2[0] - v1[0]*v2[2]; dest[2] = v1[0]*v2[1] - v1[1]*v2[0];} + +/*! + @defined LENGTH + @abstract (description) + @discussion (description) +*/ +#define LENGTH(v) (sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2])) + +/*! + @defined DOT + @abstract Vector dot-product in R3. + @discussion + 3 multiplies + 2 adds. +*/ +#define DOT(v1,v2) ((v1[0]*v2[0]) + (v1[1]*v2[1]) + (v1[2]*v2[2])) + +/*! + @defined ADD + @abstract (description) + @discussion (description) +*/ +#define ADD(dest,v1,v2) {dest[0] = v1[0] + v2[0]; dest[1] = v1[1] + v2[1]; dest[2] = v1[2] + v2[2];} + +/*! + @defined SUB + @abstract (description) + @discussion (description) +*/ +#define SUB(dest,v1,v2) {dest[0] = v1[0] - v2[0]; dest[1] = v1[1] - v2[1]; dest[2] = v1[2] - v2[2];} + +/*! + @defined AVERAGE + @abstract (description) + @discussion (description) + */ +#define AVERAGE(dest,v1,v2) {dest[0] = (v1[0] + v2[0])*0.5; dest[1] = (v1[1] + v2[1])*0.5; dest[2] = (v1[2] + v2[2])*0.5;} + +/*! + @defined COPY + @abstract (description) + @discussion (description) + */ +#define COPY(dest, v) {dest[0] = v[0]; dest[1] = v[1]; dest[2] = v[2];} + +// ============================================================================ +// Public functions +// ============================================================================ + +/*! + @function + @abstract Normalise a vector. + @discussion + @param v Vector to normalise. +*/ +float EdenMathNormalise(float v[3]); + +/*! + @function + @abstract Normalise a vector. + @discussion + @param v Vector to normalise. +*/ +double EdenMathNormalised(double v[3]); + +/*! + @function + @abstract Calculates the Hessian normal (unit normal vector) to a plane. + @discussion + The plane is specified by three vectors which are points on the plane. + + The normal calculated is of unit length (i.e. it is the Hessian normal). + + See http://mathworld.wolfram.com/HessianNormalForm.html + @param n Vector representing Hessian normal (unit normal vector) to plane. + @param p Value of distance of plane from origin. + The sign of *p determines the side of the plane on which the origin is located. + If > 0, it is in the half-space determined by the direction of n, and if < 0, + it is in the other half-space. + @param p1 Vector describing point on the plane. + @param p2 Vector describing point on the plane. + @param p3 Vector describing point on the plane. +*/ +void EdenMathPointsToPlaneHessianNormal(float n[3], float *p, const float p1[3], const float p2[3], const float p3[3]); + +/*! + @function + @abstract Calculate the general form of a plane, given three points lying on the plane. + @discussion + The general form of a plane is the equation Ax + By + Cz + D = 0. + The plane is specified by three vectors which are points on the plane. + The vector ABC is normal to the plane (not unit normal though). + + See http://mathworld.wolfram.com/Plane.html + @param abc Vector describing the plane. + @param d Value describing the plane. + @param p1 Vector describing point on the plane. + @param p2 Vector describing point on the plane. + @param p3 Vector describing point on the plane. +*/ +void EdenMathPointsToPlane(float abc[3], float *d, const float p1[3], const float p2[3], const float p3[3]); + +/*! + @function + @abstract Calculate the point of intersection (if any) between a line and a plane. + @discussion + See http://mathworld.wolfram.com/Plane.html + @param intersection Pointer to an array of 3 floats which will be + filled out with the coordinates of the point of intersection. + @param u_out If non-null, the float pointed to will be filled out with + the value 'u', representing the point of intersection, relative to the + line segement between p1 and p2. I.e., when u is 0, the intersection is + at p1, and when u is 1 the intersection is at p2. Values of u < 0 or > 1 + indicate the intersection point is outside the line segment (but there IS + still an intersection point). NULL may be passed if you are not interested + in this value. + @param p1 A point lying on the line. + @param p2 Another point lying on the line. + @param abc The vector of values A, B, and C from the general definition of a plane + Ax + By + Cz + D = 0 (see EdenMathPointsToPlane()). + @param abc The value D from the general definition of a plane + Ax + By + Cz + D = 0 (see EdenMathPointsToPlane()). + @result FALSE if the normal to the plane is perpendicular to the line, or + if a required value was not specified, TRUE otherwise. +*/ +EDEN_BOOL EdenMathIntersectionLinePlane(float intersection[3], float *u_out, const float p1[3], const float p2[3], const float abc[3], const float d); + +/*! + @function + @abstract Caclulate signed distance from point to a plane. + @discussion + See http://mathworld.wolfram.com/Point-PlaneDistance.html + @param x0 Position of the point. + @param abc The vector of values A, B, and C from the general definition of a plane + Ax + By + Cz + D = 0 (see EdenMathPointsToPlane()). + @param abc The value D from the general definition of a plane + Ax + By + Cz + D = 0 (see EdenMathPointsToPlane()). + @result The distance from the point to the plane, which is positive if the + point lies on the same side of the plane as the normal to the plane, or + negative if it lies on the opposite side, or 0 if the parameters are invalid. + */ +float EdenMathCalcDistanceToPlane(const float x0[3], const float abc[3], const float d); + +/*! + @function + @abstract Creates a 3x3 identity matrix. + @discussion + @param mtx9 A 3x3 matrix that will receive the output. + */ +void EdenMathIdentityMatrix3by3(float mtx9[9]); + +/*! + @function + @abstract Multiplies 3x3 matrix B into 3x3 matrix A, placing result in C. + @discussion + A, B and C are in column-major form, which is standard for OpenGL + (wheras the usual mathematical matrix notation is row-major.) +*/ +void EdenMathMultMatrix3by3(float C[9], const float B[9], const float A[9]); + +/*! + @function + @abstract Invert a 3x3 matrix A, placing result in Ainv. + @discussion + A and Ainv are in column-major form, which is standard for OpenGL + (wheras the usual mathematical matrix notation is row-major.) +*/ +EDEN_BOOL EdenMathInvertMatrix3by3(float A[9], float Ainv[9]); + +/*! + @function + @abstract Creates a 4x4 identity matrix. + @discussion + @param mtx16 A 4x4 matrix that will receive the output. +*/ +void EdenMathIdentityMatrix(float mtx16[16]); + +/*! + @function + @abstract Multiplies 4x4 matrix B into 4x4 matrix A, placing result in C. + @discussion + A, B and C are in column-major form, which is standard for OpenGL + (wheras the usual mathematical matrix notation is row-major.) +*/ +void EdenMathMultMatrix(float C[16], const float B[16], const float A[16]); + +/*! + @function + @abstract Multiplies 4x4 matrix B into 4x4 matrix A, placing result in C. + @discussion + A, B and C are in column-major form, which is standard for OpenGL + (wheras the usual mathematical matrix notation is row-major.) + */ +void EdenMathMultMatrixd(double C[16], const double B[16], const double A[16]); + +/*! + @function + @abstract Compute inverse of 4x4 transformation matrix + @discussion Code contributed by Jacques Leroy jle\@star.be + @param m Input, 4x4 column-major matrix. + @param out Output, 4x4 column-major matrix. + @result Return TRUE for success, FALSE for failure (singular matrix) +*/ +EDEN_BOOL EdenMathInvertMatrix(float out[16], const float m[16]); + +/*! + @function + @abstract Compute inverse of 4x4 transformation matrix + @discussion Code contributed by Jacques Leroy jle\@star.be + @param m Input, 4x4 column-major matrix. + @param out Output, 4x4 column-major matrix. + @result Return TRUE for success, FALSE for failure (singular matrix) +*/ +EDEN_BOOL EdenMathInvertMatrixd(double out[16], const double m[16]); + +/*! + @function + @abstract Multiples 4x4 matrix A into column vector p, placing result in q. + @discussion + A is in column-major form, which is standard for OpenGL + (wheras the usual mathematical matrix notation is row-major.) +*/ +void EdenMathMultMatrixByVector(float q[4], const float A[16], const float p[4]); + +/*! + @function + @abstract Multiples 4x4 matrix A into column vector p, placing result in q. + @discussion + A is in column-major form, which is standard for OpenGL + (wheras the usual mathematical matrix notation is row-major.) +*/ +void EdenMathMultMatrixByVectord(double q[4], const double A[16], const double p[4]); + +/*! + @function + @abstract Creates a matrix which represents translation by a vector. + @discussion + @param mtx16 A 4x4 matrix that will receive the output in column major form. + @param x X component of the translation vector. + @param y Y component of the translation vector. + @param z Z component of the translation vector. +*/ +void EdenMathTranslationMatrix(float mtx16[16], const float x, const float y, const float z); + +/*! + @function + @abstract Translate a matrix by a vector. + @discussion + @param B A 4x4 matrix that will receive the output in column major form. + @param A A 4x4 matrix that will supply the input in column major form. + @param x X component of the translation vector. + @param y Y component of the translation vector. + @param z Z component of the translation vector. +*/ +void EdenMathTranslateMatrix(float B[16], const float A[16], const float x, const float y, const float z); + +/*! + @function + @abstract Creates a matrix which represents the general case of a rotation about an arbitrary axis. + @discussion + @param mtx16 A 4x4 matrix that will receive the output in column major form. + @param q The angle of rotation measured in a right-hand sense, in radians. + @param x X component of the normalised non-zero vector representing the axis of rotation. + @param y Y component of the normalised non-zero vector representing the axis of rotation. + @param z Z component of the normalised non-zero vector representing the axis of rotation. +*/ +void EdenMathRotationMatrix(float mtx16[16], const float q, const float x, const float y, const float z); + +/*! + @function + @abstract Rotate a matrix about an arbitrary axis. + @discussion (description) + @param B A 4x4 matrix that will receive the output in column major form. + @param A A 4x4 matrix that will supply the input in column major form. + @param q The angle of rotation measured in a right-hand sense, in radians. + @param x X component of the normalised non-zero vector representing the axis of rotation. + @param y Y component of the normalised non-zero vector representing the axis of rotation. + @param z Z component of the normalised non-zero vector representing the axis of rotation. + */ +void EdenMathRotateMatrix(float B[16], const float A[16], const float q, const float x, const float y, const float z); + +void EdenMathScalingMatrix(float mtx16[16], const float x, const float y, const float z); + +void EdenMathScaleMatrix(float B[16], const float A[16], const float x, const float y, const float z); + +/*! + @function + @abstract Creates a rotation matrix that rotates a vector called + "from" into another vector called "to". + @discussion + Author: Tomas Moller, 1999 + @param from Normalised non-zero vector. + @param to Normalised non-zero vector. + @param mtx9 A 3x3 matrix in column-major form which receives the result. +*/ +void EdenMathRotationMatrixFromTo(const float from[3], const float to[3], float mtx9[9]); + +/*! + @function + @abstract Rotate a point about an arbitrary axis. + @discussion + @param p2 Rotated point. + @param p1 Point to rotate. + @param q The angle of rotation measured in a right-hand sense, in radians. + @param a Normalised non-zero vector representing the axis of rotation. + */ +void EdenMathRotatePointAboutAxis(float p2[3], const float p1[3], const float q, const float a[3]); + +/*! + @function + @abstract Rotate a point about an arbitrary axis. + @discussion + @param p2 Rotated point. + @param p1 Point to rotate. + @param q The angle of rotation measured in a right-hand sense, in radians. + @param a Normalised non-zero vector representing the axis of rotation. +*/ +void EdenMathRotatePointAboutAxisd(double p2[3], const double p1[3], const double q, const double a[3]); + +#ifdef __ppc__ +/*! + @function + @abstract Fast calculation of square root. + @discussion + Uses a ppc-only instruction to get an estimate of the + square root, then performs 4 iterations of + Newton-Rhapson refinement to give better precision. + Note: these functions are not IEEE-754 compliant and do not calculate + the last bit correctly. For correct accuary, refer to libm on MacOS X. + Written by A. Sazegari, started on February 2002. + Copyright 2002 Apple Computer, Inc. All rights reserved. + @param arg Pointer to double-precision floating point number. + Will be replaced with the root of the number. + (*arg = (*arg)^0.5). + @availability Available on PowerPC CPUs only. +*/ +void fsqrt(double *arg); + +/*! + @function + @abstract Fast calculation of three square roots. + @discussion + Uses a ppc-only instruction to get an estimate of the + square root, then performs 4 iterations of + Newton-Rhapson refinement to give better precision. + Note: these functions are not IEEE-754 compliant and do not calculate + the last bit correctly. For correct accuary, refer to libm on MacOS X. + Written by A. Sazegari, started on February 2002. + Copyright 2002 Apple Computer, Inc. All rights reserved. + @param arg1 Pointer to double-precision floating point number. + Will be replaced with the root of the number. + @param arg2 Pointer to double-precision floating point number. + Will be replaced with the root of the number. + @param arg3 Pointer to double-precision floating point number. + Will be replaced with the root of the number. + @availability Available on PowerPC CPUs only. + */ +void fsqrt3(double *arg1, double *arg2, double *arg3); + +/*! + @function + @abstract Fast calculation of reciprocal square root. + @discussion + Uses a ppc-only instruction to get an estimate of the + reciprocal square root, then performs 4 iterations of + Newton-Rhapson refinement to give better precision. + Note: these functions are not IEEE-754 compliant and do not calculate + the last bit correctly. For correct accuary, refer to libm on MacOS X. + Written by A. Sazegari, started on February 2002. + Copyright 2002 Apple Computer, Inc. All rights reserved. + @param arg Pointer to double-precision floating point number. + Will be replaced with the reciprocal of the root of the number. + (*arg = (*arg)^-0.5). + @availability Available on PowerPC CPUs only. +*/ +void frsqrt(double *arg); + +/*! + @function + @abstract Fast calculation of three reciprocal square roots. + @discussion + Uses a ppc-only instruction to get an estimate of the + reciprocal square root, then performs 4 iterations of + Newton-Rhapson refinement to give better precision. + Note: these functions are not IEEE-754 compliant and do not calculate + the last bit correctly. For correct accuary, refer to libm on MacOS X. + Written by A. Sazegari, started on February 2002. + Copyright 2002 Apple Computer, Inc. All rights reserved. + @param arg1 Pointer to double-precision floating point number. + Will be replaced with the reciprocal of the root of the number. + @param arg2 Pointer to double-precision floating point number. + Will be replaced with the reciprocal of the root of the number. + @param arg3 Pointer to double-precision floating point number. + Will be replaced with the reciprocal of the root of the number. + @availability Available on PowerPC CPUs only. +*/ +void frsqrt3(double *arg1, double *arg2, double *arg3); +#endif // __ppc__ + +#ifdef __cplusplus +} +#endif + +#endif /* !__EdenMath_h__ */ diff --git a/libs/include/Eden/EdenMessage.h b/libs/include/Eden/EdenMessage.h new file mode 100755 index 0000000..9c1c225 --- /dev/null +++ b/libs/include/Eden/EdenMessage.h @@ -0,0 +1,283 @@ +// +// EdenMessage.h +// The Eden Library +// +// Copyright (c) 2001-2012 Philip Lamb (PRL) phil@eden.net.nz. All rights reserved. +// Font loading code based on code by Jeff Molofee, 1999, http://nehe.gamedev.net/ +// +// Rev Date Who Changes +// 1.0.0 2001-12-04 PRL Initial version for The SRMS simulator. +// 1.0.1 2005-09-28 PRL Added headerDoc. +// 1.1.0 2013-02-19 PRL Quick update for OpenGL ES. +// + +// @@BEGIN_EDEN_LICENSE_HEADER@@ +// +// This file is part of The Eden Library. +// +// The Eden Library is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// The Eden Library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with The Eden Library. If not, see . +// +// As a special exception, the copyright holders of this library give you +// permission to link this library with independent modules to produce an +// executable, regardless of the license terms of these independent modules, and to +// copy and distribute the resulting executable under terms of your choice, +// provided that you also meet, for each linked independent module, the terms and +// conditions of the license of that module. An independent module is a module +// which is neither derived from nor based on this library. If you modify this +// library, you may extend this exception to your version of the library, but you +// are not obligated to do so. If you do not wish to do so, delete this exception +// statement from your version. +// +// @@END_EDEN_LICENSE_HEADER@@ + +// HeaderDoc documentation included. See http://developer.apple.com/darwin/projects/headerdoc/ + +/*! + @header EdenMessage + @abstract Send messages and show text-input dialog boxes on the screen. + @version 1.0.0 + @updated 2013-11-12 + @discussion + @copyright 2001-2013 Philip Lamb + */ + +#ifndef __EdenMessage_h__ +#define __EdenMessage_h__ + +#ifdef __cplusplus +extern "C" { +#endif + +// ============================================================================ +// Includes. +// ============================================================================ +#ifndef __Eden_h__ +# include +#endif + +#include // EDEN_E_t + +// ============================================================================ +// Defines and types. +// ============================================================================ + +// ============================================================================ +// Global variables. +// ============================================================================ + +// When set to TRUE, signals that EdenMessageDraw() should be called each drawing frame. +extern EDEN_BOOL gEdenMessageDrawRequired; + +// When set to TRUE, signals that keycodes should be sent to EdenMessageInputKeyboard() +extern EDEN_BOOL gEdenMessageKeyboardRequired; + +// ============================================================================ +// Public functions +// ============================================================================ + +/*! + @function + @abstract Initialise the message library. + @discussion + Must be called before any access to EdenMessage*() functions. + @param contextsActiveCount Maximum number of OpenGL contexts. + @result TRUE if succcessful, FALSE in case of error. +*/ +EDEN_BOOL EdenMessageInit(const int contextsActiveCount); + +/*! + @function + @abstract Finalise the message library. + @discussion (description) + Should be called after no more EdenMessage*() functions need be called. + @result TRUE if succcessful, FALSE in case of error. +*/ +EDEN_BOOL EdenMessageFinal(void); + +/*! + @function + @abstract Prepare a message for drawing on the screen. + @discussion + Chops up a message of not more than MESSAGE_LENGTH_MAX characters into lines to + fit inside a shaded box. The maximum dimensions of the box are 50% of the + screen width and 80% of the screen height. The box is padded left and right 4 + character widths and top and bottom one line width. The width of the screen + must allow at least 20 characters to fit on each line. This routine only chops + up the lines. The actual drawing into the framebuffer should done with calls to + EdenMessageDraw(). + This function should only be used in single-threaded applications. In + multi-threaded applications (in which a separate, blockable thread is + available to handle this kind of messaging), the function EdenMessage() should + be used instead, and it will automatically control showing and hiding of + the text. + @param msg The text to place into the message box. + @result EDEN_E_NONE in case of no error, or an error code. +*/ +EDEN_E_t EdenMessageShow(const unsigned char *msg); + +/*! + @function + @abstract Remove a message from drawing on the screen. + @discussion + Removes a message previously shown with EdenMessageShow() from the screen. + This function should only be used in single-threaded applications. In + multi-threaded applications (in which a separate, blockable thread is + available to handle this kind of messaging), the function EdenMessage() should + be used instead, and it will automatically control showing and hiding of + the text. + @result EDEN_E_NONE in case of no error, or an error code. +*/ +EDEN_E_t EdenMessageHide(void); + +/*! + @function + @abstract Prepare a text-input dialog for user interaction. + @discussion + Prepares a prompt message for drawing on the screen, and then place + a cursor at the end of the message, and collects input keystrokes + from the user until the user presses return. + @param prompt The message to show above and to the left of the user's input. + @param minLength Minimum number of characters the user must enter before the routine will + allow the input to be terminated (with the return key.) The return is NOT + included in this number. + @param maxLength Maximum number of characters the user may enter. + @result EDEN_E_NONE in case of no error, or an error code. +*/ +EDEN_E_t EdenMessageInputShow(const unsigned char *prompt, const unsigned int minLength, const unsigned int maxLength, int intOnly, int fpOnly, int alphaOnly); + +/*! + @function + @abstract Remove a text-input dialog for user interaction. + @discussion + Removes a message dialog previously shown with EdenMessageInputShow() from the screen. + This function should only be used in single-threaded applications. In + multi-threaded applications (in which a separate, blockable thread is + available to handle this kind of messaging), the function EdenMessageInput() should + be used instead, and it will automatically control showing and hiding of + the text. + @result EDEN_E_NONE in case of no error, or an error code. +*/ +EDEN_E_t EdenMessageInputHide(void); + +EDEN_BOOL EdenMessageInputIsComplete(void); + +/*! + @function + @abstract Prepare a message for drawing on the screen. + @discussion + Prepares a message for drawing on the screen (by calling through + to EdenMessageShow()), and waits the indicated number of seconds + before hiding the message (by calling through to EdenMessageHide()) + The routine blocks during the wait. It is thus designed to be + used in a multi-threaded application, where other operations, + including the actual drawing, occur in a separate thread. + Applications requiring that the routine routine immediately, such + as single-threaded applications, should not call this routine, but + should manually control the showing and hiding. + @param msg (description) + @param secs How many seconds to show the message for. + @result EDEN_E_NONE in case of no error, or an error code. +*/ +EDEN_E_t EdenMessage(unsigned char *msg, const unsigned int secs); + +/*! + @function + @abstract Prepare a text-input dialog for user interaction. + @discussion + Prepares a prompt message for drawing on the screen, and then place + a cursor at the end of the message, and collects input keystrokes + from the user until the user presses return. + The routine blocks during the wait. It is thus designed to be + used in a multi-threaded application, where other operations, + including the actual drawing and keystroke collection, occur in a + separate thread. + Applications requiring that the routine routine immediately, such + as single-threaded applications, should not call this routine, but + should manually control the showing and hiding. + @param prompt The message to show above and to the left of the user's input. + @param minLength Minimum number of characters the user must enter before the routine will + allow the input to be terminated (with the return key.) The return is NOT + included in this number. + @param maxLength Maximum number of characters the user may enter. + @result EDEN_E_NONE in case of no error, or an error code. +*/ +EDEN_E_t EdenMessageInput(const unsigned char *prompt, const unsigned int minLength, const unsigned int maxLength, int intOnly, int fpOnly, int alphaOnly); + +/*! + @function + @abstract Get the result of an input operation + @discussion + Gets the result of the input operation via a string copy. + @result + A string containing the content. If the user has cancelled input + with the ESC key, NULL will be returned. If the user has not entered + any input, this will point to a null string. + + Note that free() must be called on the result of this function + when the caller has finished with it, to prevent leaking of the result. + */ +unsigned char *EdenMessageInputGetInput(void); + +/*! + @function + @abstract Set the view size to use in calculations when aligning message box. + @discussion + The positioning of the message box is calculated each frame using + the values supplied here. + @param width Viewport width in pixels. + @param height Viewport height in pixels. + */ +void EdenMessageSetViewSize(const float width, const float height); + +void EdenMessageSetBoxParams(const float width, const float padding); + +/*! + @function + @abstract Draw previously-prepared text in a box onto the framebuffer. + @discussion + Draws a shaded white-outlined box box onto the screen and draws + lines of text previously prepared with EdenMessageShow() into it. + When the variable gEdenMessageDrawRequired is set, this function + should be called once per frame, generally after all other + drawing is complete. + + This function is typically called with the projection set to + a 2D orthographic projection. + + This drawing call is required in order to see the output of the + message routines, in both single- and multi-threaded applications. + @param contextIndex (description) +*/ +void EdenMessageDraw(const int contextIndex); + +/*! + @function + @abstract Pass user keystrokes to message library for use in dialogs. + @discussion + This function processes keystrokes for a message dialog. + When the global variable gEdenMessageKeyboardRequired is set, any keystrokes collected + from the user by the calling program should be passed to this function, + which will absorb the keystroke and update the on-screen dialog box appropriately. + This processing call is required in order to capture the user's input for the + message routines, in both single- and multi-threaded applications. + @param keyAsciiCode The ASCII-encoded keystroke. + @result Returns TRUE if the keystroke was processed successfully, FALSE in case of error. +*/ +EDEN_BOOL EdenMessageInputKeyboard(const unsigned char keyAsciiCode); + +#ifdef __cplusplus +} +#endif + +#endif /* !__EdenMessage_h__ */ diff --git a/libs/include/Eden/EdenSound.h b/libs/include/Eden/EdenSound.h new file mode 100755 index 0000000..2cc289a --- /dev/null +++ b/libs/include/Eden/EdenSound.h @@ -0,0 +1,70 @@ +// +// EdenSound.h +// The Eden Library +// +// Copyright (c) 2012-2013 Philip Lamb (PRL) phil@eden.net.nz. All rights reserved. +// +// Rev Date Who Changes +// 1.0 2012-12-23 PRL Initial version +// + +// @@BEGIN_EDEN_LICENSE_HEADER@@ +// +// This file is part of The Eden Library. +// +// The Eden Library is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// The Eden Library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with The Eden Library. If not, see . +// +// As a special exception, the copyright holders of this library give you +// permission to link this library with independent modules to produce an +// executable, regardless of the license terms of these independent modules, and to +// copy and distribute the resulting executable under terms of your choice, +// provided that you also meet, for each linked independent module, the terms and +// conditions of the license of that module. An independent module is a module +// which is neither derived from nor based on this library. If you modify this +// library, you may extend this exception to your version of the library, but you +// are not obligated to do so. If you do not wish to do so, delete this exception +// statement from your version. +// +// @@END_EDEN_LICENSE_HEADER@@ + +#ifndef __EdenSound_h__ +#define __EdenSound_h__ + +#ifndef __Eden_h__ +# include +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct _EdenSound EdenSound_t; + +EdenSound_t *EdenSoundLoad(const char *pathname); +void EdenSoundUnload(EdenSound_t **sound_p); +void EdenSoundPlay(EdenSound_t *sound); +EDEN_BOOL EdenSoundIsPlaying(EdenSound_t *sound); +void EdenSoundPause(EdenSound_t *sound); +EDEN_BOOL EdenSoundIsPaused(EdenSound_t *sound); +void EdenSoundSetLooping(EdenSound_t *sound, EDEN_BOOL looping); +EDEN_BOOL EdenSoundIsLooping(EdenSound_t *sound); +void EdenSoundStop(EdenSound_t *sound); +EDEN_BOOL EdenSoundIsStopped(EdenSound_t *sound); +void EdenSoundRewind(EdenSound_t *sound); +float EdenSoundGetPlaybackTimeInSecs(EdenSound_t *sound); + +#ifdef __cplusplus +} +#endif //__cplusplus +#endif // !__EdenSound_h__ diff --git a/libs/include/Eden/EdenSurfaces.h b/libs/include/Eden/EdenSurfaces.h new file mode 100755 index 0000000..bafd0ac --- /dev/null +++ b/libs/include/Eden/EdenSurfaces.h @@ -0,0 +1,317 @@ +/* + * EdenSurfaces.h + * The Eden Library + * + * Copyright (c) 2001-2013 Philip Lamb (PRL) phil@eden.net.nz. All rights reserved. + * + * Rev Date Who Changes + * 1.0.0 2001-11-11 PRL Initial version for The SRMS simulator. + * 1.1.0 2008-07-18 PRL Repurposed for OpenGL ES. + * 1.2.0 2010-09-22 PRL Remove redundant static material handling. + */ + +// @@BEGIN_EDEN_LICENSE_HEADER@@ +// +// This file is part of The Eden Library. +// +// The Eden Library is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// The Eden Library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with The Eden Library. If not, see . +// +// As a special exception, the copyright holders of this library give you +// permission to link this library with independent modules to produce an +// executable, regardless of the license terms of these independent modules, and to +// copy and distribute the resulting executable under terms of your choice, +// provided that you also meet, for each linked independent module, the terms and +// conditions of the license of that module. An independent module is a module +// which is neither derived from nor based on this library. If you modify this +// library, you may extend this exception to your version of the library, but you +// are not obligated to do so. If you do not wish to do so, delete this exception +// statement from your version. +// +// @@END_EDEN_LICENSE_HEADER@@ + +/*! + @header EdenSurfaces + @abstract Texture loading, selection, and drawing. + @discussion + EdenSurfaces forms one part of the Eden library. + @copyright 2001-2013 Philip Lamb + */ + +#ifndef __EdenSurfaces_h__ +#define __EdenSurfaces_h__ + +#ifdef __cplusplus +extern "C" { +#endif + +/* ============================================================================ * + * Includes + * ============================================================================ */ +#ifndef __Eden_h__ +# include +#endif + + +#if defined(EDEN_OPENGL3) +# ifdef EDEN_MACOSX +# include +# else +# include +# endif +#elif defined(EDEN_OPENGLES) +# if defined ANDROID +# include +# include +# else +# include +# include +# endif +#else +# ifdef EDEN_MACOSX +# include +# else +# include +# endif +#endif + + +/* ============================================================================ * + * defines + * ============================================================================ */ +#if 0 +// Symbolic names for faces of objects to texture. +#define TEXTURE_FACE_TOP_BIT 0x01 +#define TEXTURE_FACE_RIGHT_BIT 0x02 +#define TEXTURE_FACE_BACK_BIT 0x04 +#define TEXTURE_FACE_LEFT_BIT 0x08 +#define TEXTURE_FACE_FRONT_BIT 0x10 +#define TEXTURE_FACE_BOTTOM_BIT 0x20 +#endif + +/*! + @typedef + @abstract Scaling mode to use when drawing a texture on a quad. + @constant STRETCH Match texture size to quad, stretching as necessary. + @constant FILL Scale the texture so that its smallest side exactly fills + the largest side of the quad. If the texture and the quad are not the same + ratio, the texture will be cropped. + @constant FIT Scale the texture so that it's largest side exactly fits in + the smallest side of the quad. If the texture and the quad are not the same + ratio, the texture will be surrounded by background texture (letterbox/pillarbox). + @constant UNITY Draw the texture with one pixel per one OpenGL unit, without stretching. + If the texture is larger than the quad, it will be cropped. If it is smaller, it will + be surrounded by background texture. + */ +typedef enum { + STRETCH, + FILL, + FIT, + UNITY +} EDEN_TEXTURE_SCALING_MODE; + +/*! + @typedef + @abstract How to align the texture content when drawing a texture on a quad. + */ +typedef enum { + CENTRE, + TOP_LEFT, + TOP_RIGHT, + BOTTOM_LEFT, + BOTTOM_RIGHT, + LEFT, + TOP, + RIGHT, + BOTTOM +} EDEN_TEXTURE_ALIGNMENT_MODE; + +/* ============================================================================ * +* Public types +* ============================================================================ */ + +typedef unsigned int TEXTURE_INDEX_t; + +/*! + @typedef + @field pathname Pathname of the texture file to load. + @field mipmaps TRUE if mipmaps should be generated (e.g. if the texture will + be drawn scaled to sizes smaller than unity), FALSE otherwise. + @field internalformat OpenGL internal texture format to use. + E.g. this allows a single-channel texture to be loaded as GL_ALPHA rather + than GL_LUMINANCE. Typically GL_RGB or GL_RGBA. + @field min_filter + @field mag_filter + @field wrap_s + @field wrap_t + @field priority + @field env_mode +*/ +typedef struct { + const char *pathname; + GLboolean mipmaps; + GLint internalformat; + GLint min_filter; + GLint mag_filter; + GLint wrap_s; + GLint wrap_t; + GLclampf priority; + GLint env_mode; + //GLfloat env_color[4]; +} TEXTURE_INFO_t; + +/* ============================================================================ * + * Public functions + * ============================================================================ */ + +/*! + @function + @abstract Initialise the EdenSurfaces library. + @discussion + This function must be called prior to any other EdenSurfaces*() functions being called. + + Does NOT require that a valid OpenGL context be available. + @param contextsActiveCount Maximum number of OpenGL contexts that will be in use. Typically 1. + @param textureIndicesMax Maximum number of textures that can be loaded via calls to EdenSurfacesTextureLoad. + @result TRUE if the function succeeded, FALSE otherwise. + */ +EDEN_BOOL EdenSurfacesInit(const int contextsActiveCount, const int textureIndicesMax); + +/*! + @function + @abstract Loads textures into OpenGL texture objects. + @discussion + Loads numTextures textures into OpenGL texture objects, for the specified OpenGL + context (the first context has a contextIndex of 0). + @param contextIndex The index of the OpenGL context into which this texture is being loaded. + (The context must already be active.) Normally 0 if using only one context. + May not be more than contextsActiveCount-1 (as passed to EdenSurfacesInit). + @param numTextures The number of textures being loaded. + @param textureInfo An array (of length numTextures) holding details of each texture + being loaded. + + On OpenGL ES devices with limited non-power-of-two (NPOT) texture support, + the NPOT support will only be available if {mipmaps = FALSE, min_filter/mag_filter + = GL_NEAREST/GL_LINEAR, wrap_s/wrap_t = GL_CLAMP_TO_EDGE}. + @param textureIndices + After loading, the array textureIndices[] holds the index + numbers assigned to each texture. These index numbers may then be used in calls to + EdenSurfacesTextureSet() and EdenSurfacesTextureUnload(). (These indices are of type + TEXTURE_INDEX_t, an unsigned int, greater than or equal to 1, and are only valid + per-OpenGL context.) + In the event of a loading error, the index value of any textures not loaded will + be equal to 0. + @param hasAlpha_out If the calling routine wishes to know if the returned texture contains + an alpha channel it should supply a pointer to a char in parameter hasAlpha_out, and on + return, this char will equal 0 if no alpha channel is present, or 1 otherwise. If this + information is not needed, set hasAlpha_out to NULL + @result TRUE if all textures were loaded correctly, FALSE if one or more were not. + */ +EDEN_BOOL EdenSurfacesTextureLoad(const int contextIndex, const int numTextures, const TEXTURE_INFO_t *textureInfo, TEXTURE_INDEX_t *textureIndices, char *hasAlpha_out); + +EDEN_BOOL EdenSurfacesTextureLoad2(const int contextIndex, const int numTextures, const TEXTURE_INFO_t *textureInfo, TEXTURE_INDEX_t *textureIndices, char *hasAlpha_out, const EDEN_BOOL flipH, const EDEN_BOOL flipV); + +/*! + @function + @abstract Binds the OpenGL texture. + @discussion + @param textureIndex The texture bound is specified by parameter textureIndex. + This index is only valid if the current OpenGL context is contextIndex, and the index + was returned by EdenSurfacesTextureLoad() with the same OpenGL context. + @param contextIndex The index of the OpenGL context with which this texture is being bound. + (The context must already be active.) Normally 0 if using only one context. + May not be more than contextsActiveCount-1 (as passed to EdenSurfacesInit). + */ +void EdenSurfacesTextureSet(const int contextIndex, TEXTURE_INDEX_t textureIndex); + +/*! + @function + @abstract Unloads textures and frees OpenGL texture objects. + @discussion + Unloads numTextures textures from OpenGL texture objects, for the specified OpenGL context. + @param numTextures The number of textures being unloaded. + @param textureIndices After unloading, the corresponding index in textureIndices for each + record in textureInfo[] is set to 0. + @param contextIndex The index of the OpenGL context from this texture is being unloaded. + (The context must already be active.) Normally 0 if using only one context. + May not be more than contextsActiveCount-1 (as passed to EdenSurfacesInit). + @result TRUE if the function succeeded, FALSE otherwise. + */ +EDEN_BOOL EdenSurfacesTextureUnload(const int contextIndex, const int numTextures, TEXTURE_INDEX_t *textureIndices); + +/*! + @function + @abstract Finalise the EdenSurfaces library. + @discussion + This function should be called once no more calls to any other EdenSurfaces*() + functions are required, to free up allocated memory. + Does NOT require that a valid OpenGL context be available. + @result TRUE if the function succeeded, FALSE otherwise. + */ +EDEN_BOOL EdenSurfacesFinal(void); + +/*! + @function + @abstract Draw a texture on a quad using OpenGL. + @discussion + Draws the texture pointed to by index on a surface of size (width, height) OpenGL units, + with the lower-left corner of the surface at the origin, and the surface lying in the X-Y plane. + + To draw at a different position and/or orientation precede with glTranslate/glRotate calls. + @param width Width, in OpenGL units, of the quad on which to draw. + @param height Height, in OpenGL units, of the quad on which to draw. + @param scaleMode determines how the scale factor between pixels in the source + image and OpenGL units on the surface. + @param alignMode determines the placement of the image inside the surface. + @result TRUE if the function succeeded, FALSE otherwise. + */ +EDEN_BOOL EdenSurfacesDraw(const int contextIndex, const TEXTURE_INDEX_t textureIndex, const int width, const int height, const EDEN_TEXTURE_SCALING_MODE scaleMode, const EDEN_TEXTURE_ALIGNMENT_MODE alignMode); + +/*! + @function + @abstract Check for the availability of an OpenGL extension. + @discussion + Provides the same functionality as the gluCheckExtension() function, + since some platforms don't have GLU version 1.3 or later. + @param extName Name of the extension, e.g. "GL_EXT_texture". + @param extString The OpenGL extensions string, as returned by glGetString(GL_EXTENSIONS); + @result TRUE, if the extension is found, FALSE otherwise. +*/ +GLboolean EdenGluCheckExtension(const GLubyte* extName, const GLubyte *extString); + +/*! + @function + @abstract Checks for the presence of an OpenGL capability by version or extension. + @discussion + Checks for the presence of an OpenGL capability by version or extension. + The test returns true if EITHER the OpenGL driver's OpenGL implementation + version meets or exceeds a minimum value (passed in in minVersion) OR + if an OpenGL extension identifier passed in as a character string + is non-NULL, and is found in the current driver's list of supported extensions. + @param minVersion + A binary-coded decimal (i.e. version 1.0 is represented as 0x0100) version number. + If minVersion is zero, (i.e. there is no version of OpenGL with this extension in core) + the version test will always fail, and the result will only be true if the extension + string test passes. + @param extension A string with an extension name to search the drivers extensions + string for. E.g. "GL_EXT_texture". If NULL, the extension name test will always fail, + and the result will only be true if the version number test passes. + @result TRUE If either of the tests passes, or FALSE if both fail. +*/ +int EdenGLCapabilityCheck(const unsigned short minVersion, const unsigned char *extension); + +#ifdef __cplusplus +} +#endif + +#endif /* !__EdenSurfaces_h__ */ diff --git a/libs/include/Eden/EdenTime.h b/libs/include/Eden/EdenTime.h new file mode 100755 index 0000000..9e991c4 --- /dev/null +++ b/libs/include/Eden/EdenTime.h @@ -0,0 +1,156 @@ +// +// EdenTime.h +// +// Copyright (c) 2001-2012 Philip Lamb (PRL) phil@eden.net.nz. All rights reserved. +// +// Rev Date Who Changes +// 1.0.0 2001-11-26 PRL Initial version for The SRMS simulator. +// 1.0.1 2005-09-07 PRL Misc changes till now. Added headerdoc. +// + +// @@BEGIN_EDEN_LICENSE_HEADER@@ +// +// This file is part of The Eden Library. +// +// The Eden Library is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// The Eden Library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with The Eden Library. If not, see . +// +// As a special exception, the copyright holders of this library give you +// permission to link this library with independent modules to produce an +// executable, regardless of the license terms of these independent modules, and to +// copy and distribute the resulting executable under terms of your choice, +// provided that you also meet, for each linked independent module, the terms and +// conditions of the license of that module. An independent module is a module +// which is neither derived from nor based on this library. If you modify this +// library, you may extend this exception to your version of the library, but you +// are not obligated to do so. If you do not wish to do so, delete this exception +// statement from your version. +// +// @@END_EDEN_LICENSE_HEADER@@ + +// HeaderDoc documentation included. See http://developer.apple.com/darwin/projects/headerdoc/ + +/*! + @header EdenTime + @abstract Time utility routines. + @version 1.0.1 + @updated 2005-09-07 + @discussion + EdenTime forms one part of the Eden library, and it makes + use of other parts of the library for its internal operations. + @related EdenLog + @copyright 2005 Philip Lamb + */ +#ifndef __EdenTime_h__ +#define __EdenTime_h__ + +#ifdef __cplusplus +extern "C" { +#endif + +// ============================================================================ +// Public types, defines and includes +// ============================================================================ + +#ifndef __Eden_h__ +# include +#endif + +#if defined(EDEN_UNIX) +# include // struct timespec, struct timeval, gettimeofday() +#else +# ifndef PTHREAD_H // pthreads_win32 also defines struct timespec. +struct timespec { + long tv_sec; + long tv_nsec; +}; +# endif // !PTHREAD_H +#endif + +// ============================================================================ +// Public functions +// ============================================================================ + +/*! + @function + @abstract Get current time in fractional seconds. + @discussion + Supported via system calls on Unix, WIN32, and MacOS. + Other systems which support GLUT are also supported (with lesser accuracy.) + @result The time. +*/ +double EdenTimeInSeconds(void); + +/*! + @function + @abstract Get current time, add microseconds offset to it, and return as a timespec. + @discussion + Gets an absolute time in seconds and nanoseconds elapsed since + epoch (Jan 1, 1970), add parameter 'microseconds' microseconds + and return in a timespec structure, suitable e.g. for passing to + functions such as pthread_cond_timedwait(). + Supported via system calls on Unix, and WIN32. + @param result Timespec structure which will be filled with the result. + @param microseconds How many microseconds in the future the timespec will be. + +*/ +void EdenTimeAbsolutePlusOffset(struct timespec *result, const long microseconds); + +/*! + @function + @abstract Generate human-readable string representing time. + @discussion (description) + Put character string with a human-readable representation of the + time passed in parameter 'seconds' into 's'. + On Unix, Windows and other platforms supporting the ctime(); + system function call, the string returned will be in ctime + format, i.e. of the format "Thu Nov 24 18:22:48 1986", which + is a string with constant field widths, and taking into account + the current time zone and daylight savings time. + @param seconds The time value, should be the number of seconds + elapsed since epoch (1st Jan 1970), such as generated by + EdenTimeInSeconds(); + @param s Pointer to a character buffer, no smaller than 25 + bytes in size, which will be filled with the string. + @result Pointer to the passed in buffer. +*/ +char *EdenTimeInSecondsToText(const double seconds, char s[25]); + +#ifndef _WINRT +/*! + @function + @abstract Sleep the specified number of microseconds. + @discussion + Uses an OS-dependent routine. On Unix platforms, usleep; On Windows + platforms, Sleep; on Mac OS (Classic) platform, Delay. + @param microseconds How many microseconds (millionths of a second) to sleep. + @availability Not available on Windows Runtime (WinRT). +*/ +void EdenTime_usleep(const unsigned int microseconds); +#endif // !_WINRT + +/*! + @function + @abstract Sleep the specified number of seconds. + @discussion + Uses an OS-dependent routine. On Unix platforms, sleep; On Windows + platforms, Sleep; on Mac OS (Classic) platform, Delay. + @param seconds How many seconds to sleep. +*/ +void EdenTime_sleep(const unsigned int seconds); + +#ifdef __cplusplus +} +#endif + +#endif /* !__EdenTime_h__ */ diff --git a/libs/include/Eden/EdenUtil.h b/libs/include/Eden/EdenUtil.h new file mode 100755 index 0000000..7de9762 --- /dev/null +++ b/libs/include/Eden/EdenUtil.h @@ -0,0 +1,184 @@ +// +// EdenUtil.h +// The Eden Library +// +// Various OS-related bits and pieces. +// +// Copyright (c) 2004-2013 Philip Lamb (PRL) phil@eden.net.nz. All rights reserved. +// +// Rev Date Who Changes +// 1.0.0 2004-04-23 PRL Added functions for checking keyboard. +// + +// @@BEGIN_EDEN_LICENSE_HEADER@@ +// +// This file is part of The Eden Library. +// +// The Eden Library is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// The Eden Library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with The Eden Library. If not, see . +// +// As a special exception, the copyright holders of this library give you +// permission to link this library with independent modules to produce an +// executable, regardless of the license terms of these independent modules, and to +// copy and distribute the resulting executable under terms of your choice, +// provided that you also meet, for each linked independent module, the terms and +// conditions of the license of that module. An independent module is a module +// which is neither derived from nor based on this library. If you modify this +// library, you may extend this exception to your version of the library, but you +// are not obligated to do so. If you do not wish to do so, delete this exception +// statement from your version. +// +// @@END_EDEN_LICENSE_HEADER@@ + +/*! + + @header EdenUtil + @abstract Miscellaneous utility routines. + @discussion + EdenUtil forms one part of the Eden library. + @copyright 2004-2013 Philip Lamb + */ + +#ifndef __EdenUtil_h__ +#define __EdenUtil_h__ + +#ifdef __cplusplus +extern "C" { +#endif + +// ============================================================================ +// Public includes +// ============================================================================ + +#ifndef __Eden_h__ +# include +#endif + + +// ============================================================================ +// Public defines and types +// ============================================================================ + +// ============================================================================ +// Global variables +// ============================================================================ + +// ============================================================================ +// Public functions +// ============================================================================ + +/*! + @function + @abstract Do any required setup so that we can check for single keypresses. + @discussion + @result (description) +*/ +EDEN_BOOL EdenKeyboardHitSetup(void); + +/*! + @function + @abstract Check to see if the user has pressed a key on the keyboard. + @discussion + @result (description) +*/ +EDEN_BOOL EdenKeyboardHit(void); + +/*! + @function + @abstract Do any required cleanup from our use of single keypress detection. + @discussion + @result (description) +*/ +EDEN_BOOL EdenKeyboardHitCleanup(void); + +/*! + @function + @abstract Get file name from a path. + @discussion + Given a full or partial pathname passed in string path, + returns a pointer to the first char of the filename + portion of path. + @param path Full or partial pathname. + @result A pointer to the first char of the filename + portion of path. +*/ +char *EdenGetFileNameFromPath(const char *path); + +/*! + @function + @abstract Get file extension from a path. + @discussion + Given a full or partial pathname passed in string path, + returns a string with the extension portion of path, + i.e. the text after the rightmost '.' character, if any. + If the filename contains no '.', NULL is returned. + @param path Full or partial pathname. + @param convertToLowercase If convertToLowercase is TRUE, uppercase + ASCII characters in the extension will be converted to lowercase. + @result A string with the extension portion of path. + NB: The returned string must be freed by the caller. +*/ +char *EdenGetFileExtensionFromPath(const char *path, int convertToLowercase); + +/*! + @function + @abstract Get directory name from a path. + @discussion + Given a full or partial pathname passed in string path, + returns a string with the directory name portion of path. + The string is not terminated by the directory separator. + @param path Full or partial pathname. + @result A string with the directory name portion of path. + NB: The returned string must be freed by the caller. +*/ +char *EdenGetDirectoryNameFromPath(const char *path); + +/*! + @function + @abstract Return the path to the current executable + @discussion + Return the path to the current executable, where such a + linkage between path and execution exists and is readable. + @result NULL if the path could not be determined, + otherwise, the path as a NULL-terminated dynamically-allocated + string. N.B.: free() MUST be called on the returned string + when it is finished with. +*/ +char *EdenGetExecutablePath(void); + + +/*! + @function + @abstract Get a path as a file URI. + @discussion + Given a full or partial pathname passed in string path, + returns a string with the file URI for that path. + + Partial pathnames are handled by concatening with the + process's current working directory. + @param path Full or partial pathname. + + On Windows, both partial pathnames, full pathnames including + the drive letter, or UNC pathnames (beginning with "\\" are + all OK. + @result A string with the the file URI for that path. + NB: The returned string must be freed by the caller (by + calling free() once its use is complete). +*/ +char *EdenGetFileURI(const char *path); + +#ifdef __cplusplus +} +#endif + +#endif /* !__EdenUtil_h__ */ diff --git a/libs/include/Eden/glm.h b/libs/include/Eden/glm.h new file mode 100755 index 0000000..4ca15dd --- /dev/null +++ b/libs/include/Eden/glm.h @@ -0,0 +1,540 @@ +/* + glm.h + Nate Robins, 1997, 2000 + nate@pobox.com, http://www.pobox.com/~nate + + Wavefront OBJ model file format reader/writer/manipulator. + + Includes routines for generating smooth normals with + preservation of edges, welding redundant vertices & texture + coordinate generation (spheremap and planar projections) + more. +*/ + +// +// Updated by Philip Lamb (PRL) phil@eden.net.nz. All rights reserved. +// +// Rev Date Who Changes +// 1.0.0 ????-??-?? NR Original version released as part of Nate Robin's OpenGL tutors package. +// 1.0.1 2001-11-14 PRL Fix linear texture coordinate generation. +// 1.0.2 2001-11-15 PRL Correct glmUnitize & glmDimensions for model with no -ve vertices, +// and correct glmUnitize to use unit cube, not cube with sides=2.0. +// 1.1.0 2002-01-28 PRL Add glmDrawArrays to use compiled vertex arrays. +// 1.2.0 2002-01-30 PRL glmDraw, glmDrawArrays and glmList are now OpenGL context-specific. +// 1.2.1 2002-02-03 PRL New glmVertexNormals() routine to handle models with polys with > 3 sides more +// consistently. +// 1.3.0 2003-08-06 PRL Now handles materials with dissolve factors for transparency and texture maps +// and dissolve factors. glmReadOBJ is now OpenGL context-specific. +// 1.4.0 2008-07-30 PRL Complete rewrite of glmDrawArrays to now correctly handle normals and texcoords. +// Implementation is now OpenGL|ES 1.1-compliant. +// Fixed a few small bugs in material handling in drawing routines. +// Made glmMax into a macro and added glmMin, & replaced glmAbs with fabsf. +// 1.4.1 2009-04-21 PRL Allow use of multiple materials within a group in the file, by forking off a +// new group. Should now handle models exported from Google Sketchup Pro OK. +// 1.4.2 2010-03-23 PRL Add glmRotate function. Minor changes for correct compilation. +// 1.5.0 2010-09-17 PRL Now supports transparency in materials, including textures. Because depth sorting +// is not yet implemented, overlay of multiple transparent surfaces may produce +// odd visual results. It is recommended that models be sorted back to front +// prior to drawing. +// 1.5.1 2011-03-01 PRL Better handle the case when some but not all faces have normals or texcoords. +// 1.6.0 2011-08-17 PRL Incorporate glStateCache to improve performance on TBDR OpenGL ES renderers. +// 1.7.0 2012-09-28 PRL Added lazy loading of model textures at render time, glmReadOBJ2 to request this. +// 1.7.1 2013-10-02 PRL Added flipping of textures in vertical dimension (some .obj models need it), +// and glmReadOBJ3 to request this. Also, better handles models with odd ordering +// of group and material commands. +// + +// @@BEGIN_EDEN_LICENSE_HEADER@@ +// +// This file is part of The Eden Library. +// +// The Eden Library is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// The Eden Library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with The Eden Library. If not, see . +// +// As a special exception, the copyright holders of this library give you +// permission to link this library with independent modules to produce an +// executable, regardless of the license terms of these independent modules, and to +// copy and distribute the resulting executable under terms of your choice, +// provided that you also meet, for each linked independent module, the terms and +// conditions of the license of that module. An independent module is a module +// which is neither derived from nor based on this library. If you modify this +// library, you may extend this exception to your version of the library, but you +// are not obligated to do so. If you do not wish to do so, delete this exception +// statement from your version. +// +// @@END_EDEN_LICENSE_HEADER@@ + +#ifndef __glm_h__ +#define __glm_h__ + +#define GLM_MATERIAL_TEXTURES // PRL 2003-08-06: Uncomment to build glm with provision for texture mapping in materials. + +#ifdef GLM_MATERIAL_TEXTURES +# ifndef __Eden_h__ +# include +# endif +# include // PRL 20030806: TEXTURE_INFO_t, TEXTURE_INDEX_t, EdenSurfacesTextureLoad(), EdenSurfacesTextureSet(), EdenSurfacesTextureUnload() +#endif // GLM_MATERIAL_TEXTURES + +#ifdef EDEN_MACOSX +# include +#elif defined(EDEN_OPENGLES) +# if defined ANDROID +# include +# include +# else +# include +# include +# endif +#else +# include +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +#define GLM_NONE (0) /* render with only vertices */ +#define GLM_FLAT (1 << 0) /* render with facet normals */ +#define GLM_SMOOTH (1 << 1) /* render with vertex normals */ +#define GLM_TEXTURE (1 << 2) /* render with texture coords */ +#define GLM_COLOR (1 << 3) /* render with colors */ +#define GLM_MATERIAL (1 << 4) /* render with materials */ + +/* GLMmaterial: Structure that defines a material in a model. + */ +typedef struct _GLMmaterial +{ + char* name; /* name of material */ + GLfloat diffuse[4]; /* diffuse component */ + GLfloat ambient[4]; /* ambient component */ + GLfloat specular[4]; /* specular component */ + GLfloat emmissive[4]; /* emmissive component */ + GLfloat shininess; /* specular exponent */ + /* + 0 Color on and Ambient off + 1 Color on and Ambient on + 2 Highlight on + 3 Reflection on and Ray trace on + 4 Transparency: Glass on + Reflection: Ray trace on + 5 Reflection: Fresnel on and Ray trace on + 6 Transparency: Refraction on + Reflection: Fresnel off and Ray trace on + 7 Transparency: Refraction on + Reflection: Fresnel on and Ray trace on + 8 Reflection on and Ray trace off + 9 Transparency: Glass on + Reflection: Ray trace off + 10 Casts shadows onto invisible surfaces + */ + GLint illum; // Illumination model. +#ifdef GLM_MATERIAL_TEXTURES + char* texturemap; // PRL 2003-08-06: path to texture file, relative to material file. + char* texturemappath; // PRL 2012-09-25: path to texture file, relative to working directory. + TEXTURE_INDEX_t texturemap_index; // PRL 2003-08-06: index to loaded texture. 0 indicates not loaded. + char texturemap_hasAlpha; // Whether texture has an alpha channel. +#endif // GLM_MATERIAL_TEXTURES +} GLMmaterial; + +/* GLMtriangle: Structure that defines a triangle in a model. + */ +typedef struct _GLMtriangle { + GLuint vindices[3]; /* array of triangle vertex indices */ + GLuint nindices[3]; /* array of triangle normal indices */ + GLuint tindices[3]; /* array of triangle texcoord indices*/ + GLuint findex; /* index of triangle facet normal */ +} GLMtriangle; + +/* GLMgroup: Structure that defines a group in a model. + */ +typedef struct _GLMgroup { + char* name; /* name of this group */ + GLuint numtriangles; /* number of triangles in this group */ + GLuint* triangles; /* array of triangle _indices_ */ + GLuint material; /* index to material for group */ + struct _GLMgroup* next; /* pointer to next group in model */ +} GLMgroup; + +typedef struct _GLMarray { + GLfloat *vertices; + GLfloat *normals; + GLfloat *texcoords; + GLushort *indices; + GLushort indexCount; + GLMmaterial *material; + struct _GLMarray *next; +} GLMarray; + + +/* GLMmodel: Structure that defines a model. + */ +typedef struct _GLMmodel { + char* pathname; /* path to this model */ + char* mtllibname; /* name of the material library */ + + GLuint numvertices; /* number of vertices in model */ + GLfloat* vertices; /* array of vertices */ + + GLuint numnormals; /* number of normals in model */ + GLfloat* normals; /* array of normals */ + + GLuint numtexcoords; /* number of texcoords in model */ + GLfloat* texcoords; /* array of texture coordinates */ + + GLuint numfacetnorms; /* number of facetnorms in model */ + GLfloat* facetnorms; /* array of facetnorms */ + + GLuint numtriangles; /* number of triangles in model */ + GLMtriangle* triangles; /* array of triangles */ + + GLuint nummaterials; /* number of materials in model */ + GLMmaterial* materials; /* array of materials */ + + GLuint numgroups; /* number of groups in model */ + GLMgroup* groups; /* linked list of groups */ + + GLMarray *arrays; // Optimised arrays of vertices, normals, texcoords for fast drawing. + GLuint arrayMode; // The GLM_* mode with which the arrays were created. + + GLboolean readTextureRequired; // Set if textures need to be read in and submitted to OpenGL. + GLboolean flipTextureV; // Set if textures need to be flipped in vertical dimension. + +} GLMmodel; + + +/* glmUnitize: "unitize" a model by translating it to the origin and + * scaling it to fit in a unit cube around the origin. Returns the + * scalefactor used. + * + * model - properly initialized GLMmodel structure + */ +GLfloat +glmUnitize(GLMmodel* model); + +/* glmDimensions: Calculates the dimensions (width, height, depth) of + * a model. + * + * model - initialized GLMmodel structure + * dimensions - array of 3 GLfloats (GLfloat dimensions[3]) + */ +GLvoid +glmDimensions(GLMmodel* model, GLfloat* dimensions); + +/* glmScale: Scales a model by a given amount. + * + * model - properly initialized GLMmodel structure + * scale - scalefactor (0.5 = half as large, 2.0 = twice as large) + */ +GLvoid +glmScale(GLMmodel* model, GLfloat scale); + +/* glmScaleTextures: Scales a model's textures by a given amount. + * + * model - properly initialized GLMmodel structure + * scale - scalefactor (0.5 = half as large, 2.0 = twice as large) + */ +GLvoid +glmScaleTextures(GLMmodel* model, GLfloat scale); + +/* glmTranslate: Translates (moves) a model by a given amount in x, y, z. + * + * model - properly initialized GLMmodel structure + * offset- vector specifying amount to translate model by. + */ +GLvoid +glmTranslate(GLMmodel* model, const GLfloat offset[3]); + +/* glmRotate: Rotates a model by a given amount angle (in radians) about axis in x, y, z. + * + * model - properly initialized GLMmodel structure + * angle - scalar specifying amount to rotate model by, in radians. + * x, y, z - scalar components of a normalized vector specifiying axis of rotation. + */ +GLvoid +glmRotate(GLMmodel* model, const GLfloat angle, const GLfloat x, const GLfloat y, const GLfloat z); + +/* glmReverseWinding: Reverse the polygon winding for all polygons in + * this model. Default winding is counter-clockwise. Also changes + * the direction of the normals. + * + * model - properly initialized GLMmodel structure + */ +GLvoid +glmReverseWinding(GLMmodel* model); + +/* glmFacetNormals: Generates facet normals for a model (by taking the + * cross product of the two vectors derived from the sides of each + * triangle). Assumes a counter-clockwise winding. + * + * model - initialized GLMmodel structure + */ +GLvoid +glmFacetNormals(GLMmodel* model); + +/* glmVertexNormals: Generates smooth vertex normals for a model. + * First builds a list of all the triangles each vertex is in. Then + * loops through each vertex in the the list averaging all the facet + * normals of the triangles each vertex is in. Finally, sets the + * normal index in the triangle for the vertex to the generated smooth + * normal. If the dot product of a facet normal and the facet normal + * associated with the first triangle in the list of triangles the + * current vertex is in is greater than the cosine of the angle + * parameter to the function, that facet normal is not added into the + * average normal calculation and the corresponding vertex is given + * the facet normal. This tends to preserve hard edges. The angle to + * use depends on the model, but 90 degrees is usually a good start. + * + * model - initialized GLMmodel structure + * angle - maximum angle (in degrees) to smooth across + */ +GLvoid +glmVertexNormals(GLMmodel* model, GLfloat angle); + +/* glmLinearTexture: Generates texture coordinates according to a + * linear projection of the texture map. It generates these by + * linearly mapping the vertices onto a square. + * + * PRL, 20011114: The square lies in the x-z plane and is of the same + * dimension as the model in this plane. Note that this mapping will + * produce highly distored textures on polygons whose projections + * onto the x-z plane have areas approaching zero, i.e. whose facet + * normals have little or no y component. + * + * model - pointer to initialized GLMmodel structure + */ +GLvoid +glmLinearTexture(GLMmodel* model); + +/* glmSpheremapTexture: Generates texture coordinates according to a + * spherical projection of the texture map. Sometimes referred to as + * spheremap, or reflection map texture coordinates. It generates + * these by using the normal to calculate where that vertex would map + * onto a sphere. Since it is impossible to map something flat + * perfectly onto something spherical, there is distortion at the + * poles. This particular implementation causes the poles along the X + * axis to be distorted. + * + * model - pointer to initialized GLMmodel structure + */ +GLvoid +glmSpheremapTexture(GLMmodel* model); + +/* glmDelete: Deletes a GLMmodel structure. + * + * model - initialized GLMmodel structure + * contextIndex - PRL: index to the current OpenGL context (for texturing.) If you have only + * one OpenGL context (the most common case) set this parameter to 0. + */ +GLvoid +glmDelete(GLMmodel* model, const int contextIndex); + +/* glmReadOBJ: Reads a model description from a Wavefront .OBJ file. + * Returns a pointer to the created object which should be free'd with + * glmDelete(). + * + * filename - name of the file containing the Wavefront .OBJ format data. + * contextIndex - PRL: index to the current OpenGL context (for texturing.) + */ +GLMmodel* +glmReadOBJ(const char *filename, const int contextIndex); + +/* glmReadOBJ2: Reads a model description from a Wavefront .OBJ file. + * Returns a pointer to the created object which should be free'd with + * glmDelete(). + * Whereas glReadOBJ will attempt to load and submit to OpenGL any + * textures specified in an accompanying materials file, this variant allows + * texture loading to be delayed until the model is actually to be drawn, + * i.e. lazily loaded. + * + * filename - name of the file containing the Wavefront .OBJ format data. + * contextIndex - PRL: index to the current OpenGL context (for texturing.) + * readTexturesNow - TRUE to load and submit to OpenGL any textures specified + * in an accompanying materials file, or FALSE to lazily load textures + * at the time of a later glmDraw() or glmDrawArrays call(). + */ +GLMmodel* +glmReadOBJ2(const char *filename, const int contextIndex, const GLboolean readTexturesNow); + +/* glmReadOBJ2: Reads a model description from a Wavefront .OBJ file. + * Returns a pointer to the created object which should be free'd with + * glmDelete(). + * Whereas glReadOBJ will attempt to load and submit to OpenGL any + * textures specified in an accompanying materials file, this variant allows + * texture loading to be delayed until the model is actually to be drawn, + * i.e. lazily loaded. + * + * filename - name of the file containing the Wavefront .OBJ format data. + * contextIndex - PRL: index to the current OpenGL context (for texturing.) + * readTexturesNow - TRUE to load and submit to OpenGL any textures specified + * in an accompanying materials file, or FALSE to lazily load textures + * at the time of a later glmDraw() or glmDrawArrays call(). + * flipTextureV - If TRUE, textures will be flipped in the V (vertical) + * dimension as they are loaded. Some .obj files are written with textures flipped + * in this way. If FALSE, behaviour is the same as for glmReadOBJ2(). + */ +GLMmodel* +glmReadOBJ3(const char *filename, const int contextIndex, const GLboolean readTexturesNow, const GLboolean flipTextureV); + +/* glmWriteOBJ: Writes a model description in Wavefront .OBJ format to + * a file. + * + * model - initialized GLMmodel structure + * filename - name of the file to write the Wavefront .OBJ format data to + * mode - a bitwise or of values describing what is written to the file + * GLM_NONE - write only vertices + * GLM_FLAT - write facet normals + * GLM_SMOOTH - write vertex normals + * GLM_TEXTURE - write texture coords + * GLM_FLAT and GLM_SMOOTH should not both be specified. + */ +GLvoid +glmWriteOBJ(GLMmodel* model, char* filename, GLuint mode); + +#ifndef EDEN_OPENGLES +/* glmDraw: Renders the model to the current OpenGL context using the + * mode specified. + * + * model - initialized GLMmodel structure + * mode - a bitwise OR of values describing what is to be rendered. + * GLM_NONE - render with only vertices + * GLM_FLAT - render with facet normals + * GLM_SMOOTH - render with vertex normals + * GLM_TEXTURE - render with texture coords + * GLM_COLOR - render with colors (color material) + * GLM_MATERIAL - render with materials + * GLM_COLOR and GLM_MATERIAL should not both be specified. + * GLM_FLAT and GLM_SMOOTH should not both be specified. + * contextIndex - PRL: index to the current OpenGL context (for texturing.) If you have only + * one OpenGL context (the most common case) set this parameter to 0. + */ +GLvoid +glmDraw(GLMmodel* model, GLuint mode, const int contextIndex); + +/* glmList: Generates and returns a display list for the model using + * the mode specified. + * + * model - initialized GLMmodel structure + * mode - a bitwise OR of values describing what is to be rendered. + * GLM_NONE - render with only vertices + * GLM_FLAT - render with facet normals + * GLM_SMOOTH - render with vertex normals + * GLM_TEXTURE - render with texture coords + * GLM_COLOR - render with colors (color material) + * GLM_MATERIAL - render with materials + * GLM_COLOR and GLM_MATERIAL should not both be specified. + * GLM_FLAT and GLM_SMOOTH should not both be specified. + * contextIndex - PRL: index to the current OpenGL context (for texturing.) If you have only + * one OpenGL context (the most common case) set this parameter to 0. + */ +GLuint +glmList(GLMmodel* model, GLuint mode, const int contextIndex); +#endif // !EDEN_OPENGLES + +/* glmWeld: eliminate (weld) vectors that are within an epsilon of + * each other. + * + * model - initialized GLMmodel structure + * epsilon - maximum difference between vertices + * ( 0.00001 is a good start for a unitized model) + * + */ +GLvoid +glmWeld(GLMmodel* model, GLfloat epsilon); + + +/* glmReadPPM: read a PPM raw (type P6) file. The PPM file has a header + * that should look something like: + * + * P6 + * # comment + * width height max_value + * rgbrgbrgb... + * + * where "P6" is the magic cookie which identifies the file type and + * should be the only characters on the first line followed by a + * carriage return. Any line starting with a # mark will be treated + * as a comment and discarded. After the magic cookie, three integer + * values are expected: width, height of the image and the maximum + * value for a pixel (max_value must be < 256 for PPM raw files). The + * data section consists of width*height rgb triplets (one byte each) + * in binary format (i.e., such as that written with fwrite() or + * equivalent). + * + * The rgb data is returned as an array of unsigned chars (packed + * rgb). The malloc()'d memory should be free()'d by the caller. If + * an error occurs, an error message is sent to stderr and NULL is + * returned. + * + * filename - name of the .ppm file. + * width - will contain the width of the image on return. + * height - will contain the height of the image on return. + * + */ + +GLubyte* +glmReadPPM(const char* filename, int* width, int* height); + +/* glmCreateArrays: Creates a linked list of vertex, normal, and texcoord data arrays and + * a set of triangle indices for the model specified using the mode specified. + * + * Each node in the list represents one group in the model. + * The created arrays are added to the model and do not track any other state changes in + * the model apart from material properties, so if you change the model, or if you wish + * to draw using a different mode, you will need to regenerate the arrays by calling + * glmCreateArrays again. + * + * This function must be called before any call to glmDrawArrays(). + * + * By Philip Lamb, phil@eden.net.nz, 2008-07-30 + * + * model - initialized GLMmodel structure. + * mode - a bitwise OR of values describing what is to be rendered. + * GLM_NONE - render with only vertices + * GLM_FLAT - render with facet normals + * GLM_SMOOTH - render with vertex normals + * GLM_TEXTURE - render with texture coords + * GLM_COLOR - render with colors (color material) + * GLM_MATERIAL - render with materials + * GLM_COLOR and GLM_MATERIAL should not both be specified. + * GLM_FLAT and GLM_SMOOTH should not both be specified. + */ +GLvoid glmCreateArrays(GLMmodel* model, GLuint mode); + +/* glmDeleteArrays: Remove any arrays from a model structure. + * + * This function may be called after all calsl to glmDrawArrays() are complete + * to free up memory associated with the arrays. This will be done + * automatically if the model itself is deleted (by a call to glmDelete()). + * + * By Philip Lamb, phil@eden.net.nz, 2008-07-30 + * + * model - initialized GLMmodel structure. + */ +GLvoid glmDeleteArrays(GLMmodel *model); + + +/* glmDrawArrays: Draws a model using array data created by glmCreateArrays(). + * + * By Philip Lamb, phil@eden.net.nz, 2008-07-30 + * + * model - initialized GLMmodel structure, which has had arrays created. + * contextIndex - index to the current OpenGL context (for texturing.) If you have only + * one OpenGL context (the most common case) set this parameter to 0. + */ +GLvoid glmDrawArrays(GLMmodel* model, const int contextIndex); + +#ifdef __cplusplus +} +#endif + +#endif /* !__glm_h__ */ diff --git a/libs/include/Eden/gluttext.h b/libs/include/Eden/gluttext.h new file mode 100755 index 0000000..feab7f8 --- /dev/null +++ b/libs/include/Eden/gluttext.h @@ -0,0 +1,90 @@ +/* Copyright (c) Mark J. Kilgard, 1994. */ + +/* This program is freely distributable without licensing fees + and is provided without guarantee or warrantee expressed or + implied. This program is -not- in the public domain. */ + +// +// Updated by Philip Lamb (PRL) phil@eden.net.nz. All rights reserved. +// +// +// Defines glut stroke and bitmap font functions for OpenGL ES-based platforms. +// + +#ifndef __gluttext_h__ +#define __gluttext_h__ + +#ifndef __Eden_h__ +# include +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +#define APIENTRY + +#ifdef EDEN_OPENGLES +# define GLUTTEXT_BITMAP_ENABLE 0 +# define GLUTTEXT_STROKE_ENABLE 1 +#else +# define GLUTTEXT_BITMAP_ENABLE 0 +# define GLUTTEXT_STROKE_ENABLE 0 +#endif + +#if GLUTTEXT_STROKE_ENABLE + +/* Stroke font opaque addresses (use constants instead in source code). */ +extern const struct _StrokeFontRec glutStrokeRoman; +extern const struct _StrokeFontRec glutStrokeMonoRoman; + +/* Stroke font constants (use these in GLUT program). */ + +/* + A proportionally spaced Roman Simplex font for ASCII characters + 32 through 127. The maximum top character in the font is 119.05 + units; the bottom descends 33.33 units. + */ +#define GLUT_STROKE_ROMAN ((void *)&glutStrokeRoman) + +/* + A mono-spaced spaced Roman Simplex font (same characters as + GLUT_STROKE_ROMAN) for ASCII characters 32 through 127. The + maximum top character in the font is 119.05 units; the bottom + descends 33.33 units. Each character is 104.76 units wide. + */ +#define GLUT_STROKE_MONO_ROMAN ((void *)&glutStrokeMonoRoman) + +extern void glutStrokeCharacter(void *font, int character); +extern int glutStrokeWidth(void *font, int character); +extern int glutStrokeLength(void *font, const unsigned char *string); +#endif // GLUTTEXT_STROKE_ENABLE + +#if GLUTTEXT_BITMAP_ENABLE + +/* Bitmap font opaque addresses (use constants instead in source code). */ +extern const struct _BitmapFontRec glutBitmap9By15; +extern const struct _BitmapFontRec glutBitmap8By13; +extern const struct _BitmapFontRec glutBitmapTimesRoman10; +extern const struct _BitmapFontRec glutBitmapTimesRoman24; +extern const struct _BitmapFontRec glutBitmapHelvetica10; +extern const struct _BitmapFontRec glutBitmapHelvetica12; +extern const struct _BitmapFontRec glutBitmapHelvetica18; + +/* Bitmap font constants (use these in GLUT program). */ +#define GLUT_BITMAP_9_BY_15 ((void *)&glutBitmap9By15) +#define GLUT_BITMAP_8_BY_13 ((void *)&glutBitmap8By13) +#define GLUT_BITMAP_TIMES_ROMAN_10 ((void *)&glutBitmapTimesRoman10) +#define GLUT_BITMAP_TIMES_ROMAN_24 ((void *)&glutBitmapTimesRoman24) +#define GLUT_BITMAP_HELVETICA_10 ((void *)&glutBitmapHelvetica10) +#define GLUT_BITMAP_HELVETICA_12 ((void *)&glutBitmapHelvetica12) +#define GLUT_BITMAP_HELVETICA_18 ((void *)&glutBitmapHelvetica18) +extern void glutBitmapCharacter(void *font, int character); +extern int glutBitmapWidth(void *font, int character); +extern int glutBitmapLength(void *font, const unsigned char *string); +#endif // GLUTTEXT_BITMAP_ENABLE + +#ifdef __cplusplus +} +#endif +#endif // !__gluttext_h__ diff --git a/libs/include/Eden/readtex.h b/libs/include/Eden/readtex.h new file mode 100755 index 0000000..ed5e226 --- /dev/null +++ b/libs/include/Eden/readtex.h @@ -0,0 +1,102 @@ +/* readtex.h */ +/* + * Read an SGI .rgb image file and generate a mipmap texture set. + */ + +// @@BEGIN_EDEN_LICENSE_HEADER@@ +// +// This file is part of The Eden Library. +// +// The Eden Library is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// The Eden Library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with The Eden Library. If not, see . +// +// As a special exception, the copyright holders of this library give you +// permission to link this library with independent modules to produce an +// executable, regardless of the license terms of these independent modules, and to +// copy and distribute the resulting executable under terms of your choice, +// provided that you also meet, for each linked independent module, the terms and +// conditions of the license of that module. An independent module is a module +// which is neither derived from nor based on this library. If you modify this +// library, you may extend this exception to your version of the library, but you +// are not obligated to do so. If you do not wish to do so, delete this exception +// statement from your version. +// +// @@END_EDEN_LICENSE_HEADER@@ + +/*! + @header readtex + @abstract Texture loading from file. + @discussion + readtex forms one part of the Eden library. + @copyright 2001-2013 Philip Lamb + */ + +#ifndef READTEX_H +#define READTEX_H + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef __Eden_h__ +# include +#endif + +#include + +#ifdef EDEN_HAVE_LIBJPEG +/*! + @function + @abstract Read a JPEG file and return it as a raw buffer. + @discussion + Reads a JPEG image from a file into a raw buffer. JPEGs in mono and RGB format + are supported. + @param fp File pointer to open jpeg file. + @param w Pointer to location which will be filled with the width of the JPEG image in pixels, + or NULL if this is not required. + @param h Pointer to location which will be filled with the width of the JPEG image in pixels, + or NULL if this is not required. + @param nc Pointer to location which will be filled with the number of components in + the JPEG image in pixels, or NULL if this is not required. + @param dpi Pointer to location which will be filled with the resolution of the jpeg in + dots-per-inch, or NULL if this is not required. + @result A raw buffer holding the jpeg data, beginning with the first component of the + leftmost pixel of the uppermost scanline, and continuing by component, pixel, and line. + This buffer must be free()d when finished with. + */ +unsigned char *jpgread (FILE *fp, int *w, int *h, int *nc, float *dpi); +#endif // EDEN_HAVE_LIBJPEG + +/*! + @function + @abstract Read an image file and return it as a raw buffer. + @discussion + @param imageFile name of image to read. At present, images in SGI format (.sgi or .rgb) + and JPEG format (.jpg or .jpeg) are supported. + @param w Pointer to location which will be filled with the width of the image in pixels, + or NULL if this is not required. + @param h Pointer to location which will be filled with the width of the image in pixels, + or NULL if this is not required. + @param nc Pointer to location which will be filled with the number of components in + the image in pixels, or NULL if this is not required. + @result A raw buffer holding the image data, beginning with the first component of the + leftmost pixel of the uppermost scanline, and continuing by component, pixel, and line. + This buffer must be free()d when finished with. + */ +extern unsigned char *ReadTex(const char *imageFile, int *w, int *h, int *nc); + +#ifdef __cplusplus +} +#endif + +#endif /* !READTEX_H */ diff --git a/libs/include/KPM/kpm.h b/libs/include/KPM/kpm.h new file mode 100755 index 0000000..c8686f8 --- /dev/null +++ b/libs/include/KPM/kpm.h @@ -0,0 +1,405 @@ +/* + * kpm.h + * ARToolKit5 + * + * This file is part of ARToolKit. + * + * ARToolKit is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ARToolKit is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ARToolKit. If not, see . + * + * As a special exception, the copyright holders of this library give you + * permission to link this library with independent modules to produce an + * executable, regardless of the license terms of these independent modules, and to + * copy and distribute the resulting executable under terms of your choice, + * provided that you also meet, for each linked independent module, the terms and + * conditions of the license of that module. An independent module is a module + * which is neither derived from nor based on this library. If you modify this + * library, you may extend this exception to your version of the library, but you + * are not obligated to do so. If you do not wish to do so, delete this exception + * statement from your version. + * + * Copyright 2015 Daqri, LLC. All rights reserved. + * Copyright 2006-2015 ARToolworks, Inc. All rights reserved. + * Author(s): Hirokazu Kato, Philip Lamb + * + */ + +/*! + @header kpm + @abstract libKPM NFT image recognition and tracking initialisation routines. + @discussion + This header declares types and API for an NFT tracker, + in particular those routines involved in recognising a texture page and + initialising the tracking for use by the texture tracker. + @copyright 2006-2015 ARToolworks, Inc. + */ + +#ifndef KPM_H +#define KPM_H + +#define BINARY_FEATURE 1 + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define KpmPose6DOF 1 +#define KpmPoseHomography 2 + +typedef enum { + KpmProcFullSize = 1, + KpmProcHalfSize = 2, + KpmProcQuatSize = 3, + KpmProcOneThirdSize = 4, + KpmProcTwoThirdSize = 5 +} KPM_PROC_MODE; +#define KpmDefaultProcMode KpmProcFullSize + +#define KpmCompNull 0 +#define KpmCompX 1 +#define KpmCompY 2 +#define KpmDefaultComp KpmCompNull + +#define KpmChangePageNoAllPages (-1) + +typedef struct { + float x; + float y; +} KpmCoord2D; + +typedef struct { + int width; + int height; + int imageNo; +} KpmImageInfo; + +typedef struct { + KpmImageInfo *imageInfo; + int imageNum; + int pageNo; +} KpmPageInfo; + +typedef struct _KpmRefData { + KpmCoord2D coord2D; + KpmCoord2D coord3D; // millimetres. +#if BINARY_FEATURE + FreakFeature featureVec; +#else + SurfFeature featureVec; +#endif + int pageNo; + int refImageNo; +} KpmRefData; + +/*! + @typedef KpmRefDataSet + @abstract A loaded dataset for KPM tracking. + @discussion + Key point matching takes as input a reference data set of points. This structure holds a set of points in memory prior to loading into the tracker. + @field refPoint Tracking reference points. + @field num Number of refPoints in the dataset. + @field pageInfo Array of info about each page in the dataset. One entry per page. + @field pageNum Number of pages in the dataset (i.e. a count, not an index). + */ +typedef struct { + KpmRefData *refPoint; + int num; + KpmPageInfo *pageInfo; + int pageNum; +} KpmRefDataSet; + +/*! + @typedef KpmInputDataSet + @abstract Data describing the number and location of keypoints in an input image to be matched against a loaded data set. + @discussion + Key point matching occurs between a loaded data set and a set of keypoints extracted from an input image. This structure + holds the number and pixel location of keypoints in the input image. The keypoints themselves are an array of 'num' + KpmRefData structures. + @field coord Array of pixel locations of the keypoints in an input image. + @field num Number of coords in the array. + */ +typedef struct { + KpmCoord2D *coord; + int num; +} KpmInputDataSet; + +#if !BINARY_FEATURE +typedef struct { + int refIndex; + int inIndex; +} KpmMatchData; + +typedef struct { + KpmMatchData *match; + int num; +} KpmMatchResult; +#endif + +typedef struct { + float camPose[3][4]; + int pageNo; + float error; + int inlierNum; + int camPoseF; + int skipF; +} KpmResult; + +typedef struct _KpmHandle KpmHandle; + + +/*! + @function + @abstract Allocate and initialise essential structures for KPM tracking, using full six degree-of-freedom tracking. + @discussion + @param cparamLT Pointer to an ARParamLT structure holding camera parameters in lookup-table form. + The pointer only is copied, and the ARParamLT structure itself is NOT copied, and must remain + valid for the lifetime of the KpmHandle. + This structure also specifies the size of video frames which will be later supplied to the + kpmMatching() function as cparamLT->param.xsize and cparamLT->param.ysize. + @param pixFormat Pixel format of video frames which will be later supplied to the kpmMatching() function. + @result Pointer to a newly-allocated KpmHandle structure. This structure must be deallocated + via a call to kpmDeleteHandle() when no longer needed. + @seealso kpmCreateHandleHomography kpmCreateHandleHomography + @seealso kpmDeleteHandle kpmDeleteHandle + */ +KpmHandle *kpmCreateHandle ( ARParamLT *cparamLT, AR_PIXEL_FORMAT pixFormat ); +#define kpmCreatHandle kpmCreateHandle + +KpmHandle *kpmCreateHandle2( int xsize, int ysize, AR_PIXEL_FORMAT pixFormat ); +#define kpmCreatHandle2 kpmCreateHandle2 + +/*! + @function + @abstract Allocate and initialise essential structures for KPM tracking, using homography-only tracking. + @discussion + Homography tracking assumes that the camera has zero lens-distortion, and this does not depend on + camera parameters. It is therefore unable to provide correctly calibrated position measurements, + but the resulting pose is suitable for visual overlay purposes. + @param xsize Width of video frames which will be later supplied to the kpmMatching() function. + @param ysize Height of video frames which will be later supplied to the kpmMatching() function. + @param pixFormat Pixel format of video frames which will be later supplied to the kpmMatching() function. + @result Pointer to a newly-allocated KpmHandle structure. This structure must be deallocated + via a call to kpmDeleteHandle() when no longer needed. + @seealso kpmCreateHandle kpmCreateHandle + @seealso kpmDeleteHandle kpmDeleteHandle + */ +KpmHandle *kpmCreateHandleHomography( int xsize, int ysize, AR_PIXEL_FORMAT pixFormat ); +#define kpmCreatHandleHomography kpmCreateHandleHomography + +/*! + @function + @abstract Finalise and dispose of structures for KPM tracking. + @discussion + Once KPM processing has completed, this routine should be called to + dispose of memory allocated. + @param kpmHandle Pointer to a location which holds a pointer to a KpmHandle structure. + On return, the location pointed to will be set to NULL. + @result 0 if successful, or value <0 in case of error. + @seealso kpmCreateHandle kpmCreateHandle + @seealso kpmCreateHandleHomography kpmCreateHandleHomography + */ +int kpmDeleteHandle( KpmHandle **kpmHandle ); + +int kpmHandleGetXSize(const KpmHandle *kpmHandle); +int kpmHandleGetYSize(const KpmHandle *kpmHandle); +AR_PIXEL_FORMAT kpmHandleGetPixelFormat(const KpmHandle *kpmHandle); + +int kpmSetProcMode( KpmHandle *kpmHandle, KPM_PROC_MODE procMode ); +int kpmGetProcMode( KpmHandle *kpmHandle, KPM_PROC_MODE *procMode ); +int kpmSetDetectedFeatureMax( KpmHandle *kpmHandle, int detectedMaxFeature ); +int kpmGetDetectedFeatureMax( KpmHandle *kpmHandle, int *detectedMaxFeature ); +int kpmSetSurfThreadNum( KpmHandle *kpmHandle, int surfThreadNum ); + +/*! + @function + @abstract Load a reference data set into the key point matcher for tracking. + @discussion + This function takes a reference data set already in memory and makes it the current + dataset for key point matching. + @param kpmHandle Handle to the current KPM tracker instance, as generated by kpmCreateHandle or kpmCreateHandleHomography. + @param refDataSet The reference data set to load into the KPM handle. The operation takes + a copy of the data required from this dataset, thus unless the need for a further load + at a later time is required, the dataset can be disposed of by calling kpmDeleteRefDataSet + after this operation succeeds. + @result 0 if successful, or value <0 in case of error. + @seealso kpmCreateHandle kpmCreateHandle + @seealso kpmCreateHandleHomography kpmCreateHandleHomography + @seealso kpmDeleteRefDataSet kpmDeleteRefDataSet + */ +int kpmSetRefDataSet( KpmHandle *kpmHandle, KpmRefDataSet *refDataSet ); + +/*! + @function + @abstract + Loads a reference data set from a file into the KPM tracker. + @discussion + This is a convenience method which performs a sequence of kpmLoadRefDataSet, followed + by kpmSetRefDataSet and finally kpmDeleteRefDataSet. When tracking from a single + reference dataset file, this is the simplest means to start. + @param kpmHandle Handle to the current KPM tracker instance, as generated by kpmCreateHandle or kpmCreateHandleHomography. + @param filename Path to the dataset. Either full path, or a relative path if supported by + the operating system. + @param ext If non-NULL, a '.' charater and this string will be appended to 'filename'. + Often, this parameter is a pointer to the string "fset3". + @result Returns 0 if successful, or value <0 in case of error. + @seealso kpmLoadRefDataSet kpmLoadRefDataSet + @seealso kpmSetRefDataSet kpmSetRefDataSet + @seealso kpmDeleteRefDataSet kpmDeleteRefDataSet + */ +int kpmSetRefDataSetFile( KpmHandle *kpmHandle, const char *filename, const char *ext ); + +int kpmSetRefDataSetFileOld( KpmHandle *kpmHandle, const char *filename, const char *ext ); + +/*! + @function + @abstract Perform key-point matching on an image. + @discussion + @param kpmHandle + @param inImage Source image containing the pixels which will be searched for features. + Typically, this is one frame from a video stream. The dimensions and pixel format + of this image must match the values specified at the time of creation of the KPM handle. + @result 0 if successful, or value <0 in case of error. + @seealso kpmCreateHandle kpmCreateHandle + @seealso kpmCreateHandleHomography kpmCreateHandleHomography + */ +int kpmMatching( KpmHandle *kpmHandle, ARUint8 *inImage ); + +int kpmSetMatchingSkipPage( KpmHandle *kpmHandle, int *skipPages, int num ); +#if !BINARY_FEATURE +int kpmSetMatchingSkipRegion( KpmHandle *kpmHandle, SurfSubRect *skipRegion, int regionNum); +#endif + +int kpmGetRefDataSet( KpmHandle *kpmHandle, KpmRefDataSet **refDataSet ); +int kpmGetInDataSet( KpmHandle *kpmHandle, KpmInputDataSet **inDataSet ); +#if !BINARY_FEATURE +int kpmGetMatchingResult( KpmHandle *kpmHandle, KpmMatchResult **preRANSAC, KpmMatchResult **aftRANSAC ); +#endif +int kpmGetPose( KpmHandle *kpmHandle, float pose[3][4], int *pageNo, float *error ); +int kpmGetResult( KpmHandle *kpmHandle, KpmResult **result, int *resultNum ); + + +int kpmGenRefDataSet ( ARUint8 *refImage, AR_PIXEL_FORMAT pixFormat, int xsize, int ysize, float dpi, int procMode, int compMode, int maxFeatureNum, + int pageNo, int imageNo, KpmRefDataSet **refDataSet ); +int kpmAddRefDataSet ( ARUint8 *refImage, AR_PIXEL_FORMAT pixFormat, int xsize, int ysize, float dpi, int procMode, int compMode, int maxFeatureNum, + int pageNo, int imageNo, KpmRefDataSet **refDataSet ); + +/*! + @function + @abstract Merge a second KPM dataset into the first, and dispose of second. + @discussion + This function merges two KPM datasets by adding the reference points in + the second into the first (allocating a new set if the location pointed to + by refDataSetPtr1 is NULL) and then deleting the second set. + @param refDataSetPtr1 Pointer to a location which points to the first data set, or pointer + to NULL if a new dataset is to be created. This will hold the results of the merge. + @param refDataSetPtr2 Pointer to a location which points to the second data set. After the + merge, the dataset pointed to will be deleted and the location pointed to set to NULL. + @result 0 if the merge succeeded, or a value < 0 in case of error. + */ +int kpmMergeRefDataSet ( KpmRefDataSet **refDataSetPtr1, KpmRefDataSet **refDataSetPtr2 ); +#define kpmMargeRefDataSet kpmMergeRefDataSet + +/*! + @function + @abstract Dispose of a reference data set and its allocated memory. + @discussion + Once a data set has been loaded into a KPM handle, or is otherwise no longer required + to be held in memory, it should be deleted (i.e. disposed) from memory by calling + this function. + @param refDataSetPtr Pointer to memory location which points to the dataset. On success, + this location will be set to NULL. + @result 0 if the delete succeeded, or a value < 0 in case of error. + @seealso kpmLoadRefDataSet kpmLoadRefDataSet + */ +int kpmDeleteRefDataSet ( KpmRefDataSet **refDataSetPtr ); + +/*! + @function + @abstract + @discussion + @param filename + @param ext + @param refDataSet + @result + */ +int kpmSaveRefDataSet ( const char *filename, const char *ext, KpmRefDataSet *refDataSet ); + +/*! + @function + @abstract Load a reference data set from the filesystem into memory. + @discussion + This does not set the reference data as the current tracking set. To do that, call + kpmSetRefDataSet after this load completes. Alternately, the loaded set can be + merged with another loaded set by calling kpmMergeRefDataSet. To dispose of the + loaded dataset, call kpmDeleteRefDataSet. + @param filename Path to the dataset. Either full path, or a relative path if supported by + the operating system. + @param ext If non-NULL, a '.' charater and this string will be appended to 'filename'. + Often, this parameter is a pointer to the string "fset3". + @result Returns 0 if successful, or value <0 in case of error. + @param refDataSetPtr Pointer to a location which after loading will point to the loaded + reference data set. + @result 0 if the load succeeded, or a value < 0 in case of error. + @seealso kpmSetRefDataSet kpmSetRefDataSet + @seealso kpmMergeRefDataSet kpmMergeRefDataSet + @seealso kpmDeleteRefDataSet kpmDeleteRefDataSet + */ +int kpmLoadRefDataSet ( const char *filename, const char *ext, KpmRefDataSet **refDataSetPtr ); + +int kpmLoadRefDataSetOld( const char *filename, const char *ext, KpmRefDataSet **refDataSetPtr ); + +/*! + @function + @abstract + @discussion + @param refDataSet + @param oldPageNo + @param newPageNo + @result + */ +int kpmChangePageNoOfRefDataSet ( KpmRefDataSet *refDataSet, int oldPageNo, int newPageNo ); + + +/*! + @function + @abstract + @discussion + @param image Source image, as an unpadded pixel buffer beginning with the leftmost pixel of the top row. + @param pixFormat Layout of pixel data in 'image'. + @param xsize Layout of pixel data in 'image'. + @param ysize Layout of pixel data in 'image'. + @param procMode + @result + */ +ARUint8 *kpmUtilGenBWImage( ARUint8 *image, AR_PIXEL_FORMAT pixFormat, int xsize, int ysize, int procMode, int *newXsize, int *newYsize ); + +#if !BINARY_FEATURE +int kpmUtilGetPose ( ARParamLT *cparamLT, KpmMatchResult *matchData, KpmRefDataSet *refDataSet, KpmInputDataSet *inputDataSet, float camPose[3][4], float *err ); + +int kpmUtilGetPose2( ARParamLT *cparamLT, KpmMatchResult *matchData, KpmRefDataSet *refDataSet, int *redDataIndex, KpmInputDataSet *inputDataSet, float camPose[3][4], float *error ); +int kpmUtilGetPoseHomography( KpmMatchResult *matchData, KpmRefDataSet *refDataSet, KpmInputDataSet *inputDataSet, float camPose[3][4], float *err ); +#endif +int kpmUtilGetCorner( ARUint8 *inImagePtr, AR_PIXEL_FORMAT pixFormat, int xsize, int ysize, int procMode, int maxPointNum, CornerPoints *cornerPoints ); + + +double wallclock(); + +int kpmLoadImageDb(const char *filename); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/libs/include/KPM/kpmType.h b/libs/include/KPM/kpmType.h new file mode 100755 index 0000000..58afe7b --- /dev/null +++ b/libs/include/KPM/kpmType.h @@ -0,0 +1,109 @@ +/* + * kpmType.h + * ARToolKit5 + * + * This file is part of ARToolKit. + * + * ARToolKit is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ARToolKit is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ARToolKit. If not, see . + * + * As a special exception, the copyright holders of this library give you + * permission to link this library with independent modules to produce an + * executable, regardless of the license terms of these independent modules, and to + * copy and distribute the resulting executable under terms of your choice, + * provided that you also meet, for each linked independent module, the terms and + * conditions of the license of that module. An independent module is a module + * which is neither derived from nor based on this library. If you modify this + * library, you may extend this exception to your version of the library, but you + * are not obligated to do so. If you do not wish to do so, delete this exception + * statement from your version. + * + * Copyright 2015 Daqri, LLC. All rights reserved. + * Copyright 2006-2015 ARToolworks, Inc. All rights reserved. + * Author(s): Hirokazu Kato, Philip Lamb + * + */ + +#pragma once + +#if !BINARY_FEATURE +#include +#endif + +//------------------------------------------------------------------------- +// Corner points +//------------------------------------------------------------------------- + +#define MAX_CORNER_POINTS 2000 + +typedef struct _Point2f { + float x; + float y; +} Point2f; + +typedef struct _Point2i { + int x; + int y; +} Point2i; + +typedef struct _CornerPoints { + int num; + Point2i pt[MAX_CORNER_POINTS]; +} CornerPoints; + +//------------------------------------------------------------------------- +// Correspondence +//------------------------------------------------------------------------- + +typedef struct _MatchPoint { + float x1, y1; // Coordinates of corner points in an input image + float x2, y2; // Coordinates of corner points in a reference image +} MatchPoint; + +typedef struct _CorspMap { + int num; // Same as the number of corner points in the input image + MatchPoint *mp; +} CorspMap; + +#if BINARY_FEATURE + +#define FREAK_SUB_DIMENSION 96 + +//FREAK feature vector +typedef struct _FreakFeature { + unsigned char v[FREAK_SUB_DIMENSION]; + float angle; + float scale; + int maxima; +} FreakFeature; +#else +//------------------------------------------------------------------------- +// Surf feature vector +//------------------------------------------------------------------------- + +typedef struct _SurfFeature { + float v[SURF_SUB_DIMENSION]; + int l; +} SurfFeature; +#endif + +typedef struct _FeatureVector { + int num; +#if BINARY_FEATURE + FreakFeature *sf; +#else + SurfFeature *sf; +#endif + +} FeatureVector; + diff --git a/libs/include/android/OpenThreads/Atomic b/libs/include/android/OpenThreads/Atomic new file mode 100755 index 0000000..ba67233 --- /dev/null +++ b/libs/include/android/OpenThreads/Atomic @@ -0,0 +1,287 @@ +/* -*-c++-*- OpenThreads library, Copyright (C) 2008 The Open Thread Group + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef _OPENTHREADS_ATOMIC_ +#define _OPENTHREADS_ATOMIC_ + +#include +#include + +#if defined(_OPENTHREADS_ATOMIC_USE_BSD_ATOMIC) +# include +# define _OPENTHREADS_ATOMIC_USE_LIBRARY_ROUTINES +#elif defined(_OPENTHREADS_ATOMIC_USE_GCC_BUILTINS) && defined(__i386__) +# define _OPENTHREADS_ATOMIC_USE_LIBRARY_ROUTINES +#elif defined(_OPENTHREADS_ATOMIC_USE_WIN32_INTERLOCKED) +# define _OPENTHREADS_ATOMIC_USE_LIBRARY_ROUTINES +#elif defined(_OPENTHREADS_ATOMIC_USE_SUN) +# include +# include "Mutex" +# include "ScopedLock" +#elif defined(_OPENTHREADS_ATOMIC_USE_MUTEX) +# include "Mutex" +# include "ScopedLock" +#endif + +#if defined(_OPENTHREADS_ATOMIC_USE_LIBRARY_ROUTINES) +#define _OPENTHREADS_ATOMIC_INLINE +#else +#define _OPENTHREADS_ATOMIC_INLINE inline +#endif + +namespace OpenThreads { + +/** + * @class Atomic + * @brief This class provides an atomic increment and decrement operation. + */ +class OPENTHREAD_EXPORT_DIRECTIVE Atomic { + public: + Atomic(unsigned value = 0) : _value(value) + { } + _OPENTHREADS_ATOMIC_INLINE unsigned operator++(); + _OPENTHREADS_ATOMIC_INLINE unsigned operator--(); + _OPENTHREADS_ATOMIC_INLINE unsigned AND(unsigned value); + _OPENTHREADS_ATOMIC_INLINE unsigned OR(unsigned value); + _OPENTHREADS_ATOMIC_INLINE unsigned XOR(unsigned value); + _OPENTHREADS_ATOMIC_INLINE unsigned exchange(unsigned value = 0); + _OPENTHREADS_ATOMIC_INLINE operator unsigned() const; + private: + + Atomic(const Atomic&); + Atomic& operator=(const Atomic&); + +#if defined(_OPENTHREADS_ATOMIC_USE_MUTEX) + mutable Mutex _mutex; +#endif +#if defined(_OPENTHREADS_ATOMIC_USE_WIN32_INTERLOCKED) + volatile long _value; +#elif defined(_OPENTHREADS_ATOMIC_USE_BSD_ATOMIC) + volatile int32_t _value; +#elif defined(_OPENTHREADS_ATOMIC_USE_SUN) + volatile uint_t _value; + mutable Mutex _mutex; // needed for xor +#else + volatile unsigned _value; +#endif +}; + +/** + * @class AtomicPtr + * @brief This class provides an atomic pointer assignment using cas operations. + */ +class OPENTHREAD_EXPORT_DIRECTIVE AtomicPtr { +public: + AtomicPtr(void* ptr = 0) : _ptr(ptr) + { } + ~AtomicPtr() + { _ptr = 0; } + + // assigns a new pointer + _OPENTHREADS_ATOMIC_INLINE bool assign(void* ptrNew, const void* const ptrOld); + _OPENTHREADS_ATOMIC_INLINE void* get() const; + +private: + AtomicPtr(const AtomicPtr&); + AtomicPtr& operator=(const AtomicPtr&); + +#if defined(_OPENTHREADS_ATOMIC_USE_MUTEX) + mutable Mutex _mutex; +#endif + void* volatile _ptr; +}; + +#if !defined(_OPENTHREADS_ATOMIC_USE_LIBRARY_ROUTINES) + +_OPENTHREADS_ATOMIC_INLINE unsigned +Atomic::operator++() +{ +#if defined(_OPENTHREADS_ATOMIC_USE_GCC_BUILTINS) + return __sync_add_and_fetch(&_value, 1); +#elif defined(_OPENTHREADS_ATOMIC_USE_MIPOSPRO_BUILTINS) + return __add_and_fetch(&_value, 1); +#elif defined(_OPENTHREADS_ATOMIC_USE_SUN) + return atomic_inc_uint_nv(&_value); +#elif defined(_OPENTHREADS_ATOMIC_USE_MUTEX) + ScopedLock lock(_mutex); + return ++_value; +#else + return ++_value; +#endif +} + +_OPENTHREADS_ATOMIC_INLINE unsigned +Atomic::operator--() +{ +#if defined(_OPENTHREADS_ATOMIC_USE_GCC_BUILTINS) + return __sync_sub_and_fetch(&_value, 1); +#elif defined(_OPENTHREADS_ATOMIC_USE_MIPOSPRO_BUILTINS) + return __sub_and_fetch(&_value, 1); +#elif defined(_OPENTHREADS_ATOMIC_USE_SUN) + return atomic_dec_uint_nv(&_value); +#elif defined(_OPENTHREADS_ATOMIC_USE_MUTEX) + ScopedLock lock(_mutex); + return --_value; +#else + return --_value; +#endif +} + +_OPENTHREADS_ATOMIC_INLINE unsigned +Atomic::AND(unsigned value) +{ +#if defined(_OPENTHREADS_ATOMIC_USE_GCC_BUILTINS) + return __sync_fetch_and_and(&_value, value); +#elif defined(_OPENTHREADS_ATOMIC_USE_MIPOSPRO_BUILTINS) + return __and_and_fetch(&_value, value); +#elif defined(_OPENTHREADS_ATOMIC_USE_SUN) + return atomic_and_uint_nv(&_value, value); +#elif defined(_OPENTHREADS_ATOMIC_USE_MUTEX) + ScopedLock lock(_mutex); + _value &= value; + return _value; +#else + _value &= value; + return _value; +#endif +} + +_OPENTHREADS_ATOMIC_INLINE unsigned +Atomic::OR(unsigned value) +{ +#if defined(_OPENTHREADS_ATOMIC_USE_GCC_BUILTINS) + return __sync_fetch_and_or(&_value, value); +#elif defined(_OPENTHREADS_ATOMIC_USE_MIPOSPRO_BUILTINS) + return __or_and_fetch(&_value, value); +#elif defined(_OPENTHREADS_ATOMIC_USE_SUN) + return atomic_or_uint_nv(&_value, value); +#elif defined(_OPENTHREADS_ATOMIC_USE_MUTEX) + ScopedLock lock(_mutex); + _value |= value; + return _value; +#else + _value |= value; + return _value; +#endif +} + +_OPENTHREADS_ATOMIC_INLINE unsigned +Atomic::XOR(unsigned value) +{ +#if defined(_OPENTHREADS_ATOMIC_USE_GCC_BUILTINS) + return __sync_fetch_and_xor(&_value, value); +#elif defined(_OPENTHREADS_ATOMIC_USE_MIPOSPRO_BUILTINS) + return __xor_and_fetch(&_value, value); +#elif defined(_OPENTHREADS_ATOMIC_USE_SUN) + ScopedLock lock(_mutex); + _value ^= value; + return _value; +#elif defined(_OPENTHREADS_ATOMIC_USE_MUTEX) + ScopedLock lock(_mutex); + _value ^= value; + return _value; +#else + _value ^= value; + return _value; +#endif +} + +_OPENTHREADS_ATOMIC_INLINE unsigned +Atomic::exchange(unsigned value) +{ +#if defined(_OPENTHREADS_ATOMIC_USE_GCC_BUILTINS) + return __sync_lock_test_and_set(&_value, value); +#elif defined(_OPENTHREADS_ATOMIC_USE_MIPOSPRO_BUILTINS) + return __compare_and_swap(&_value, _value, value); +#elif defined(_OPENTHREADS_ATOMIC_USE_SUN) + return atomic_cas_uint(&_value, _value, value); +#elif defined(_OPENTHREADS_ATOMIC_USE_MUTEX) + ScopedLock lock(_mutex); + unsigned oldval = _value; + _value = value; + return oldval; +#else + unsigned oldval = _value; + _value = value; + return oldval; +#endif +} + +_OPENTHREADS_ATOMIC_INLINE +Atomic::operator unsigned() const +{ +#if defined(_OPENTHREADS_ATOMIC_USE_GCC_BUILTINS) + __sync_synchronize(); + return _value; +#elif defined(_OPENTHREADS_ATOMIC_USE_MIPOSPRO_BUILTINS) + __synchronize(); + return _value; +#elif defined(_OPENTHREADS_ATOMIC_USE_SUN) + membar_consumer(); // Hmm, do we need??? + return _value; +#elif defined(_OPENTHREADS_ATOMIC_USE_MUTEX) + ScopedLock lock(_mutex); + return _value; +#else + return _value; +#endif +} + +_OPENTHREADS_ATOMIC_INLINE bool +AtomicPtr::assign(void* ptrNew, const void* const ptrOld) +{ +#if defined(_OPENTHREADS_ATOMIC_USE_GCC_BUILTINS) + return __sync_bool_compare_and_swap(&_ptr, (void *)ptrOld, ptrNew); +#elif defined(_OPENTHREADS_ATOMIC_USE_MIPOSPRO_BUILTINS) + return __compare_and_swap((unsigned long*)&_ptr, (unsigned long)ptrOld, (unsigned long)ptrNew); +#elif defined(_OPENTHREADS_ATOMIC_USE_SUN) + return ptrOld == atomic_cas_ptr(&_ptr, const_cast(ptrOld), ptrNew); +#elif defined(_OPENTHREADS_ATOMIC_USE_MUTEX) + ScopedLock lock(_mutex); + if (_ptr != ptrOld) + return false; + _ptr = ptrNew; + return true; +#else + if (_ptr != ptrOld) + return false; + _ptr = ptrNew; + return true; +#endif +} + +_OPENTHREADS_ATOMIC_INLINE void* +AtomicPtr::get() const +{ +#if defined(_OPENTHREADS_ATOMIC_USE_GCC_BUILTINS) + __sync_synchronize(); + return _ptr; +#elif defined(_OPENTHREADS_ATOMIC_USE_MIPOSPRO_BUILTINS) + __synchronize(); + return _ptr; +#elif defined(_OPENTHREADS_ATOMIC_USE_SUN) + membar_consumer(); // Hmm, do we need??? + return _ptr; +#elif defined(_OPENTHREADS_ATOMIC_USE_MUTEX) + ScopedLock lock(_mutex); + return _ptr; +#else + return _ptr; +#endif +} + +#endif // !defined(_OPENTHREADS_ATOMIC_USE_LIBRARY_ROUTINES) + +} + +#endif // _OPENTHREADS_ATOMIC_ diff --git a/libs/include/android/OpenThreads/Barrier b/libs/include/android/OpenThreads/Barrier new file mode 100755 index 0000000..f15368d --- /dev/null +++ b/libs/include/android/OpenThreads/Barrier @@ -0,0 +1,100 @@ +/* -*-c++-*- OpenThreads library, Copyright (C) 2002 - 2007 The Open Thread Group + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + + +// +// Barrier - C++ barrier class +// ~~~~~~~ +// + +#ifndef _OPENTHREADS_BARRIER_ +#define _OPENTHREADS_BARRIER_ + +#include + +namespace OpenThreads { + + +/** + * @class Barrier + * @brief This class provides an object-oriented thread barrier interface + * + * @warning It is unwise to use the construct "Barrier barrier" in the + * global namespace on sgi's. The object "barrier" + * will confilict with the c-library sproc function "barrier" and + * unpredictable results may occur. You have been warned. + */ +class OPENTHREAD_EXPORT_DIRECTIVE Barrier { + +public: + + /** + * Constructor + */ + Barrier(int numThreads=0); + + /** + * Destructor + */ + virtual ~Barrier(); + + /** + * Reset the barrier to it's original state. + */ + virtual void reset(); + + /** + * Block until numThreads threads have entered the barrier. + */ + virtual void block(unsigned int numThreads=0); + + /** + * Release the barrier, now. + */ + virtual void release(); + + /** + * Return the number of threads currently blocked in the barrier, + * Return -1 if error. + */ + virtual int numThreadsCurrentlyBlocked(); + + + void invalidate(); + +private: + + /** + * Private copy constructor, to prevent tampering. + */ + Barrier(const Barrier &/*b*/) {}; + + /** + * Private copy assignment, to prevent tampering. + */ + Barrier &operator=(const Barrier &/*b*/) {return *(this);}; + + /** + * Implementation-specific private data. + */ + void *_prvData; + + + bool _valid; + +}; + +} + +#endif // !_OPENTHREADS_BARRIER_ + diff --git a/libs/include/android/OpenThreads/Block b/libs/include/android/OpenThreads/Block new file mode 100755 index 0000000..380ed22 --- /dev/null +++ b/libs/include/android/OpenThreads/Block @@ -0,0 +1,177 @@ +/* -*-c++-*- OpenThreads - Copyright (C) 1998-2007 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef _OPENTHREADS_BLOCK_ +#define _OPENTHREADS_BLOCK_ + +#include +#include +#include +#include + +namespace OpenThreads { + +/** Block is a block that can be used to halt a thread that is waiting another thread to release it.*/ +class Block +{ + public: + + Block(): + _released(false) {} + + ~Block() + { + release(); + } + + inline bool block() + { + ScopedLock mutlock(_mut); + if( !_released ) + { + return _cond.wait(&_mut)==0; + } + else + { + return true; + } + } + + inline bool block(unsigned long timeout) + { + ScopedLock mutlock(_mut); + if( !_released ) + { + return _cond.wait(&_mut, timeout)==0; + } + else + { + return true; + } + } + + inline void release() + { + ScopedLock mutlock(_mut); + if (!_released) + { + _released = true; + _cond.broadcast(); + } + } + + inline void reset() + { + ScopedLock mutlock(_mut); + _released = false; + } + + inline void set(bool doRelease) + { + if (doRelease!=_released) + { + if (doRelease) release(); + else reset(); + } + } + + protected: + + Mutex _mut; + Condition _cond; + bool _released; + + private: + + Block(const Block&) {} +}; + +/** BlockCount is a block that can be used to halt a thread that is waiting for a specified number of operations to be completed.*/ +class BlockCount +{ + public: + + BlockCount(unsigned int blockCount): + _blockCount(blockCount), + _currentCount(0) {} + + ~BlockCount() + { + _blockCount = 0; + release(); + } + + inline void completed() + { + OpenThreads::ScopedLock mutlock(_mut); + if (_currentCount>0) + { + --_currentCount; + + if (_currentCount==0) + { + // osg::notify(osg::NOTICE)<<"Released"< mutlock(_mut); + if (_currentCount) + _cond.wait(&_mut); + } + + inline void reset() + { + OpenThreads::ScopedLock mutlock(_mut); + if (_currentCount!=_blockCount) + { + if (_blockCount==0) _cond.broadcast(); + _currentCount = _blockCount; + } + } + + inline void release() + { + OpenThreads::ScopedLock mutlock(_mut); + if (_currentCount) + { + _currentCount = 0; + _cond.broadcast(); + } + } + + inline void setBlockCount(unsigned int blockCount) { _blockCount = blockCount; } + + inline unsigned int getBlockCount() const { return _blockCount; } + + inline unsigned int getCurrentCount() const { return _currentCount; } + + protected: + + OpenThreads::Mutex _mut; + OpenThreads::Condition _cond; + unsigned int _blockCount; + unsigned int _currentCount; + + private: + + BlockCount(const BlockCount&) {} + +}; + +} + +#endif diff --git a/libs/include/android/OpenThreads/Condition b/libs/include/android/OpenThreads/Condition new file mode 100755 index 0000000..cf96635 --- /dev/null +++ b/libs/include/android/OpenThreads/Condition @@ -0,0 +1,93 @@ +/* -*-c++-*- OpenThreads library, Copyright (C) 2002 - 2007 The Open Thread Group + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + + +// +// Condition - C++ condition class +// ~~~~~~~~~ +// + +#ifndef _OPENTHREADS_CONDITION_ +#define _OPENTHREADS_CONDITION_ + +#include +#include + +namespace OpenThreads { + +/** + * @class Condition + * @brief This class provides an object-oriented thread condition interface. + */ +class OPENTHREAD_EXPORT_DIRECTIVE Condition { + +public: + + /** + * Constructor + */ + Condition(); + + /** + * Destructor + */ + virtual ~Condition(); + + /** + * Wait on a mutex. + */ + virtual int wait(Mutex *mutex); + + /** + * Wait on a mutex for a given amount of time (ms) + * + * @return 0 if normal, -1 if errno set, errno code otherwise. + */ + virtual int wait(Mutex *mutex, unsigned long int ms); + + /** + * Signal a SINGLE thread to wake if it's waiting. + * + * @return 0 if normal, -1 if errno set, errno code otherwise. + */ + virtual int signal(); + + /** + * Wake all threads waiting on this condition. + * + * @return 0 if normal, -1 if errno set, errno code otherwise. + */ + virtual int broadcast(); + +private: + + /** + * Private copy constructor, to prevent tampering. + */ + Condition(const Condition &/*c*/) {}; + + /** + * Private copy assignment, to prevent tampering. + */ + Condition &operator=(const Condition &/*c*/) {return *(this);}; + + /** + * Implementation-specific data + */ + void *_prvData; + +}; + +} + +#endif // !_OPENTHREADS_CONDITION_ diff --git a/libs/include/android/OpenThreads/Config b/libs/include/android/OpenThreads/Config new file mode 100755 index 0000000..fd3e646 --- /dev/null +++ b/libs/include/android/OpenThreads/Config @@ -0,0 +1,34 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 2008 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +/**************************************************************************** + * THIS FILE IS AUTOGENERATED BY CMAKE. DO NOT EDIT! + ****************************************************************************/ + +/* Changes to the configuration reflected here can be made with ccmake on + * unix or with cmake-gui on windows. Alternatively you can use cmake's -D + * or -P switches to set some configuration values at cmake configuration time. + */ + +#ifndef _OPENTHREADS_CONFIG +#define _OPENTHREADS_CONFIG + +/* #undef _OPENTHREADS_ATOMIC_USE_GCC_BUILTINS */ +/* #undef _OPENTHREADS_ATOMIC_USE_MIPOSPRO_BUILTINS */ +/* #undef _OPENTHREADS_ATOMIC_USE_SUN */ +/* #undef _OPENTHREADS_ATOMIC_USE_WIN32_INTERLOCKED */ +/* #undef _OPENTHREADS_ATOMIC_USE_BSD_ATOMIC */ +/* #undef _OPENTHREADS_ATOMIC_USE_MUTEX */ +#define OT_LIBRARY_STATIC + +#endif diff --git a/libs/include/android/OpenThreads/Exports b/libs/include/android/OpenThreads/Exports new file mode 100755 index 0000000..9331f0e --- /dev/null +++ b/libs/include/android/OpenThreads/Exports @@ -0,0 +1,44 @@ +/* -*-c++-*- OpenThreads library, Copyright (C) 2002 - 2007 The Open Thread Group + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef _OPENTHREAD_EXPORTS_H_ +#define _OPENTHREAD_EXPORTS_H_ + +#include + +#ifndef WIN32 + #define OPENTHREAD_EXPORT_DIRECTIVE +#else + #if defined( OT_LIBRARY_STATIC ) + #define OPENTHREAD_EXPORT_DIRECTIVE + #elif defined( OPENTHREADS_EXPORTS ) + #define OPENTHREAD_EXPORT_DIRECTIVE __declspec(dllexport) + #else + #define OPENTHREAD_EXPORT_DIRECTIVE __declspec(dllimport) + + #if 0 // Commented out for now + + #ifdef _MSC_VER + #ifdef _DEBUG + #pragma comment(lib ,"OpenThreadsWin32d") + #else + #pragma comment(lib, "OpenThreadsWin32") + #endif + #endif + #endif + #endif +#endif + +#endif + + diff --git a/libs/include/android/OpenThreads/Mutex b/libs/include/android/OpenThreads/Mutex new file mode 100755 index 0000000..b9e8b9c --- /dev/null +++ b/libs/include/android/OpenThreads/Mutex @@ -0,0 +1,100 @@ +/* -*-c++-*- OpenThreads library, Copyright (C) 2002 - 2007 The Open Thread Group + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + + +// +// Mutex - C++ mutex class +// ~~~~~ +// + +#ifndef _OPENTHREADS_MUTEX_ +#define _OPENTHREADS_MUTEX_ + +#include + +namespace OpenThreads { + +/** + * @class Mutex + * @brief This class provides an object-oriented thread mutex interface. + */ +class OPENTHREAD_EXPORT_DIRECTIVE Mutex { + + friend class Condition; + +public: + + enum MutexType + { + MUTEX_NORMAL, + MUTEX_RECURSIVE + }; + + /** + * Constructor + */ + Mutex(MutexType type=MUTEX_NORMAL); + + /** + * Destructor + */ + virtual ~Mutex(); + + + MutexType getMutexType() const { return _mutexType; } + + + /** + * Lock the mutex + * + * @return 0 if normal, -1 if errno set, errno code otherwise. + */ + virtual int lock(); + + /** + * Unlock the mutex + * + * @return 0 if normal, -1 if errno set, errno code otherwise. + */ + virtual int unlock(); + + /** + * Test if mutex can be locked. + * + * @return 0 if normal, -1 if errno set, errno code otherwise. + */ + virtual int trylock(); + +private: + + /** + * Private copy constructor, to prevent tampering. + */ + Mutex(const Mutex &/*m*/) {}; + + /** + * Private copy assignment, to prevent tampering. + */ + Mutex &operator=(const Mutex &/*m*/) {return *(this);}; + + /** + * Implementation-specific private data. + */ + void *_prvData; + MutexType _mutexType; + +}; + +} + +#endif // _OPENTHREADS_MUTEX_ diff --git a/libs/include/android/OpenThreads/ReadWriteMutex b/libs/include/android/OpenThreads/ReadWriteMutex new file mode 100755 index 0000000..a74c075 --- /dev/null +++ b/libs/include/android/OpenThreads/ReadWriteMutex @@ -0,0 +1,114 @@ +/* -*-c++-*- OpenThreads - Copyright (C) 1998-2007 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef _OPENTHREADS_READWRITEMUTEX_ +#define _OPENTHREADS_READWRITEMUTEX_ + +#include +#include + +namespace OpenThreads { + +class ReadWriteMutex +{ + public: + + ReadWriteMutex(): + _readCount(0) {} + + virtual ~ReadWriteMutex() {} + + virtual int readLock() + { + OpenThreads::ScopedLock lock(_readCountMutex); + int result = 0; + if (_readCount==0) + { + result = _readWriteMutex.lock(); + } + ++_readCount; + return result; + } + + + virtual int readUnlock() + { + OpenThreads::ScopedLock lock(_readCountMutex); + int result = 0; + if (_readCount>0) + { + --_readCount; + if (_readCount==0) + { + result = _readWriteMutex.unlock(); + } + } + return result; + } + + virtual int writeLock() + { + return _readWriteMutex.lock(); + } + + virtual int writeUnlock() + { + return _readWriteMutex.unlock(); + } + + protected: + + ReadWriteMutex(const ReadWriteMutex&) {} + ReadWriteMutex& operator = (const ReadWriteMutex&) { return *(this); } + +#if 0 + ReentrantMutex _readWriteMutex; + ReentrantMutex _readCountMutex; +#else + OpenThreads::Mutex _readWriteMutex; + OpenThreads::Mutex _readCountMutex; +#endif + unsigned int _readCount; + +}; + +class ScopedReadLock +{ + public: + + ScopedReadLock(ReadWriteMutex& mutex):_mutex(mutex) { _mutex.readLock(); } + ~ScopedReadLock() { _mutex.readUnlock(); } + + protected: + ReadWriteMutex& _mutex; + + ScopedReadLock& operator = (const ScopedReadLock&) { return *this; } +}; + + +class ScopedWriteLock +{ + public: + + ScopedWriteLock(ReadWriteMutex& mutex):_mutex(mutex) { _mutex.writeLock(); } + ~ScopedWriteLock() { _mutex.writeUnlock(); } + + protected: + ReadWriteMutex& _mutex; + + ScopedWriteLock& operator = (const ScopedWriteLock&) { return *this; } +}; + +} + +#endif diff --git a/libs/include/android/OpenThreads/ReentrantMutex b/libs/include/android/OpenThreads/ReentrantMutex new file mode 100755 index 0000000..84f7315 --- /dev/null +++ b/libs/include/android/OpenThreads/ReentrantMutex @@ -0,0 +1,34 @@ +/* -*-c++-*- OpenThreads - Copyright (C) 1998-2007 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef _OPENTHREADS_REENTRANTMUTEX_ +#define _OPENTHREADS_REENTRANTMUTEX_ + +#include +#include +#include + +namespace OpenThreads { + +class ReentrantMutex : public OpenThreads::Mutex +{ + public: + + ReentrantMutex(): + Mutex(MUTEX_RECURSIVE) {} + +}; + +} + +#endif diff --git a/libs/include/android/OpenThreads/ScopedLock b/libs/include/android/OpenThreads/ScopedLock new file mode 100755 index 0000000..4176f3b --- /dev/null +++ b/libs/include/android/OpenThreads/ScopedLock @@ -0,0 +1,70 @@ +/* -*-c++-*- OpenThreads library, Copyright (C) 2002 - 2007 The Open Thread Group + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + + +// +// ScopedLock and ReverseScopedLock templates +// ~~~~~~~ +// +#ifndef _ScopedLock_ +#define _ScopedLock_ + +namespace OpenThreads{ + +template class ScopedLock +{ + private: + M& m_lock; + ScopedLock(const ScopedLock&); // prevent copy + ScopedLock& operator=(const ScopedLock&); // prevent assign + public: + explicit ScopedLock(M& m):m_lock(m) {m_lock.lock();} + ~ScopedLock(){m_lock.unlock();} +}; + +template class ReverseScopedLock +{ + private: + M& m_lock; + ReverseScopedLock(const ReverseScopedLock&); // prevent copy + ReverseScopedLock& operator=(const ReverseScopedLock&); // prevent assign + public: + explicit ReverseScopedLock(M& m):m_lock(m) {m_lock.unlock();} + ~ReverseScopedLock(){m_lock.lock();} +}; + + +template class ScopedPointerLock +{ + private: + M* m_lock; + ScopedPointerLock(const ScopedPointerLock&); // prevent copy + ScopedPointerLock& operator=(const ScopedPointerLock&); // prevent assign + public: + explicit ScopedPointerLock(M* m):m_lock(m) { if (m_lock) m_lock->lock();} + ~ScopedPointerLock(){ if (m_lock) m_lock->unlock();} +}; + +template class ReverseScopedPointerLock +{ + private: + M* m_lock; + ReverseScopedPointerLock(const ReverseScopedPointerLock&); // prevent copy + ReverseScopedPointerLock& operator=(const ReverseScopedPointerLock&); // prevent assign + public: + explicit ReverseScopedPointerLock(M* m):m_lock(m) { if (m_lock) m_lock->unlock();} + ~ReverseScopedPointerLock(){ if (m_lock) m_lock->lock();} +}; + +} +#endif diff --git a/libs/include/android/OpenThreads/Thread b/libs/include/android/OpenThreads/Thread new file mode 100755 index 0000000..1c13aee --- /dev/null +++ b/libs/include/android/OpenThreads/Thread @@ -0,0 +1,389 @@ +/* -*-c++-*- OpenThreads library, Copyright (C) 2002 - 2007 The Open Thread Group + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + + +// +// Thread - C++ Thread class +// ~~~~~~~~ +// + +#ifndef _OPENTHREADS_THREAD_ +#define _OPENTHREADS_THREAD_ + +#include + +#include + +namespace OpenThreads { + +/** + * Get the number of processors. + * + * Note, systems where no support exists for querrying the number of processors, 1 is returned. + * + */ +extern OPENTHREAD_EXPORT_DIRECTIVE int GetNumberOfProcessors(); + +/** + * Set the processor affinity of current thread. + * + * Note, systems where no support exists no affinity will be set, and -1 will be returned. + * + */ +extern OPENTHREAD_EXPORT_DIRECTIVE int SetProcessorAffinityOfCurrentThread(unsigned int cpunum); + +/** + * @class Thread + * @brief This class provides an object-oriented thread interface. + */ +class OPENTHREAD_EXPORT_DIRECTIVE Thread { + +public: + + /** + * Set the concurrency level for a running application. This method + * only has effect if the pthreads thread model is being used, and + * then only when that model is many-to-one (eg. irix). + * in other cases it is ignored. The concurrency level is only a + * *hint* as to the number of execution vehicles to use, the actual + * implementation may do anything it wants. Setting the value + * to 0 returns things to their default state. + * + * @return previous concurrency level, -1 indicates no-op. + */ + static int SetConcurrency(int concurrencyLevel); + + /** + * Get the concurrency level for a running application. In this + * case, a return code of 0 means that the application is in default + * mode. A return code of -1 means that the application is incapable + * of setting an arbitrary concurrency, because it is a one-to-one + * execution model (sprocs, linuxThreads) + */ + static int GetConcurrency(); + + /** + * Enumerated Type for thread priority + */ + enum ThreadPriority { + + THREAD_PRIORITY_MAX, /**< The maximum possible priority */ + THREAD_PRIORITY_HIGH, /**< A high (but not max) setting */ + THREAD_PRIORITY_NOMINAL, /**< An average priority */ + THREAD_PRIORITY_LOW, /**< A low (but not min) setting */ + THREAD_PRIORITY_MIN, /**< The miniumum possible priority */ + THREAD_PRIORITY_DEFAULT /**< Priority scheduling default */ + + }; + + /** + * Enumerated Type for thread scheduling policy + */ + enum ThreadPolicy { + + THREAD_SCHEDULE_FIFO, /**< First in, First out scheduling */ + THREAD_SCHEDULE_ROUND_ROBIN, /**< Round-robin scheduling (LINUX_DEFAULT) */ + THREAD_SCHEDULE_TIME_SHARE, /**< Time-share scheduling (IRIX DEFAULT) */ + THREAD_SCHEDULE_DEFAULT /**< Default scheduling */ + + }; + + /** + * Constructor + */ + Thread(); + + /** + * Destructor + */ + virtual ~Thread(); + + + /** + * Return a pointer to the current running thread + */ + static Thread *CurrentThread(); + + + /** + * Initialize Threading in a program. This method must be called before + * you can do any threading in a program. + */ + static void Init(); + + /** + * Yield the processor. + * + * @note This method operates on the calling process. And is + * equivalent to calling sched_yield(). + * + * @return 0 if normal, -1 if errno set, errno code otherwise. + */ + static int YieldCurrentThread(); + + /** + * This method will return the ThreadPriority of the master process. + * (ie, the one calling the thread->start() methods for the first time) + * The method will almost certainly return + * Thread::THREAD_PRIORITY_DEFAULT if + * Init() has not been called. + * + * @return the Thread::ThreadPriority of the master thread. + */ + static ThreadPriority GetMasterPriority() {return s_masterThreadPriority;}; + + + /** + * Get a unique thread id. This id is monotonically increasing. + * + * @return a unique thread identifier + */ + int getThreadId(); + + /** + * Get the thread's process id. This is the pthread_t or pid_t value + * depending on the threading model being used. + * + * @return thread process id. + */ + size_t getProcessId(); + + /** + * Start the thread. This method will configure the thread, set + * it's priority, and spawn it. + * + * @note if the stack size specified setStackSize is smaller than the + * smallest allowable stack size, the threads stack size will be set to + * the minimum allowed, and may be retrieved via the getStackSize() + * + * @return 0 if normal, -1 if errno set, errno code otherwise. + */ + int start(); + int startThread(); + + /** + * Test the cancel state of the thread. If the thread has been canceled + * this method will cause the thread to exit now. This method operates + * on the calling thread. + * + * Returns 0 if normal, -1 if called from a thread other that this. + */ + int testCancel(); + + + /** + * Cancel the thread. Equivalent to SIGKILL. + * + * @return 0 if normal, -1 if errno set, errno code otherwise. + */ + virtual int cancel(); + + /** + * Set the thread's schedule priority. This is a complex method. + * Beware of thread priorities when using a many-to-many kernel + * entity implemenation (such as IRIX pthreads). If one is not carefull + * to manage the thread priorities, a priority inversion deadlock can + * easily occur (Although the OpenThreads::Mutex & OpenThreads::Barrier + * constructs have been designed with this senario in mind). Unless + * you have explicit need to set the schedule pirorites for a given + * task, it is best to leave them alone. + * + * @note some implementations (notably LinuxThreads and IRIX Sprocs) + * only alow you to decrease thread priorities dynamically. Thus, + * a lower priority thread will not allow it's priority to be raised + * on the fly. + * + * @note seting the environment variable OUTPUT_THREADLIB_SCHEDULING_INFO + * will output scheduling information for each thread to stdout. + * + * @return 0 if normal, -1 if errno set, errno code otherwise. + */ + int setSchedulePriority(ThreadPriority priority); + + /** + * Get the thread's schedule priority (if able) + * + * @note seting the environment variable OUTPUT_THREADLIB_SCHEDULING_INFO + * will output scheduling information for each thread to stdout. + * + * @return 0 if normal, -1 if errno set, errno code otherwise. + */ + int getSchedulePriority(); + + /** + * Set the thread's scheduling policy (if able) + * + * @note On some implementations (notably IRIX Sprocs & LinuxThreads) + * The policy may prohibit the use of SCHEDULE_ROUND_ROBIN and + * SCHEDULE_FIFO policies - due to their real-time nature, and + * the danger of deadlocking the machine when used as super-user. + * In such cases, the command is a no-op. + * + * @note seting the environment variable OUTPUT_THREADLIB_SCHEDULING_INFO + * will output scheduling information for each thread to stdout. + * + * @return 0 if normal, -1 if errno set, errno code otherwise. + */ + int setSchedulePolicy(ThreadPolicy policy); + + /** + * Get the thread's policy (if able) + * + * @note seting the environment variable OUTPUT_THREADLIB_SCHEDULING_INFO + * will output scheduling information for each thread to stdout. + * + * @return policy if normal, -1 if errno set, errno code otherwise. + */ + int getSchedulePolicy(); + + /** + * Set the thread's desired stack size (in bytes). + * This method is an attribute of the thread and must be called + * *before* the start() method is invoked. + * + * @note a return code of 13 (EACESS) means that the thread stack + * size can no longer be changed. + * + * @return 0 if normal, -1 if errno set, errno code otherwise. + */ + int setStackSize(size_t size); + + /** + * Get the thread's desired stack size. + * + * @return the thread's stack size. 0 indicates that the stack size + * has either not yet been initialized, or not yet been specified by + * the application. + */ + size_t getStackSize(); + + /** + * Print the thread's scheduling information to stdout. + */ + void printSchedulingInfo(); + + /** + * Detach the thread from the calling process. + * + * @return 0 if normal, -1 if errno set, errno code otherwise. + */ + int detach(); + + /** + * Join the calling process with the thread + * + * @return 0 if normal, -1 if errno set, errno code otherwise. + */ + int join(); + + /** + * Disable thread cancelation altogether. Thread::cancel() has no effect. + * + * @return 0 if normal, -1 if errno set, errno code otherwise. + */ + int setCancelModeDisable(); + + /** + * Mark the thread to cancel aysncronously on Thread::cancel(). + * (May not be available with process-level implementations). + * + * @return 0 if normal, -1 if errno set, errno code otherwise. + */ + int setCancelModeAsynchronous(); + + /** + * Mark the thread to cancel at the earliest convenience on + * Thread::cancel() (This is the default) + * + * @return 0 if normal, -1 if errno set, errno code otherwise. + */ + int setCancelModeDeferred(); + + /** + * Query the thread's running status + * + * @return true if running, false if not. + */ + bool isRunning(); + + /** + * Thread's run method. Must be implemented by derived classes. + * This is where the action happens. + */ + virtual void run() = 0; + + /** + * Thread's cancel cleanup routine, called upon cancel(), after the + * cancelation has taken place, but before the thread exits completely. + * This method should be used to repair parts of the thread's data + * that may have been damaged by a pre-mature cancel. No-op by default. + */ + virtual void cancelCleanup() {}; + + void* getImplementation(){ return _prvData; }; + + /** Thread's processor affinity method. This binds a thread to a + * processor whenever possible. This call must be made before + * start() or startThread() and has no effect after the thread + * has been running. In the pthreads implementation, this is only + * implemented on sgi, through a pthread extension. On other pthread + * platforms this is ignored. Returns 0 on success, implementation's + * error on failure, or -1 if ignored. + */ + int setProcessorAffinity( unsigned int cpunum ); + + /** microSleep method, equivilant to the posix usleep(microsec). + * This is not strictly thread API but is used + * so often with threads. It's basically UNIX usleep. Parameter is + * number of microseconds we current thread to sleep. Returns 0 on + * succes, non-zero on failure (UNIX errno or GetLastError() will give + * detailed description. + */ + static int microSleep( unsigned int microsec); + +private: + + /** + * The Private Actions class is allowed to operate on private data. + */ + friend class ThreadPrivateActions; + + /** + * Private copy constructor, to prevent tampering. + */ + Thread(const Thread &/*t*/) {}; + + /** + * Private copy assignment, to prevent tampering. + */ + Thread &operator=(const Thread &/*t*/) {return *(this);}; + + /** + * Implementation-specific data + */ + void * _prvData; + + /** + * Master thread's priority, set by Thread::Init. + */ + static ThreadPriority s_masterThreadPriority; + + /** + * Is initialized flag + */ + static bool s_isInitialized; +}; + +} + +#endif // !_OPENTHREADS_THREAD_ diff --git a/libs/include/android/OpenThreads/Version b/libs/include/android/OpenThreads/Version new file mode 100755 index 0000000..678ba73 --- /dev/null +++ b/libs/include/android/OpenThreads/Version @@ -0,0 +1,38 @@ +/* -*-c++-*- OpenThreads library, Copyright (C) 2002 - 2007 The Open Thread Group + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OPENTHREADS_VERSION +#define OPENTHREADS_VERSION 1 + +#include + +extern "C" { + +#define OPENTHREADS_MAJOR_VERSION 3 +#define OPENTHREADS_MINOR_VERSION 2 +#define OPENTHREADS_PATCH_VERSION 1 +#define OPENTHREADS_SOVERSION 20 + +/** OpenThreadsGetVersion() returns the library version number. + * Numbering convention : OpenThreads-1.0 will return 1.0 from OpenThreadsGetVersion. */ +extern OPENTHREAD_EXPORT_DIRECTIVE const char* OpenThreadsGetVersion(); + +/** The OpenThreadsGetSOVersion() method returns the OpenSceneGraph soversion number. */ +extern OPENTHREAD_EXPORT_DIRECTIVE const char* OpenThreadsGetSOVersion(); + +/** The OpenThreadsGetLibraryName() method returns the library name in human-friendly form. */ +extern OPENTHREAD_EXPORT_DIRECTIVE const char* OpenThreadsGetLibraryName(); + +} + +#endif diff --git a/libs/include/android/cpu-features.h b/libs/include/android/cpu-features.h new file mode 100755 index 0000000..b6bf2ac --- /dev/null +++ b/libs/include/android/cpu-features.h @@ -0,0 +1,182 @@ +/* + * Copyright (C) 2010 The Android Open Source Project + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED + * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ +#ifndef CPU_FEATURES_H +#define CPU_FEATURES_H + +#include +#include + +__BEGIN_DECLS + +typedef enum { + ANDROID_CPU_FAMILY_UNKNOWN = 0, + ANDROID_CPU_FAMILY_ARM, + ANDROID_CPU_FAMILY_X86, + ANDROID_CPU_FAMILY_MIPS, + + ANDROID_CPU_FAMILY_MAX /* do not remove */ + +} AndroidCpuFamily; + +/* Return family of the device's CPU */ +extern AndroidCpuFamily android_getCpuFamily(void); + +/* The list of feature flags for ARM CPUs that can be recognized by the + * library. Value details are: + * + * VFPv2: + * CPU supports the VFPv2 instruction set. Many, but not all, ARMv6 CPUs + * support these instructions. VFPv2 is a subset of VFPv3 so this will + * be set whenever VFPv3 is set too. + * + * ARMv7: + * CPU supports the ARMv7-A basic instruction set. + * This feature is mandated by the 'armeabi-v7a' ABI. + * + * VFPv3: + * CPU supports the VFPv3-D16 instruction set, providing hardware FPU + * support for single and double precision floating point registers. + * Note that only 16 FPU registers are available by default, unless + * the D32 bit is set too. This feature is also mandated by the + * 'armeabi-v7a' ABI. + * + * VFP_D32: + * CPU VFP optional extension that provides 32 FPU registers, + * instead of 16. Note that ARM mandates this feature is the 'NEON' + * feature is implemented by the CPU. + * + * NEON: + * CPU FPU supports "ARM Advanced SIMD" instructions, also known as + * NEON. Note that this mandates the VFP_D32 feature as well, per the + * ARM Architecture specification. + * + * VFP_FP16: + * Half-width floating precision VFP extension. If set, the CPU + * supports instructions to perform floating-point operations on + * 16-bit registers. This is part of the VFPv4 specification, but + * not mandated by any Android ABI. + * + * VFP_FMA: + * Fused multiply-accumulate VFP instructions extension. Also part of + * the VFPv4 specification, but not mandated by any Android ABI. + * + * NEON_FMA: + * Fused multiply-accumulate NEON instructions extension. Optional + * extension from the VFPv4 specification, but not mandated by any + * Android ABI. + * + * IDIV_ARM: + * Integer division available in ARM mode. Only available + * on recent CPUs (e.g. Cortex-A15). + * + * IDIV_THUMB2: + * Integer division available in Thumb-2 mode. Only available + * on recent CPUs (e.g. Cortex-A15). + * + * iWMMXt: + * Optional extension that adds MMX registers and operations to an + * ARM CPU. This is only available on a few XScale-based CPU designs + * sold by Marvell. Pretty rare in practice. + * + * If you want to tell the compiler to generate code that targets one of + * the feature set above, you should probably use one of the following + * flags (for more details, see technical note at the end of this file): + * + * -mfpu=vfp + * -mfpu=vfpv2 + * These are equivalent and tell GCC to use VFPv2 instructions for + * floating-point operations. Use this if you want your code to + * run on *some* ARMv6 devices, and any ARMv7-A device supported + * by Android. + * + * Generated code requires VFPv2 feature. + * + * -mfpu=vfpv3-d16 + * Tell GCC to use VFPv3 instructions (using only 16 FPU registers). + * This should be generic code that runs on any CPU that supports the + * 'armeabi-v7a' Android ABI. Note that no ARMv6 CPU supports this. + * + * Generated code requires VFPv3 feature. + * + * -mfpu=vfpv3 + * Tell GCC to use VFPv3 instructions with 32 FPU registers. + * Generated code requires VFPv3|VFP_D32 features. + * + * -mfpu=neon + * Tell GCC to use VFPv3 instructions with 32 FPU registers, and + * also support NEON intrinsics (see ). + * Generated code requires VFPv3|VFP_D32|NEON features. + * + * -mfpu=vfpv4-d16 + * Generated code requires VFPv3|VFP_FP16|VFP_FMA features. + * + * -mfpu=vfpv4 + * Generated code requires VFPv3|VFP_FP16|VFP_FMA|VFP_D32 features. + * + * -mfpu=neon-vfpv4 + * Generated code requires VFPv3|VFP_FP16|VFP_FMA|VFP_D32|NEON|NEON_FMA + * features. + * + * -mcpu=cortex-a7 + * -mcpu=cortex-a15 + * Generated code requires VFPv3|VFP_FP16|VFP_FMA|VFP_D32| + * NEON|NEON_FMA|IDIV_ARM|IDIV_THUMB2 + * This flag implies -mfpu=neon-vfpv4. + * + * -mcpu=iwmmxt + * Allows the use of iWMMXt instrinsics with GCC. + */ +enum { + ANDROID_CPU_ARM_FEATURE_ARMv7 = (1 << 0), + ANDROID_CPU_ARM_FEATURE_VFPv3 = (1 << 1), + ANDROID_CPU_ARM_FEATURE_NEON = (1 << 2), + ANDROID_CPU_ARM_FEATURE_LDREX_STREX = (1 << 3), + ANDROID_CPU_ARM_FEATURE_VFPv2 = (1 << 4), + ANDROID_CPU_ARM_FEATURE_VFP_D32 = (1 << 5), + ANDROID_CPU_ARM_FEATURE_VFP_FP16 = (1 << 6), + ANDROID_CPU_ARM_FEATURE_VFP_FMA = (1 << 7), + ANDROID_CPU_ARM_FEATURE_NEON_FMA = (1 << 8), + ANDROID_CPU_ARM_FEATURE_IDIV_ARM = (1 << 9), + ANDROID_CPU_ARM_FEATURE_IDIV_THUMB2 = (1 << 10), + ANDROID_CPU_ARM_FEATURE_iWMMXt = (1 << 11), +}; + +enum { + ANDROID_CPU_X86_FEATURE_SSSE3 = (1 << 0), + ANDROID_CPU_X86_FEATURE_POPCNT = (1 << 1), + ANDROID_CPU_X86_FEATURE_MOVBE = (1 << 2), +}; + +extern uint64_t android_getCpuFeatures(void); + +/* Return the number of CPU cores detected on this device. */ +extern int android_getCpuCount(void); + +__END_DECLS + +#endif /* CPU_FEATURES_H */ diff --git a/libs/include/android/jconfig.h b/libs/include/android/jconfig.h new file mode 100755 index 0000000..15a9817 --- /dev/null +++ b/libs/include/android/jconfig.h @@ -0,0 +1,156 @@ +/* android jconfig.h */ +/* + * jconfig.doc + * + * Copyright (C) 1991-1994, Thomas G. Lane. + * This file is part of the Independent JPEG Group's software. + * For conditions of distribution and use, see the accompanying README file. + * + * This file documents the configuration options that are required to + * customize the JPEG software for a particular system. + * + * The actual configuration options for a particular installation are stored + * in jconfig.h. On many machines, jconfig.h can be generated automatically + * or copied from one of the "canned" jconfig files that we supply. But if + * you need to generate a jconfig.h file by hand, this file tells you how. + * + * DO NOT EDIT THIS FILE --- IT WON'T ACCOMPLISH ANYTHING. + * EDIT A COPY NAMED JCONFIG.H. + */ + + +/* + * These symbols indicate the properties of your machine or compiler. + * #define the symbol if yes, #undef it if no. + */ + +/* Does your compiler support function prototypes? + * (If not, you also need to use ansi2knr, see install.doc) + */ +#define HAVE_PROTOTYPES + +/* Does your compiler support the declaration "unsigned char" ? + * How about "unsigned short" ? + */ +#define HAVE_UNSIGNED_CHAR +#define HAVE_UNSIGNED_SHORT + +/* Define "void" as "char" if your compiler doesn't know about type void. + * NOTE: be sure to define void such that "void *" represents the most general + * pointer type, e.g., that returned by malloc(). + */ +/* #define void char */ + +/* Define "const" as empty if your compiler doesn't know the "const" keyword. + */ +/* #define const */ + +/* Define this if an ordinary "char" type is unsigned. + * If you're not sure, leaving it undefined will work at some cost in speed. + * If you defined HAVE_UNSIGNED_CHAR then the speed difference is minimal. + */ +#undef CHAR_IS_UNSIGNED + +/* Define this if your system has an ANSI-conforming file. + */ +#define HAVE_STDDEF_H + +/* Define this if your system has an ANSI-conforming file. + */ +#define HAVE_STDLIB_H + +/* Define this if your system does not have an ANSI/SysV , + * but does have a BSD-style . + */ +#undef NEED_BSD_STRINGS + +/* Define this if your system does not provide typedef size_t in any of the + * ANSI-standard places (stddef.h, stdlib.h, or stdio.h), but places it in + * instead. + */ +#undef NEED_SYS_TYPES_H + +/* For 80x86 machines, you need to define NEED_FAR_POINTERS, + * unless you are using a large-data memory model or 80386 flat-memory mode. + * On less brain-damaged CPUs this symbol must not be defined. + * (Defining this symbol causes large data structures to be referenced through + * "far" pointers and to be allocated with a special version of malloc.) + */ +#undef NEED_FAR_POINTERS + +/* Define this if your linker needs global names to be unique in less + * than the first 15 characters. + */ +#undef NEED_SHORT_EXTERNAL_NAMES + +/* Although a real ANSI C compiler can deal perfectly well with pointers to + * unspecified structures (see "incomplete types" in the spec), a few pre-ANSI + * and pseudo-ANSI compilers get confused. To keep one of these bozos happy, + * define INCOMPLETE_TYPES_BROKEN. This is not recommended unless you + * actually get "missing structure definition" warnings or errors while + * compiling the JPEG code. + */ +#undef INCOMPLETE_TYPES_BROKEN + + +/* + * The following options affect code selection within the JPEG library, + * but they don't need to be visible to applications using the library. + * To minimize application namespace pollution, the symbols won't be + * defined unless JPEG_INTERNALS has been defined. + */ + +#ifdef JPEG_INTERNALS + +/* Define this if your compiler implements ">>" on signed values as a logical + * (unsigned) shift; leave it undefined if ">>" is a signed (arithmetic) shift, + * which is the normal and rational definition. + */ +#undef RIGHT_SHIFT_IS_UNSIGNED + + +#endif /* JPEG_INTERNALS */ + + +/* + * The remaining options do not affect the JPEG library proper, + * but only the sample applications cjpeg/djpeg (see cjpeg.c, djpeg.c). + * Other applications can ignore these. + */ + +#ifdef JPEG_CJPEG_DJPEG + +/* These defines indicate which image (non-JPEG) file formats are allowed. */ + +#define BMP_SUPPORTED /* BMP image file format */ +#define GIF_SUPPORTED /* GIF image file format */ +#define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */ +#undef RLE_SUPPORTED /* Utah RLE image file format */ +#define TARGA_SUPPORTED /* Targa image file format */ + +/* Define this if you want to name both input and output files on the command + * line, rather than using stdout and optionally stdin. You MUST do this if + * your system can't cope with binary I/O to stdin/stdout. See comments at + * head of cjpeg.c or djpeg.c. + */ +#undef TWO_FILE_COMMANDLINE + +/* Define this if your system needs explicit cleanup of temporary files. + * This is crucial under MS-DOS, where the temporary "files" may be areas + * of extended memory; on most other systems it's not as important. + */ +#undef NEED_SIGNAL_CATCHER + +/* By default, we open image files with fopen(...,"rb") or fopen(...,"wb"). + * This is necessary on systems that distinguish text files from binary files, + * and is harmless on most systems that don't. If you have one of the rare + * systems that complains about the "b" spec, define this symbol. + */ +#undef DONT_USE_B_MODE + +/* Define this if you want percent-done progress reports from cjpeg/djpeg. + */ +#undef PROGRESS_REPORT + + +#endif /* JPEG_CJPEG_DJPEG */ diff --git a/libs/include/android/jmorecfg.h b/libs/include/android/jmorecfg.h new file mode 100755 index 0000000..f878ed7 --- /dev/null +++ b/libs/include/android/jmorecfg.h @@ -0,0 +1,402 @@ +/* + * jmorecfg.h + * + * Copyright (C) 1991-1997, Thomas G. Lane. + * This file is part of the Independent JPEG Group's software. + * For conditions of distribution and use, see the accompanying README file. + * + * This file contains additional configuration options that customize the + * JPEG software for special applications or support machine-dependent + * optimizations. Most users will not need to touch this file. + */ + +#ifndef JMORECFG_H +#define JMORECFG_H + +#include + +/* + * Define ANDROID_RGB to enable specific optimizations for Android + * JCS_RGBA_8888 support + * JCS_RGB_565 support + * + */ + +#define ANDROID_RGB + +#ifdef ANDROID_RGB +#define PACK_SHORT_565(r,g,b) ((((r)<<8)&0xf800)|(((g)<<3)&0x7E0)|((b)>>3)) +#define PACK_TWO_PIXELS(l,r) ((r<<16) | l) +#define PACK_NEED_ALIGNMENT(ptr) (((uintptr_t)(ptr))&3) +#define WRITE_TWO_PIXELS(addr, pixels) do { \ + ((INT16*)(addr))[0] = (pixels); \ + ((INT16*)(addr))[1] = (pixels)>>16; \ + } while(0) +#define WRITE_TWO_ALIGNED_PIXELS(addr, pixels) ((*(INT32*)(addr)) = pixels) +#define DITHER_565_R(r, dither) ((r) + ((dither)&0xFF)) +#define DITHER_565_G(g, dither) ((g) + (((dither)&0xFF)>>1)) +#define DITHER_565_B(b, dither) ((b) + ((dither)&0xFF)) +#endif + +/* + * Define BITS_IN_JSAMPLE as either + * 8 for 8-bit sample values (the usual setting) + * 12 for 12-bit sample values + * Only 8 and 12 are legal data precisions for lossy JPEG according to the + * JPEG standard, and the IJG code does not support anything else! + * We do not support run-time selection of data precision, sorry. + */ + +#define BITS_IN_JSAMPLE 8 /* use 8 or 12 */ + + +/* + * Maximum number of components (color channels) allowed in JPEG image. + * To meet the letter of the JPEG spec, set this to 255. However, darn + * few applications need more than 4 channels (maybe 5 for CMYK + alpha + * mask). We recommend 10 as a reasonable compromise; use 4 if you are + * really short on memory. (Each allowed component costs a hundred or so + * bytes of storage, whether actually used in an image or not.) + */ + +#define MAX_COMPONENTS 10 /* maximum number of image components */ + + +/* + * Basic data types. + * You may need to change these if you have a machine with unusual data + * type sizes; for example, "char" not 8 bits, "short" not 16 bits, + * or "long" not 32 bits. We don't care whether "int" is 16 or 32 bits, + * but it had better be at least 16. + */ + +/* Representation of a single sample (pixel element value). + * We frequently allocate large arrays of these, so it's important to keep + * them small. But if you have memory to burn and access to char or short + * arrays is very slow on your hardware, you might want to change these. + */ + +#if BITS_IN_JSAMPLE == 8 +/* JSAMPLE should be the smallest type that will hold the values 0..255. + * You can use a signed char by having GETJSAMPLE mask it with 0xFF. + */ + +#ifdef HAVE_UNSIGNED_CHAR + +typedef uint8_t JSAMPLE; +#define GETJSAMPLE(value) ((int) (value)) + +#else /* not HAVE_UNSIGNED_CHAR */ + +typedef char JSAMPLE; +#ifdef CHAR_IS_UNSIGNED +#define GETJSAMPLE(value) ((int) (value)) +#else +#define GETJSAMPLE(value) ((int) (value) & 0xFF) +#endif /* CHAR_IS_UNSIGNED */ + +#endif /* HAVE_UNSIGNED_CHAR */ + +#define MAXJSAMPLE 255 +#define CENTERJSAMPLE 128 + +#endif /* BITS_IN_JSAMPLE == 8 */ + + +#if BITS_IN_JSAMPLE == 12 +/* JSAMPLE should be the smallest type that will hold the values 0..4095. + * On nearly all machines "short" will do nicely. + */ + +typedef int16_t JSAMPLE; +#define GETJSAMPLE(value) ((int) (value)) + +#define MAXJSAMPLE 4095 +#define CENTERJSAMPLE 2048 + +#endif /* BITS_IN_JSAMPLE == 12 */ + + +/* Representation of a DCT frequency coefficient. + * This should be a signed value of at least 16 bits; "short" is usually OK. + * Again, we allocate large arrays of these, but you can change to int + * if you have memory to burn and "short" is really slow. + */ + +typedef int16_t JCOEF; + + +/* Compressed datastreams are represented as arrays of JOCTET. + * These must be EXACTLY 8 bits wide, at least once they are written to + * external storage. Note that when using the stdio data source/destination + * managers, this is also the data type passed to fread/fwrite. + */ + +#ifdef HAVE_UNSIGNED_CHAR + +typedef uint8_t JOCTET; +#define GETJOCTET(value) (value) + +#else /* not HAVE_UNSIGNED_CHAR */ + +typedef char JOCTET; +#ifdef CHAR_IS_UNSIGNED +#define GETJOCTET(value) (value) +#else +#define GETJOCTET(value) ((value) & 0xFF) +#endif /* CHAR_IS_UNSIGNED */ + +#endif /* HAVE_UNSIGNED_CHAR */ + + +/* These typedefs are used for various table entries and so forth. + * They must be at least as wide as specified; but making them too big + * won't cost a huge amount of memory, so we don't provide special + * extraction code like we did for JSAMPLE. (In other words, these + * typedefs live at a different point on the speed/space tradeoff curve.) + */ + +/* UINT8 must hold at least the values 0..255. */ + +#ifdef HAVE_UNSIGNED_CHAR +typedef uint8_t UINT8; +#else /* not HAVE_UNSIGNED_CHAR */ +#ifdef CHAR_IS_UNSIGNED +typedef char UINT8; +#else /* not CHAR_IS_UNSIGNED */ +typedef short UINT8; +#endif /* CHAR_IS_UNSIGNED */ +#endif /* HAVE_UNSIGNED_CHAR */ + +/* UINT16 must hold at least the values 0..65535. */ + +#ifdef HAVE_UNSIGNED_SHORT +typedef uint16_t UINT16; +#else /* not HAVE_UNSIGNED_SHORT */ +typedef unsigned int UINT16; +#endif /* HAVE_UNSIGNED_SHORT */ + +/* INT16 must hold at least the values -32768..32767. */ + +#ifndef XMD_H /* X11/xmd.h correctly defines INT16 */ +typedef int16_t INT16; +#endif + +/* INT32 must hold at least signed 32-bit values. */ + +#ifndef XMD_H /* X11/xmd.h correctly defines INT32 */ +typedef int32_t INT32; +#endif + +/* Datatype used for image dimensions. The JPEG standard only supports + * images up to 64K*64K due to 16-bit fields in SOF markers. Therefore + * "unsigned int" is sufficient on all machines. However, if you need to + * handle larger images and you don't mind deviating from the spec, you + * can change this datatype. + */ + +typedef unsigned int JDIMENSION; + +#define JPEG_MAX_DIMENSION 65500L /* a tad under 64K to prevent overflows */ + + +/* These macros are used in all function definitions and extern declarations. + * You could modify them if you need to change function linkage conventions; + * in particular, you'll need to do that to make the library a Windows DLL. + * Another application is to make all functions global for use with debuggers + * or code profilers that require it. + */ + +/* a function called through method pointers: */ +#define METHODDEF(type) static type +/* a function used only in its module: */ +#define LOCAL(type) static type +/* a function referenced thru EXTERNs: */ +#define GLOBAL(type) type +/* a reference to a GLOBAL function: */ +#define EXTERN(type) extern type + + +/* This macro is used to declare a "method", that is, a function pointer. + * We want to supply prototype parameters if the compiler can cope. + * Note that the arglist parameter must be parenthesized! + * Again, you can customize this if you need special linkage keywords. + */ + +#ifdef HAVE_PROTOTYPES +#define JMETHOD(type,methodname,arglist) type (*methodname) arglist +#else +#define JMETHOD(type,methodname,arglist) type (*methodname) () +#endif + + +/* Here is the pseudo-keyword for declaring pointers that must be "far" + * on 80x86 machines. Most of the specialized coding for 80x86 is handled + * by just saying "FAR *" where such a pointer is needed. In a few places + * explicit coding is needed; see uses of the NEED_FAR_POINTERS symbol. + */ + +#ifdef NEED_FAR_POINTERS +#define FAR far +#else +#define FAR +#endif + + +/* + * On a few systems, type boolean and/or its values FALSE, TRUE may appear + * in standard header files. Or you may have conflicts with application- + * specific header files that you want to include together with these files. + * Defining HAVE_BOOLEAN before including jpeglib.h should make it work. + */ + +#ifndef HAVE_BOOLEAN +typedef int boolean; +#endif +#ifndef FALSE /* in case these macros already exist */ +#define FALSE 0 /* values of boolean */ +#endif +#ifndef TRUE +#define TRUE 1 +#endif + + +/* + * The remaining options affect code selection within the JPEG library, + * but they don't need to be visible to most applications using the library. + * To minimize application namespace pollution, the symbols won't be + * defined unless JPEG_INTERNALS or JPEG_INTERNAL_OPTIONS has been defined. + */ + +#ifdef JPEG_INTERNALS +#define JPEG_INTERNAL_OPTIONS +#endif + +#ifdef JPEG_INTERNAL_OPTIONS + + +/* + * These defines indicate whether to include various optional functions. + * Undefining some of these symbols will produce a smaller but less capable + * library. Note that you can leave certain source files out of the + * compilation/linking process if you've #undef'd the corresponding symbols. + * (You may HAVE to do that if your compiler doesn't like null source files.) + */ + +/* Arithmetic coding is unsupported for legal reasons. Complaints to IBM. */ + +/* Capability options common to encoder and decoder: */ + +#define DCT_ISLOW_SUPPORTED /* slow but accurate integer algorithm */ +#define DCT_IFAST_SUPPORTED /* faster, less accurate integer method */ +#define DCT_FLOAT_SUPPORTED /* floating-point: accurate, fast on fast HW */ + +/* Encoder capability options: */ + +#undef C_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */ +#define C_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */ +#define C_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/ +#define ENTROPY_OPT_SUPPORTED /* Optimization of entropy coding parms? */ +/* Note: if you selected 12-bit data precision, it is dangerous to turn off + * ENTROPY_OPT_SUPPORTED. The standard Huffman tables are only good for 8-bit + * precision, so jchuff.c normally uses entropy optimization to compute + * usable tables for higher precision. If you don't want to do optimization, + * you'll have to supply different default Huffman tables. + * The exact same statements apply for progressive JPEG: the default tables + * don't work for progressive mode. (This may get fixed, however.) + */ +#define INPUT_SMOOTHING_SUPPORTED /* Input image smoothing option? */ + +/* Decoder capability options: */ + +#undef D_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */ +#define D_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */ +#define D_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/ +#define SAVE_MARKERS_SUPPORTED /* jpeg_save_markers() needed? */ +#define BLOCK_SMOOTHING_SUPPORTED /* Block smoothing? (Progressive only) */ +#define IDCT_SCALING_SUPPORTED /* Output rescaling via IDCT? */ +#undef UPSAMPLE_SCALING_SUPPORTED /* Output rescaling at upsample stage? */ +#define UPSAMPLE_MERGING_SUPPORTED /* Fast path for sloppy upsampling? */ +#define QUANT_1PASS_SUPPORTED /* 1-pass color quantization? */ +#define QUANT_2PASS_SUPPORTED /* 2-pass color quantization? */ + +/* more capability options later, no doubt */ + + +/* + * Ordering of RGB data in scanlines passed to or from the application. + * If your application wants to deal with data in the order B,G,R, just + * change these macros. You can also deal with formats such as R,G,B,X + * (one extra byte per pixel) by changing RGB_PIXELSIZE. Note that changing + * the offsets will also change the order in which colormap data is organized. + * RESTRICTIONS: + * 1. The sample applications cjpeg,djpeg do NOT support modified RGB formats. + * 2. These macros only affect RGB<=>YCbCr color conversion, so they are not + * useful if you are using JPEG color spaces other than YCbCr or grayscale. + * 3. The color quantizer modules will not behave desirably if RGB_PIXELSIZE + * is not 3 (they don't understand about dummy color components!). So you + * can't use color quantization if you change that value. + */ + +#define RGB_RED 0 /* Offset of Red in an RGB scanline element */ +#define RGB_GREEN 1 /* Offset of Green */ +#define RGB_BLUE 2 /* Offset of Blue */ +#ifdef ANDROID_RGB +#define RGB_ALPHA 3 /* Offset of Alpha */ +#endif +#define RGB_PIXELSIZE 3 /* JSAMPLEs per RGB scanline element */ + +/* Definitions for speed-related optimizations. */ + + +/* If your compiler supports inline functions, define INLINE + * as the inline keyword; otherwise define it as empty. + */ + +#ifndef INLINE +#ifdef __GNUC__ /* for instance, GNU C knows about inline */ +#define INLINE __inline__ +#endif +#ifndef INLINE +#define INLINE /* default is to define it as empty */ +#endif +#endif + + +/* On some machines (notably 68000 series) "int" is 32 bits, but multiplying + * two 16-bit shorts is faster than multiplying two ints. Define MULTIPLIER + * as short on such a machine. MULTIPLIER must be at least 16 bits wide. + */ + +#ifndef MULTIPLIER +#ifdef ANDROID_INTELSSE2_IDCT + #define MULTIPLIER short +#elif ANDROID_MIPS_IDCT + #define MULTIPLIER short +#elif NV_ARM_NEON + #define MULTIPLIER short +#else + #define MULTIPLIER int /* type for fastest integer multiply */ +#endif +#endif + + +/* FAST_FLOAT should be either float or double, whichever is done faster + * by your compiler. (Note that this type is only used in the floating point + * DCT routines, so it only matters if you've defined DCT_FLOAT_SUPPORTED.) + * Typically, float is faster in ANSI C compilers, while double is faster in + * pre-ANSI compilers (because they insist on converting to double anyway). + * The code below therefore chooses float if we have ANSI-style prototypes. + */ + +#ifndef FAST_FLOAT +#ifdef HAVE_PROTOTYPES +#define FAST_FLOAT float +#else +#define FAST_FLOAT double +#endif +#endif + +#endif /* JPEG_INTERNAL_OPTIONS */ + +#endif /* JMORECFG_H */ diff --git a/libs/include/android/jpeglib.h b/libs/include/android/jpeglib.h new file mode 100755 index 0000000..07e6872 --- /dev/null +++ b/libs/include/android/jpeglib.h @@ -0,0 +1,1184 @@ +/* + * jpeglib.h + * + * Copyright (C) 1991-1998, Thomas G. Lane. + * This file is part of the Independent JPEG Group's software. + * For conditions of distribution and use, see the accompanying README file. + * + * This file defines the application interface for the JPEG library. + * Most applications using the library need only include this file, + * and perhaps jerror.h if they want to know the exact error codes. + */ + +#ifndef JPEGLIB_H +#define JPEGLIB_H + +/* + * First we include the configuration files that record how this + * installation of the JPEG library is set up. jconfig.h can be + * generated automatically for many systems. jmorecfg.h contains + * manual configuration options that most people need not worry about. + */ + +#ifndef JCONFIG_INCLUDED /* in case jinclude.h already did */ +#include "jconfig.h" /* widely used configuration options */ +#endif +#include "jmorecfg.h" /* seldom changed options */ + + +/* Version ID for the JPEG library. + * Might be useful for tests like "#if JPEG_LIB_VERSION >= 60". + */ + +#define JPEG_LIB_VERSION 62 /* Version 6b */ + + +/* Various constants determining the sizes of things. + * All of these are specified by the JPEG standard, so don't change them + * if you want to be compatible. + */ + +#define DCTSIZE 8 /* The basic DCT block is 8x8 samples */ +#define DCTSIZE2 64 /* DCTSIZE squared; # of elements in a block */ +#define NUM_QUANT_TBLS 4 /* Quantization tables are numbered 0..3 */ +#define NUM_HUFF_TBLS 4 /* Huffman tables are numbered 0..3 */ +#define NUM_ARITH_TBLS 16 /* Arith-coding tables are numbered 0..15 */ +#define MAX_COMPS_IN_SCAN 4 /* JPEG limit on # of components in one scan */ +#define MAX_SAMP_FACTOR 4 /* JPEG limit on sampling factors */ +/* Unfortunately, some bozo at Adobe saw no reason to be bound by the standard; + * the PostScript DCT filter can emit files with many more than 10 blocks/MCU. + * If you happen to run across such a file, you can up D_MAX_BLOCKS_IN_MCU + * to handle it. We even let you do this from the jconfig.h file. However, + * we strongly discourage changing C_MAX_BLOCKS_IN_MCU; just because Adobe + * sometimes emits noncompliant files doesn't mean you should too. + */ +#define C_MAX_BLOCKS_IN_MCU 10 /* compressor's limit on blocks per MCU */ +#ifndef D_MAX_BLOCKS_IN_MCU +#define D_MAX_BLOCKS_IN_MCU 10 /* decompressor's limit on blocks per MCU */ +#endif + + +/* Data structures for images (arrays of samples and of DCT coefficients). + * On 80x86 machines, the image arrays are too big for near pointers, + * but the pointer arrays can fit in near memory. + */ + +typedef JSAMPLE FAR *JSAMPROW; /* ptr to one image row of pixel samples. */ +typedef JSAMPROW *JSAMPARRAY; /* ptr to some rows (a 2-D sample array) */ +typedef JSAMPARRAY *JSAMPIMAGE; /* a 3-D sample array: top index is color */ + +typedef JCOEF JBLOCK[DCTSIZE2]; /* one block of coefficients */ +typedef JBLOCK FAR *JBLOCKROW; /* pointer to one row of coefficient blocks */ +typedef JBLOCKROW *JBLOCKARRAY; /* a 2-D array of coefficient blocks */ +typedef JBLOCKARRAY *JBLOCKIMAGE; /* a 3-D array of coefficient blocks */ + +typedef JCOEF FAR *JCOEFPTR; /* useful in a couple of places */ + + +/* Types for JPEG compression parameters and working tables. */ + + +/* DCT coefficient quantization tables. */ + +typedef struct { + /* This array gives the coefficient quantizers in natural array order + * (not the zigzag order in which they are stored in a JPEG DQT marker). + * CAUTION: IJG versions prior to v6a kept this array in zigzag order. + */ + UINT16 quantval[DCTSIZE2]; /* quantization step for each coefficient */ + /* This field is used only during compression. It's initialized FALSE when + * the table is created, and set TRUE when it's been output to the file. + * You could suppress output of a table by setting this to TRUE. + * (See jpeg_suppress_tables for an example.) + */ + boolean sent_table; /* TRUE when table has been output */ +} JQUANT_TBL; + + +/* Huffman coding tables. */ + +typedef struct { + /* These two fields directly represent the contents of a JPEG DHT marker */ + UINT8 bits[17]; /* bits[k] = # of symbols with codes of */ + /* length k bits; bits[0] is unused */ + UINT8 huffval[256]; /* The symbols, in order of incr code length */ + /* This field is used only during compression. It's initialized FALSE when + * the table is created, and set TRUE when it's been output to the file. + * You could suppress output of a table by setting this to TRUE. + * (See jpeg_suppress_tables for an example.) + */ + boolean sent_table; /* TRUE when table has been output */ +} JHUFF_TBL; + + +/* Basic info about one component (color channel). */ + +typedef struct { + /* These values are fixed over the whole image. */ + /* For compression, they must be supplied by parameter setup; */ + /* for decompression, they are read from the SOF marker. */ + int component_id; /* identifier for this component (0..255) */ + int component_index; /* its index in SOF or cinfo->comp_info[] */ + int h_samp_factor; /* horizontal sampling factor (1..4) */ + int v_samp_factor; /* vertical sampling factor (1..4) */ + int quant_tbl_no; /* quantization table selector (0..3) */ + /* These values may vary between scans. */ + /* For compression, they must be supplied by parameter setup; */ + /* for decompression, they are read from the SOS marker. */ + /* The decompressor output side may not use these variables. */ + int dc_tbl_no; /* DC entropy table selector (0..3) */ + int ac_tbl_no; /* AC entropy table selector (0..3) */ + + /* Remaining fields should be treated as private by applications. */ + + /* These values are computed during compression or decompression startup: */ + /* Component's size in DCT blocks. + * Any dummy blocks added to complete an MCU are not counted; therefore + * these values do not depend on whether a scan is interleaved or not. + */ + JDIMENSION width_in_blocks; + JDIMENSION height_in_blocks; + /* Size of a DCT block in samples. Always DCTSIZE for compression. + * For decompression this is the size of the output from one DCT block, + * reflecting any scaling we choose to apply during the IDCT step. + * Values of 1,2,4,8 are likely to be supported. Note that different + * components may receive different IDCT scalings. + */ + int DCT_scaled_size; + /* The downsampled dimensions are the component's actual, unpadded number + * of samples at the main buffer (preprocessing/compression interface), thus + * downsampled_width = ceil(image_width * Hi/Hmax) + * and similarly for height. For decompression, IDCT scaling is included, so + * downsampled_width = ceil(image_width * Hi/Hmax * DCT_scaled_size/DCTSIZE) + */ + JDIMENSION downsampled_width; /* actual width in samples */ + JDIMENSION downsampled_height; /* actual height in samples */ + /* This flag is used only for decompression. In cases where some of the + * components will be ignored (eg grayscale output from YCbCr image), + * we can skip most computations for the unused components. + */ + boolean component_needed; /* do we need the value of this component? */ + + /* These values are computed before starting a scan of the component. */ + /* The decompressor output side may not use these variables. */ + int MCU_width; /* number of blocks per MCU, horizontally */ + int MCU_height; /* number of blocks per MCU, vertically */ + int MCU_blocks; /* MCU_width * MCU_height */ + int MCU_sample_width; /* MCU width in samples, MCU_width*DCT_scaled_size */ + int last_col_width; /* # of non-dummy blocks across in last MCU */ + int last_row_height; /* # of non-dummy blocks down in last MCU */ + + /* Saved quantization table for component; NULL if none yet saved. + * See jdinput.c comments about the need for this information. + * This field is currently used only for decompression. + */ + JQUANT_TBL * quant_table; + + /* Private per-component storage for DCT or IDCT subsystem. */ + void * dct_table; +} jpeg_component_info; + + +/* The script for encoding a multiple-scan file is an array of these: */ + +typedef struct { + int comps_in_scan; /* number of components encoded in this scan */ + int component_index[MAX_COMPS_IN_SCAN]; /* their SOF/comp_info[] indexes */ + int Ss, Se; /* progressive JPEG spectral selection parms */ + int Ah, Al; /* progressive JPEG successive approx. parms */ +} jpeg_scan_info; + +/* The decompressor can save APPn and COM markers in a list of these: */ + +typedef struct jpeg_marker_struct FAR * jpeg_saved_marker_ptr; + +struct jpeg_marker_struct { + jpeg_saved_marker_ptr next; /* next in list, or NULL */ + UINT8 marker; /* marker code: JPEG_COM, or JPEG_APP0+n */ + unsigned int original_length; /* # bytes of data in the file */ + unsigned int data_length; /* # bytes of data saved at data[] */ + JOCTET FAR * data; /* the data contained in the marker */ + /* the marker length word is not counted in data_length or original_length */ +}; + +/* Known color spaces. */ + +typedef enum { + JCS_UNKNOWN, /* error/unspecified */ + JCS_GRAYSCALE, /* monochrome */ + JCS_RGB, /* red/green/blue */ + JCS_YCbCr, /* Y/Cb/Cr (also known as YUV) */ + JCS_CMYK, /* C/M/Y/K */ + JCS_YCCK, /* Y/Cb/Cr/K */ +#ifdef ANDROID_RGB + JCS_RGBA_8888, /* red/green/blue/alpha */ + JCS_RGB_565 /* red/green/blue in 565 format */ +#endif +} J_COLOR_SPACE; + +/* DCT/IDCT algorithm options. */ + +typedef enum { + JDCT_ISLOW, /* slow but accurate integer algorithm */ + JDCT_IFAST, /* faster, less accurate integer method */ + JDCT_FLOAT /* floating-point: accurate, fast on fast HW */ +} J_DCT_METHOD; + +#ifndef JDCT_DEFAULT /* may be overridden in jconfig.h */ +#define JDCT_DEFAULT JDCT_ISLOW +#endif +#ifndef JDCT_FASTEST /* may be overridden in jconfig.h */ +#define JDCT_FASTEST JDCT_IFAST +#endif + +/* Dithering options for decompression. */ + +typedef enum { + JDITHER_NONE, /* no dithering */ + JDITHER_ORDERED, /* simple ordered dither */ + JDITHER_FS /* Floyd-Steinberg error diffusion dither */ +} J_DITHER_MODE; + + +/* Common fields between JPEG compression and decompression master structs. */ + +#define jpeg_common_fields \ + struct jpeg_error_mgr * err; /* Error handler module */\ + struct jpeg_memory_mgr * mem; /* Memory manager module */\ + struct jpeg_progress_mgr * progress; /* Progress monitor, or NULL if none */\ + void * client_data; /* Available for use by application */\ + boolean is_decompressor; /* So common code can tell which is which */\ + int global_state /* For checking call sequence validity */ + +/* Routines that are to be used by both halves of the library are declared + * to receive a pointer to this structure. There are no actual instances of + * jpeg_common_struct, only of jpeg_compress_struct and jpeg_decompress_struct. + */ +struct jpeg_common_struct { + jpeg_common_fields; /* Fields common to both master struct types */ + /* Additional fields follow in an actual jpeg_compress_struct or + * jpeg_decompress_struct. All three structs must agree on these + * initial fields! (This would be a lot cleaner in C++.) + */ +}; + +typedef struct jpeg_common_struct * j_common_ptr; +typedef struct jpeg_compress_struct * j_compress_ptr; +typedef struct jpeg_decompress_struct * j_decompress_ptr; + + +/* Master record for a compression instance */ + +struct jpeg_compress_struct { + jpeg_common_fields; /* Fields shared with jpeg_decompress_struct */ + + /* Destination for compressed data */ + struct jpeg_destination_mgr * dest; + + /* Description of source image --- these fields must be filled in by + * outer application before starting compression. in_color_space must + * be correct before you can even call jpeg_set_defaults(). + */ + + JDIMENSION image_width; /* input image width */ + JDIMENSION image_height; /* input image height */ + int input_components; /* # of color components in input image */ + J_COLOR_SPACE in_color_space; /* colorspace of input image */ + + double input_gamma; /* image gamma of input image */ + + /* Compression parameters --- these fields must be set before calling + * jpeg_start_compress(). We recommend calling jpeg_set_defaults() to + * initialize everything to reasonable defaults, then changing anything + * the application specifically wants to change. That way you won't get + * burnt when new parameters are added. Also note that there are several + * helper routines to simplify changing parameters. + */ + + int data_precision; /* bits of precision in image data */ + + int num_components; /* # of color components in JPEG image */ + J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */ + + jpeg_component_info * comp_info; + /* comp_info[i] describes component that appears i'th in SOF */ + + JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS]; + /* ptrs to coefficient quantization tables, or NULL if not defined */ + + JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS]; + JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS]; + /* ptrs to Huffman coding tables, or NULL if not defined */ + + UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */ + UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */ + UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */ + + int num_scans; /* # of entries in scan_info array */ + const jpeg_scan_info * scan_info; /* script for multi-scan file, or NULL */ + /* The default value of scan_info is NULL, which causes a single-scan + * sequential JPEG file to be emitted. To create a multi-scan file, + * set num_scans and scan_info to point to an array of scan definitions. + */ + + boolean raw_data_in; /* TRUE=caller supplies downsampled data */ + boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */ + boolean optimize_coding; /* TRUE=optimize entropy encoding parms */ + boolean CCIR601_sampling; /* TRUE=first samples are cosited */ + int smoothing_factor; /* 1..100, or 0 for no input smoothing */ + J_DCT_METHOD dct_method; /* DCT algorithm selector */ + + /* The restart interval can be specified in absolute MCUs by setting + * restart_interval, or in MCU rows by setting restart_in_rows + * (in which case the correct restart_interval will be figured + * for each scan). + */ + unsigned int restart_interval; /* MCUs per restart, or 0 for no restart */ + int restart_in_rows; /* if > 0, MCU rows per restart interval */ + + /* Parameters controlling emission of special markers. */ + + boolean write_JFIF_header; /* should a JFIF marker be written? */ + UINT8 JFIF_major_version; /* What to write for the JFIF version number */ + UINT8 JFIF_minor_version; + /* These three values are not used by the JPEG code, merely copied */ + /* into the JFIF APP0 marker. density_unit can be 0 for unknown, */ + /* 1 for dots/inch, or 2 for dots/cm. Note that the pixel aspect */ + /* ratio is defined by X_density/Y_density even when density_unit=0. */ + UINT8 density_unit; /* JFIF code for pixel size units */ + UINT16 X_density; /* Horizontal pixel density */ + UINT16 Y_density; /* Vertical pixel density */ + boolean write_Adobe_marker; /* should an Adobe marker be written? */ + + /* State variable: index of next scanline to be written to + * jpeg_write_scanlines(). Application may use this to control its + * processing loop, e.g., "while (next_scanline < image_height)". + */ + + JDIMENSION next_scanline; /* 0 .. image_height-1 */ + + /* Remaining fields are known throughout compressor, but generally + * should not be touched by a surrounding application. + */ + + /* + * These fields are computed during compression startup + */ + boolean progressive_mode; /* TRUE if scan script uses progressive mode */ + int max_h_samp_factor; /* largest h_samp_factor */ + int max_v_samp_factor; /* largest v_samp_factor */ + + JDIMENSION total_iMCU_rows; /* # of iMCU rows to be input to coef ctlr */ + /* The coefficient controller receives data in units of MCU rows as defined + * for fully interleaved scans (whether the JPEG file is interleaved or not). + * There are v_samp_factor * DCTSIZE sample rows of each component in an + * "iMCU" (interleaved MCU) row. + */ + + /* + * These fields are valid during any one scan. + * They describe the components and MCUs actually appearing in the scan. + */ + int comps_in_scan; /* # of JPEG components in this scan */ + jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN]; + /* *cur_comp_info[i] describes component that appears i'th in SOS */ + + JDIMENSION MCUs_per_row; /* # of MCUs across the image */ + JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */ + + int blocks_in_MCU; /* # of DCT blocks per MCU */ + int MCU_membership[C_MAX_BLOCKS_IN_MCU]; + /* MCU_membership[i] is index in cur_comp_info of component owning */ + /* i'th block in an MCU */ + + int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */ + + /* + * Links to compression subobjects (methods and private variables of modules) + */ + struct jpeg_comp_master * master; + struct jpeg_c_main_controller * main; + struct jpeg_c_prep_controller * prep; + struct jpeg_c_coef_controller * coef; + struct jpeg_marker_writer * marker; + struct jpeg_color_converter * cconvert; + struct jpeg_downsampler * downsample; + struct jpeg_forward_dct * fdct; + struct jpeg_entropy_encoder * entropy; + jpeg_scan_info * script_space; /* workspace for jpeg_simple_progression */ + int script_space_size; +}; + + +/* Master record for a decompression instance */ + +struct jpeg_decompress_struct { + jpeg_common_fields; /* Fields shared with jpeg_compress_struct */ + + /* Source of compressed data */ + struct jpeg_source_mgr * src; + + /* Basic description of image --- filled in by jpeg_read_header(). */ + /* Application may inspect these values to decide how to process image. */ + + JDIMENSION original_image_width; /* nominal image width (from SOF marker) */ + + JDIMENSION image_width; /* nominal image width (from SOF marker) + may be changed by tile decode */ + JDIMENSION image_height; /* nominal image height */ + int num_components; /* # of color components in JPEG image */ + J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */ + + /* Decompression processing parameters --- these fields must be set before + * calling jpeg_start_decompress(). Note that jpeg_read_header() initializes + * them to default values. + */ + + J_COLOR_SPACE out_color_space; /* colorspace for output */ + + unsigned int scale_num, scale_denom; /* fraction by which to scale image */ + + double output_gamma; /* image gamma wanted in output */ + + boolean buffered_image; /* TRUE=multiple output passes */ + boolean raw_data_out; /* TRUE=downsampled data wanted */ + + J_DCT_METHOD dct_method; /* IDCT algorithm selector */ + boolean do_fancy_upsampling; /* TRUE=apply fancy upsampling */ + boolean do_block_smoothing; /* TRUE=apply interblock smoothing */ + + boolean quantize_colors; /* TRUE=colormapped output wanted */ + /* the following are ignored if not quantize_colors: */ + J_DITHER_MODE dither_mode; /* type of color dithering to use */ + boolean two_pass_quantize; /* TRUE=use two-pass color quantization */ + int desired_number_of_colors; /* max # colors to use in created colormap */ + /* these are significant only in buffered-image mode: */ + boolean enable_1pass_quant; /* enable future use of 1-pass quantizer */ + boolean enable_external_quant;/* enable future use of external colormap */ + boolean enable_2pass_quant; /* enable future use of 2-pass quantizer */ + + /* Description of actual output image that will be returned to application. + * These fields are computed by jpeg_start_decompress(). + * You can also use jpeg_calc_output_dimensions() to determine these values + * in advance of calling jpeg_start_decompress(). + */ + + JDIMENSION output_width; /* scaled image width */ + JDIMENSION output_height; /* scaled image height */ + int out_color_components; /* # of color components in out_color_space */ + int output_components; /* # of color components returned */ + /* output_components is 1 (a colormap index) when quantizing colors; + * otherwise it equals out_color_components. + */ + int rec_outbuf_height; /* min recommended height of scanline buffer */ + /* If the buffer passed to jpeg_read_scanlines() is less than this many rows + * high, space and time will be wasted due to unnecessary data copying. + * Usually rec_outbuf_height will be 1 or 2, at most 4. + */ + + /* When quantizing colors, the output colormap is described by these fields. + * The application can supply a colormap by setting colormap non-NULL before + * calling jpeg_start_decompress; otherwise a colormap is created during + * jpeg_start_decompress or jpeg_start_output. + * The map has out_color_components rows and actual_number_of_colors columns. + */ + int actual_number_of_colors; /* number of entries in use */ + JSAMPARRAY colormap; /* The color map as a 2-D pixel array */ + + /* State variables: these variables indicate the progress of decompression. + * The application may examine these but must not modify them. + */ + + /* Row index of next scanline to be read from jpeg_read_scanlines(). + * Application may use this to control its processing loop, e.g., + * "while (output_scanline < output_height)". + */ + JDIMENSION output_scanline; /* 0 .. output_height-1 */ + + /* Current input scan number and number of iMCU rows completed in scan. + * These indicate the progress of the decompressor input side. + */ + int input_scan_number; /* Number of SOS markers seen so far */ + JDIMENSION input_iMCU_row; /* Number of iMCU rows completed */ + + /* The "output scan number" is the notional scan being displayed by the + * output side. The decompressor will not allow output scan/row number + * to get ahead of input scan/row, but it can fall arbitrarily far behind. + */ + int output_scan_number; /* Nominal scan number being displayed */ + JDIMENSION output_iMCU_row; /* Number of iMCU rows read */ + + /* Current progression status. coef_bits[c][i] indicates the precision + * with which component c's DCT coefficient i (in zigzag order) is known. + * It is -1 when no data has yet been received, otherwise it is the point + * transform (shift) value for the most recent scan of the coefficient + * (thus, 0 at completion of the progression). + * This pointer is NULL when reading a non-progressive file. + */ + int (*coef_bits)[DCTSIZE2]; /* -1 or current Al value for each coef */ + + /* Internal JPEG parameters --- the application usually need not look at + * these fields. Note that the decompressor output side may not use + * any parameters that can change between scans. + */ + + /* Quantization and Huffman tables are carried forward across input + * datastreams when processing abbreviated JPEG datastreams. + */ + + JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS]; + /* ptrs to coefficient quantization tables, or NULL if not defined */ + + JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS]; + JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS]; + /* ptrs to Huffman coding tables, or NULL if not defined */ + + /* These parameters are never carried across datastreams, since they + * are given in SOF/SOS markers or defined to be reset by SOI. + */ + + int data_precision; /* bits of precision in image data */ + + jpeg_component_info * comp_info; + /* comp_info[i] describes component that appears i'th in SOF */ + + boolean tile_decode; /* TRUE if using tile based decoding */ + boolean progressive_mode; /* TRUE if SOFn specifies progressive mode */ + boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */ + + UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */ + UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */ + UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */ + + unsigned int restart_interval; /* MCUs per restart interval, or 0 for no restart */ + + /* These fields record data obtained from optional markers recognized by + * the JPEG library. + */ + boolean saw_JFIF_marker; /* TRUE iff a JFIF APP0 marker was found */ + /* Data copied from JFIF marker; only valid if saw_JFIF_marker is TRUE: */ + UINT8 JFIF_major_version; /* JFIF version number */ + UINT8 JFIF_minor_version; + UINT8 density_unit; /* JFIF code for pixel size units */ + UINT16 X_density; /* Horizontal pixel density */ + UINT16 Y_density; /* Vertical pixel density */ + boolean saw_Adobe_marker; /* TRUE iff an Adobe APP14 marker was found */ + UINT8 Adobe_transform; /* Color transform code from Adobe marker */ + + boolean CCIR601_sampling; /* TRUE=first samples are cosited */ + + /* Aside from the specific data retained from APPn markers known to the + * library, the uninterpreted contents of any or all APPn and COM markers + * can be saved in a list for examination by the application. + */ + jpeg_saved_marker_ptr marker_list; /* Head of list of saved markers */ + + /* Remaining fields are known throughout decompressor, but generally + * should not be touched by a surrounding application. + */ + + /* + * These fields are computed during decompression startup + */ + int max_h_samp_factor; /* largest h_samp_factor */ + int max_v_samp_factor; /* largest v_samp_factor */ + + int min_DCT_scaled_size; /* smallest DCT_scaled_size of any component */ + + JDIMENSION total_iMCU_rows; /* # of iMCU rows in image */ + /* The coefficient controller's input and output progress is measured in + * units of "iMCU" (interleaved MCU) rows. These are the same as MCU rows + * in fully interleaved JPEG scans, but are used whether the scan is + * interleaved or not. We define an iMCU row as v_samp_factor DCT block + * rows of each component. Therefore, the IDCT output contains + * v_samp_factor*DCT_scaled_size sample rows of a component per iMCU row. + */ + + JSAMPLE * sample_range_limit; /* table for fast range-limiting */ + + /* + * These fields are valid during any one scan. + * They describe the components and MCUs actually appearing in the scan. + * Note that the decompressor output side must not use these fields. + */ + int comps_in_scan; /* # of JPEG components in this scan */ + jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN]; + /* *cur_comp_info[i] describes component that appears i'th in SOS */ + + JDIMENSION MCUs_per_row; /* # of MCUs across the image */ + JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */ + + int blocks_in_MCU; /* # of DCT blocks per MCU */ + int MCU_membership[D_MAX_BLOCKS_IN_MCU]; + /* MCU_membership[i] is index in cur_comp_info of component owning */ + /* i'th block in an MCU */ + + int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */ + + /* This field is shared between entropy decoder and marker parser. + * It is either zero or the code of a JPEG marker that has been + * read from the data source, but has not yet been processed. + */ + int unread_marker; + + /* + * Links to decompression subobjects (methods, private variables of modules) + */ + struct jpeg_decomp_master * master; + struct jpeg_d_main_controller * main; + struct jpeg_d_coef_controller * coef; + struct jpeg_d_post_controller * post; + struct jpeg_input_controller * inputctl; + struct jpeg_marker_reader * marker; + struct jpeg_entropy_decoder * entropy; + struct jpeg_inverse_dct * idct; + struct jpeg_upsampler * upsample; + struct jpeg_color_deconverter * cconvert; + struct jpeg_color_quantizer * cquantize; +}; + +typedef struct { + + // |--- byte_offset ---|- bit_left -| + // \------ 27 -------/ \---- 5 ----/ + unsigned int bitstream_offset; + short prev_dc[3]; + + // remaining EOBs in EOBRUN + unsigned short EOBRUN; + + // save the decoder current bit buffer, entropy->bitstate.get_buffer. + INT32 get_buffer; + + // save the restart info. + unsigned short restarts_to_go; + unsigned char next_restart_num; +} huffman_offset_data; + +typedef struct { + + // The header starting position of this scan + unsigned int bitstream_offset; + + // Number of components in this scan + int comps_in_scan; + + // Number of MCUs in each row + int MCUs_per_row; + int MCU_rows_per_iMCU_row; + + // The last MCU position and its dc value in this scan + huffman_offset_data prev_MCU_offset; + + huffman_offset_data **offset; +} huffman_scan_header; + +#define DEFAULT_MCU_SAMPLE_SIZE 16 + +typedef struct { + + // The number of MCUs that we sample each time as an index point + int MCU_sample_size; + + // Number of scan in this image + int scan_count; + + // Number of iMCUs rows in this image + int total_iMCU_rows; + + // Memory used by scan struct + size_t mem_used; + huffman_scan_header *scan; +} huffman_index; + +/* "Object" declarations for JPEG modules that may be supplied or called + * directly by the surrounding application. + * As with all objects in the JPEG library, these structs only define the + * publicly visible methods and state variables of a module. Additional + * private fields may exist after the public ones. + */ + + +/* Error handler object */ + +struct jpeg_error_mgr { + /* Error exit handler: does not return to caller */ + JMETHOD(void, error_exit, (j_common_ptr cinfo)); + /* Conditionally emit a trace or warning message */ + JMETHOD(void, emit_message, (j_common_ptr cinfo, int msg_level)); + /* Routine that actually outputs a trace or error message */ + JMETHOD(void, output_message, (j_common_ptr cinfo)); + /* Format a message string for the most recent JPEG error or message */ + JMETHOD(void, format_message, (j_common_ptr cinfo, char * buffer)); +#define JMSG_LENGTH_MAX 200 /* recommended size of format_message buffer */ + /* Reset error state variables at start of a new image */ + JMETHOD(void, reset_error_mgr, (j_common_ptr cinfo)); + + /* The message ID code and any parameters are saved here. + * A message can have one string parameter or up to 8 int parameters. + */ + int msg_code; +#define JMSG_STR_PARM_MAX 80 + union { + int i[8]; + char s[JMSG_STR_PARM_MAX]; + } msg_parm; + + /* Standard state variables for error facility */ + + int trace_level; /* max msg_level that will be displayed */ + + /* For recoverable corrupt-data errors, we emit a warning message, + * but keep going unless emit_message chooses to abort. emit_message + * should count warnings in num_warnings. The surrounding application + * can check for bad data by seeing if num_warnings is nonzero at the + * end of processing. + */ + long num_warnings; /* number of corrupt-data warnings */ + + /* These fields point to the table(s) of error message strings. + * An application can change the table pointer to switch to a different + * message list (typically, to change the language in which errors are + * reported). Some applications may wish to add additional error codes + * that will be handled by the JPEG library error mechanism; the second + * table pointer is used for this purpose. + * + * First table includes all errors generated by JPEG library itself. + * Error code 0 is reserved for a "no such error string" message. + */ + const char * const * jpeg_message_table; /* Library errors */ + int last_jpeg_message; /* Table contains strings 0..last_jpeg_message */ + /* Second table can be added by application (see cjpeg/djpeg for example). + * It contains strings numbered first_addon_message..last_addon_message. + */ + const char * const * addon_message_table; /* Non-library errors */ + int first_addon_message; /* code for first string in addon table */ + int last_addon_message; /* code for last string in addon table */ +}; + + +/* Progress monitor object */ + +struct jpeg_progress_mgr { + JMETHOD(void, progress_monitor, (j_common_ptr cinfo)); + + long pass_counter; /* work units completed in this pass */ + long pass_limit; /* total number of work units in this pass */ + int completed_passes; /* passes completed so far */ + int total_passes; /* total number of passes expected */ +}; + + +/* Data destination object for compression */ + +struct jpeg_destination_mgr { + JOCTET * next_output_byte; /* => next byte to write in buffer */ + size_t free_in_buffer; /* # of byte spaces remaining in buffer */ + + JMETHOD(void, init_destination, (j_compress_ptr cinfo)); + JMETHOD(boolean, empty_output_buffer, (j_compress_ptr cinfo)); + JMETHOD(void, term_destination, (j_compress_ptr cinfo)); +}; + + +/* Data source object for decompression */ + +struct jpeg_source_mgr { + const JOCTET * next_input_byte; /* => next byte to read from buffer */ + const JOCTET * start_input_byte; /* => first byte to read from input */ + size_t bytes_in_buffer; /* # of bytes remaining in buffer */ + size_t current_offset; /* current readed input offset */ + + JMETHOD(void, init_source, (j_decompress_ptr cinfo)); + JMETHOD(boolean, fill_input_buffer, (j_decompress_ptr cinfo)); + JMETHOD(void, skip_input_data, (j_decompress_ptr cinfo, long num_bytes)); + JMETHOD(boolean, resync_to_restart, (j_decompress_ptr cinfo, int desired)); + JMETHOD(void, term_source, (j_decompress_ptr cinfo)); + JMETHOD(boolean, seek_input_data, (j_decompress_ptr cinfo, long byte_offset)); +}; + + +/* Memory manager object. + * Allocates "small" objects (a few K total), "large" objects (tens of K), + * and "really big" objects (virtual arrays with backing store if needed). + * The memory manager does not allow individual objects to be freed; rather, + * each created object is assigned to a pool, and whole pools can be freed + * at once. This is faster and more convenient than remembering exactly what + * to free, especially where malloc()/free() are not too speedy. + * NB: alloc routines never return NULL. They exit to error_exit if not + * successful. + */ + +#define JPOOL_PERMANENT 0 /* lasts until master record is destroyed */ +#define JPOOL_IMAGE 1 /* lasts until done with image/datastream */ +#define JPOOL_NUMPOOLS 2 + +typedef struct jvirt_sarray_control * jvirt_sarray_ptr; +typedef struct jvirt_barray_control * jvirt_barray_ptr; + + +struct jpeg_memory_mgr { + /* Method pointers */ + JMETHOD(void *, alloc_small, (j_common_ptr cinfo, int pool_id, + size_t sizeofobject)); + JMETHOD(void FAR *, alloc_large, (j_common_ptr cinfo, int pool_id, + size_t sizeofobject)); + JMETHOD(JSAMPARRAY, alloc_sarray, (j_common_ptr cinfo, int pool_id, + JDIMENSION samplesperrow, + JDIMENSION numrows)); + JMETHOD(JBLOCKARRAY, alloc_barray, (j_common_ptr cinfo, int pool_id, + JDIMENSION blocksperrow, + JDIMENSION numrows)); + JMETHOD(jvirt_sarray_ptr, request_virt_sarray, (j_common_ptr cinfo, + int pool_id, + boolean pre_zero, + JDIMENSION samplesperrow, + JDIMENSION numrows, + JDIMENSION maxaccess)); + JMETHOD(jvirt_barray_ptr, request_virt_barray, (j_common_ptr cinfo, + int pool_id, + boolean pre_zero, + JDIMENSION blocksperrow, + JDIMENSION numrows, + JDIMENSION maxaccess)); + JMETHOD(void, realize_virt_arrays, (j_common_ptr cinfo)); + JMETHOD(JSAMPARRAY, access_virt_sarray, (j_common_ptr cinfo, + jvirt_sarray_ptr ptr, + JDIMENSION start_row, + JDIMENSION num_rows, + boolean writable)); + JMETHOD(JBLOCKARRAY, access_virt_barray, (j_common_ptr cinfo, + jvirt_barray_ptr ptr, + JDIMENSION start_row, + JDIMENSION num_rows, + boolean writable)); + JMETHOD(void, free_pool, (j_common_ptr cinfo, int pool_id)); + JMETHOD(void, self_destruct, (j_common_ptr cinfo)); + + /* Limit on memory allocation for this JPEG object. (Note that this is + * merely advisory, not a guaranteed maximum; it only affects the space + * used for virtual-array buffers.) May be changed by outer application + * after creating the JPEG object. + */ + long max_memory_to_use; + + /* Maximum allocation request accepted by alloc_large. */ + long max_alloc_chunk; +}; + + +/* Routine signature for application-supplied marker processing methods. + * Need not pass marker code since it is stored in cinfo->unread_marker. + */ +typedef JMETHOD(boolean, jpeg_marker_parser_method, (j_decompress_ptr cinfo)); + + +/* Declarations for routines called by application. + * The JPP macro hides prototype parameters from compilers that can't cope. + * Note JPP requires double parentheses. + */ + +#ifdef HAVE_PROTOTYPES +#define JPP(arglist) arglist +#else +#define JPP(arglist) () +#endif + + +/* Short forms of external names for systems with brain-damaged linkers. + * We shorten external names to be unique in the first six letters, which + * is good enough for all known systems. + * (If your compiler itself needs names to be unique in less than 15 + * characters, you are out of luck. Get a better compiler.) + */ + +#ifdef NEED_SHORT_EXTERNAL_NAMES +#define jpeg_std_error jStdError +#define jpeg_CreateCompress jCreaCompress +#define jpeg_CreateDecompress jCreaDecompress +#define jpeg_destroy_compress jDestCompress +#define jpeg_destroy_decompress jDestDecompress +#define jpeg_stdio_dest jStdDest +#define jpeg_stdio_src jStdSrc +#define jpeg_set_defaults jSetDefaults +#define jpeg_set_colorspace jSetColorspace +#define jpeg_default_colorspace jDefColorspace +#define jpeg_set_quality jSetQuality +#define jpeg_set_linear_quality jSetLQuality +#define jpeg_add_quant_table jAddQuantTable +#define jpeg_quality_scaling jQualityScaling +#define jpeg_simple_progression jSimProgress +#define jpeg_suppress_tables jSuppressTables +#define jpeg_alloc_quant_table jAlcQTable +#define jpeg_alloc_huff_table jAlcHTable +#define jpeg_start_compress jStrtCompress +#define jpeg_write_scanlines jWrtScanlines +#define jpeg_finish_compress jFinCompress +#define jpeg_write_raw_data jWrtRawData +#define jpeg_write_marker jWrtMarker +#define jpeg_write_m_header jWrtMHeader +#define jpeg_write_m_byte jWrtMByte +#define jpeg_write_tables jWrtTables +#define jpeg_read_header jReadHeader +#define jpeg_start_decompress jStrtDecompress +#define jpeg_read_scanlines jReadScanlines +#define jpeg_finish_decompress jFinDecompress +#define jpeg_read_raw_data jReadRawData +#define jpeg_has_multiple_scans jHasMultScn +#define jpeg_start_output jStrtOutput +#define jpeg_finish_output jFinOutput +#define jpeg_input_complete jInComplete +#define jpeg_new_colormap jNewCMap +#define jpeg_consume_input jConsumeInput +#define jpeg_calc_output_dimensions jCalcDimensions +#define jpeg_save_markers jSaveMarkers +#define jpeg_set_marker_processor jSetMarker +#define jpeg_read_coefficients jReadCoefs +#define jpeg_write_coefficients jWrtCoefs +#define jpeg_copy_critical_parameters jCopyCrit +#define jpeg_abort_compress jAbrtCompress +#define jpeg_abort_decompress jAbrtDecompress +#define jpeg_abort jAbort +#define jpeg_destroy jDestroy +#define jpeg_resync_to_restart jResyncRestart +#endif /* NEED_SHORT_EXTERNAL_NAMES */ + + +/* Default error-management setup */ +EXTERN(struct jpeg_error_mgr *) jpeg_std_error + JPP((struct jpeg_error_mgr * err)); + +/* Initialization of JPEG compression objects. + * jpeg_create_compress() and jpeg_create_decompress() are the exported + * names that applications should call. These expand to calls on + * jpeg_CreateCompress and jpeg_CreateDecompress with additional information + * passed for version mismatch checking. + * NB: you must set up the error-manager BEFORE calling jpeg_create_xxx. + */ +#define jpeg_create_compress(cinfo) \ + jpeg_CreateCompress((cinfo), JPEG_LIB_VERSION, \ + (size_t) sizeof(struct jpeg_compress_struct)) +#define jpeg_create_decompress(cinfo) \ + jpeg_CreateDecompress((cinfo), JPEG_LIB_VERSION, \ + (size_t) sizeof(struct jpeg_decompress_struct)) +EXTERN(void) jpeg_CreateCompress JPP((j_compress_ptr cinfo, + int version, size_t structsize)); +EXTERN(void) jpeg_CreateDecompress JPP((j_decompress_ptr cinfo, + int version, size_t structsize)); +/* Destruction of JPEG compression objects */ +EXTERN(void) jpeg_destroy_compress JPP((j_compress_ptr cinfo)); +EXTERN(void) jpeg_destroy_decompress JPP((j_decompress_ptr cinfo)); + +/* Standard data source and destination managers: stdio streams. */ +/* Caller is responsible for opening the file before and closing after. */ +EXTERN(void) jpeg_stdio_dest JPP((j_compress_ptr cinfo, FILE * outfile)); +EXTERN(void) jpeg_stdio_src JPP((j_decompress_ptr cinfo, FILE * infile)); + +/* Default parameter setup for compression */ +EXTERN(void) jpeg_set_defaults JPP((j_compress_ptr cinfo)); +/* Compression parameter setup aids */ +EXTERN(void) jpeg_set_colorspace JPP((j_compress_ptr cinfo, + J_COLOR_SPACE colorspace)); +EXTERN(void) jpeg_default_colorspace JPP((j_compress_ptr cinfo)); +EXTERN(void) jpeg_set_quality JPP((j_compress_ptr cinfo, int quality, + boolean force_baseline)); +EXTERN(void) jpeg_set_linear_quality JPP((j_compress_ptr cinfo, + int scale_factor, + boolean force_baseline)); +EXTERN(void) jpeg_add_quant_table JPP((j_compress_ptr cinfo, int which_tbl, + const unsigned int *basic_table, + int scale_factor, + boolean force_baseline)); +EXTERN(int) jpeg_quality_scaling JPP((int quality)); +EXTERN(void) jpeg_simple_progression JPP((j_compress_ptr cinfo)); +EXTERN(void) jpeg_suppress_tables JPP((j_compress_ptr cinfo, + boolean suppress)); +EXTERN(JQUANT_TBL *) jpeg_alloc_quant_table JPP((j_common_ptr cinfo)); +EXTERN(JHUFF_TBL *) jpeg_alloc_huff_table JPP((j_common_ptr cinfo)); + +/* Main entry points for compression */ +EXTERN(void) jpeg_start_compress JPP((j_compress_ptr cinfo, + boolean write_all_tables)); +EXTERN(JDIMENSION) jpeg_write_scanlines JPP((j_compress_ptr cinfo, + JSAMPARRAY scanlines, + JDIMENSION num_lines)); +EXTERN(void) jpeg_finish_compress JPP((j_compress_ptr cinfo)); + +/* Replaces jpeg_write_scanlines when writing raw downsampled data. */ +EXTERN(JDIMENSION) jpeg_write_raw_data JPP((j_compress_ptr cinfo, + JSAMPIMAGE data, + JDIMENSION num_lines)); + +/* Write a special marker. See libjpeg.doc concerning safe usage. */ +EXTERN(void) jpeg_write_marker + JPP((j_compress_ptr cinfo, int marker, + const JOCTET * dataptr, unsigned int datalen)); +/* Same, but piecemeal. */ +EXTERN(void) jpeg_write_m_header + JPP((j_compress_ptr cinfo, int marker, unsigned int datalen)); +EXTERN(void) jpeg_write_m_byte + JPP((j_compress_ptr cinfo, int val)); + +/* Alternate compression function: just write an abbreviated table file */ +EXTERN(void) jpeg_write_tables JPP((j_compress_ptr cinfo)); + +/* Decompression startup: read start of JPEG datastream to see what's there */ +EXTERN(int) jpeg_read_header JPP((j_decompress_ptr cinfo, + boolean require_image)); +/* Return value is one of: */ +#define JPEG_SUSPENDED 0 /* Suspended due to lack of input data */ +#define JPEG_HEADER_OK 1 /* Found valid image datastream */ +#define JPEG_HEADER_TABLES_ONLY 2 /* Found valid table-specs-only datastream */ +/* If you pass require_image = TRUE (normal case), you need not check for + * a TABLES_ONLY return code; an abbreviated file will cause an error exit. + * JPEG_SUSPENDED is only possible if you use a data source module that can + * give a suspension return (the stdio source module doesn't). + */ + +/* Main entry points for decompression */ +EXTERN(boolean) jpeg_start_decompress JPP((j_decompress_ptr cinfo)); +EXTERN(boolean) jpeg_start_tile_decompress JPP((j_decompress_ptr cinfo)); +EXTERN(JDIMENSION) jpeg_read_scanlines JPP((j_decompress_ptr cinfo, + JSAMPARRAY scanlines, + JDIMENSION max_lines)); +EXTERN(JDIMENSION) jpeg_read_scanlines_from JPP((j_decompress_ptr cinfo, + JSAMPARRAY scanlines, + int line_offset, + JDIMENSION max_lines)); +EXTERN(JDIMENSION) jpeg_read_tile_scanline JPP((j_decompress_ptr cinfo, + huffman_index *index, + JSAMPARRAY scanlines)); +EXTERN(void) jpeg_init_read_tile_scanline JPP((j_decompress_ptr cinfo, + huffman_index *index, + int *start_x, int *start_y, + int *width, int *height)); +EXTERN(boolean) jpeg_finish_decompress JPP((j_decompress_ptr cinfo)); + +/* Replaces jpeg_read_scanlines when reading raw downsampled data. */ +EXTERN(JDIMENSION) jpeg_read_raw_data JPP((j_decompress_ptr cinfo, + JSAMPIMAGE data, + JDIMENSION max_lines)); + +/* Additional entry points for buffered-image mode. */ +EXTERN(boolean) jpeg_has_multiple_scans JPP((j_decompress_ptr cinfo)); +EXTERN(boolean) jpeg_start_output JPP((j_decompress_ptr cinfo, + int scan_number)); +EXTERN(boolean) jpeg_finish_output JPP((j_decompress_ptr cinfo)); +EXTERN(boolean) jpeg_input_complete JPP((j_decompress_ptr cinfo)); +EXTERN(void) jpeg_new_colormap JPP((j_decompress_ptr cinfo)); +EXTERN(int) jpeg_consume_input JPP((j_decompress_ptr cinfo)); +/* Return value is one of: */ +/* #define JPEG_SUSPENDED 0 Suspended due to lack of input data */ +#define JPEG_REACHED_SOS 1 /* Reached start of new scan */ +#define JPEG_REACHED_EOI 2 /* Reached end of image */ +#define JPEG_ROW_COMPLETED 3 /* Completed one iMCU row */ +#define JPEG_SCAN_COMPLETED 4 /* Completed last iMCU row of a scan */ + +/* Precalculate output dimensions for current decompression parameters. */ +EXTERN(void) jpeg_calc_output_dimensions JPP((j_decompress_ptr cinfo)); + +/* Control saving of COM and APPn markers into marker_list. */ +EXTERN(void) jpeg_save_markers + JPP((j_decompress_ptr cinfo, int marker_code, + unsigned int length_limit)); + +/* Install a special processing method for COM or APPn markers. */ +EXTERN(void) jpeg_set_marker_processor + JPP((j_decompress_ptr cinfo, int marker_code, + jpeg_marker_parser_method routine)); + +/* Read or write raw DCT coefficients --- useful for lossless transcoding. */ +EXTERN(jvirt_barray_ptr *) jpeg_read_coefficients JPP((j_decompress_ptr cinfo)); +EXTERN(boolean) jpeg_build_huffman_index + JPP((j_decompress_ptr cinfo, huffman_index *index)); +EXTERN(void) jpeg_write_coefficients JPP((j_compress_ptr cinfo, + jvirt_barray_ptr * coef_arrays)); +EXTERN(void) jpeg_copy_critical_parameters JPP((j_decompress_ptr srcinfo, + j_compress_ptr dstinfo)); + +/* If you choose to abort compression or decompression before completing + * jpeg_finish_(de)compress, then you need to clean up to release memory, + * temporary files, etc. You can just call jpeg_destroy_(de)compress + * if you're done with the JPEG object, but if you want to clean it up and + * reuse it, call this: + */ +EXTERN(void) jpeg_abort_compress JPP((j_compress_ptr cinfo)); +EXTERN(void) jpeg_abort_decompress JPP((j_decompress_ptr cinfo)); + +/* Generic versions of jpeg_abort and jpeg_destroy that work on either + * flavor of JPEG object. These may be more convenient in some places. + */ +EXTERN(void) jpeg_abort JPP((j_common_ptr cinfo)); +EXTERN(void) jpeg_destroy JPP((j_common_ptr cinfo)); + +/* Default restart-marker-resync procedure for use by data source modules */ +EXTERN(boolean) jpeg_resync_to_restart JPP((j_decompress_ptr cinfo, + int desired)); + +EXTERN(void) jpeg_configure_huffman_decoder(j_decompress_ptr cinfo, + huffman_offset_data offset); +EXTERN(void) jpeg_get_huffman_decoder_configuration(j_decompress_ptr cinfo, + huffman_offset_data *offset); +EXTERN(void) jpeg_create_huffman_index(j_decompress_ptr cinfo, + huffman_index *index); +EXTERN(void) jpeg_configure_huffman_index_scan(j_decompress_ptr cinfo, + huffman_index *index, int scan_no, int offset); +EXTERN(void) jpeg_destroy_huffman_index(huffman_index *index); + + +/* These marker codes are exported since applications and data source modules + * are likely to want to use them. + */ + +#define JPEG_RST0 0xD0 /* RST0 marker code */ +#define JPEG_EOI 0xD9 /* EOI marker code */ +#define JPEG_APP0 0xE0 /* APP0 marker code */ +#define JPEG_COM 0xFE /* COM marker code */ + + +/* If we have a brain-damaged compiler that emits warnings (or worse, errors) + * for structure definitions that are never filled in, keep it quiet by + * supplying dummy definitions for the various substructures. + */ + +#ifdef INCOMPLETE_TYPES_BROKEN +#ifndef JPEG_INTERNALS /* will be defined in jpegint.h */ +struct jvirt_sarray_control { long dummy; }; +struct jvirt_barray_control { long dummy; }; +struct jpeg_comp_master { long dummy; }; +struct jpeg_c_main_controller { long dummy; }; +struct jpeg_c_prep_controller { long dummy; }; +struct jpeg_c_coef_controller { long dummy; }; +struct jpeg_marker_writer { long dummy; }; +struct jpeg_color_converter { long dummy; }; +struct jpeg_downsampler { long dummy; }; +struct jpeg_forward_dct { long dummy; }; +struct jpeg_entropy_encoder { long dummy; }; +struct jpeg_decomp_master { long dummy; }; +struct jpeg_d_main_controller { long dummy; }; +struct jpeg_d_coef_controller { long dummy; }; +struct jpeg_d_post_controller { long dummy; }; +struct jpeg_input_controller { long dummy; }; +struct jpeg_marker_reader { long dummy; }; +struct jpeg_entropy_decoder { long dummy; }; +struct jpeg_inverse_dct { long dummy; }; +struct jpeg_upsampler { long dummy; }; +struct jpeg_color_deconverter { long dummy; }; +struct jpeg_color_quantizer { long dummy; }; +#endif /* JPEG_INTERNALS */ +#endif /* INCOMPLETE_TYPES_BROKEN */ + + +/* + * The JPEG library modules define JPEG_INTERNALS before including this file. + * The internal structure declarations are read only when that is true. + * Applications using the library should not include jpegint.h, but may wish + * to include jerror.h. + */ + +#ifdef JPEG_INTERNALS +#include "jpegint.h" /* fetch private declarations */ +#include "jerror.h" /* fetch error codes too */ +#endif + +#endif /* JPEGLIB_H */ diff --git a/libs/include/android/jversion.h b/libs/include/android/jversion.h new file mode 100755 index 0000000..6472c58 --- /dev/null +++ b/libs/include/android/jversion.h @@ -0,0 +1,14 @@ +/* + * jversion.h + * + * Copyright (C) 1991-1998, Thomas G. Lane. + * This file is part of the Independent JPEG Group's software. + * For conditions of distribution and use, see the accompanying README file. + * + * This file contains software version identification. + */ + + +#define JVERSION "6b 27-Mar-1998" + +#define JCOPYRIGHT "Copyright (C) 1998, Thomas G. Lane" diff --git a/libs/include/android/osg/AlphaFunc b/libs/include/android/osg/AlphaFunc new file mode 100755 index 0000000..f63f50f --- /dev/null +++ b/libs/include/android/osg/AlphaFunc @@ -0,0 +1,102 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_ALPHAFUNC +#define OSG_ALPHAFUNC 1 + +#include + +#ifndef GL_ALPHA_TEST + #define GL_ALPHA_TEST 0x0BC0 +#endif + +namespace osg { + +/** Encapsulates OpenGL glAlphaFunc. +*/ +class OSG_EXPORT AlphaFunc : public StateAttribute +{ + public : + + enum ComparisonFunction { + NEVER = GL_NEVER, + LESS = GL_LESS, + EQUAL = GL_EQUAL, + LEQUAL = GL_LEQUAL, + GREATER = GL_GREATER, + NOTEQUAL = GL_NOTEQUAL, + GEQUAL = GL_GEQUAL, + ALWAYS = GL_ALWAYS + }; + + + AlphaFunc(); + + AlphaFunc(ComparisonFunction func,float ref): + _comparisonFunc(func), + _referenceValue(ref) {} + + /** Copy constructor using CopyOp to manage deep vs shallow copy. */ + AlphaFunc(const AlphaFunc& af,const CopyOp& copyop=CopyOp::SHALLOW_COPY): + StateAttribute(af,copyop), + _comparisonFunc(af._comparisonFunc), + _referenceValue(af._referenceValue) {} + + META_StateAttribute(osg, AlphaFunc,ALPHAFUNC); + + /** Return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs. */ + virtual int compare(const StateAttribute& sa) const + { + // Check for equal types, then create the rhs variable + // used by the COMPARE_StateAttribute_Parameter macros below. + COMPARE_StateAttribute_Types(AlphaFunc,sa) + + // Compare each parameter in turn against the rhs. + COMPARE_StateAttribute_Parameter(_comparisonFunc) + COMPARE_StateAttribute_Parameter(_referenceValue) + + return 0; // Passed all the above comparison macros, so must be equal. + } + + virtual bool getModeUsage(StateAttribute::ModeUsage& usage) const + { + usage.usesMode(GL_ALPHA_TEST); + return true; + } + + inline void setFunction(ComparisonFunction func,float ref) + { + _comparisonFunc = func; + _referenceValue = ref; + } + + inline void setFunction(ComparisonFunction func) { _comparisonFunc=func; } + inline ComparisonFunction getFunction() const { return _comparisonFunc; } + + inline void setReferenceValue(float value) { _referenceValue=value; } + inline float getReferenceValue() const { return _referenceValue; } + + virtual void apply(State& state) const; + + protected: + + virtual ~AlphaFunc(); + + ComparisonFunction _comparisonFunc; + float _referenceValue; + +}; + +} + +#endif diff --git a/libs/include/android/osg/AnimationPath b/libs/include/android/osg/AnimationPath new file mode 100755 index 0000000..f96e530 --- /dev/null +++ b/libs/include/android/osg/AnimationPath @@ -0,0 +1,314 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_ANIMATIONPATH +#define OSG_ANIMATIONPATH 1 + +#include +#include +#include + +#include +#include +#include +#include + +namespace osg { + +/** AnimationPath encapsulates a time varying transformation pathway. Can be + * used for updating camera position and model object position. + * AnimationPathCallback can be attached directly to Transform nodes to + * move subgraphs around the scene. +*/ +class OSG_EXPORT AnimationPath : public virtual osg::Object +{ + public: + + AnimationPath():_loopMode(LOOP) {} + + AnimationPath(const AnimationPath& ap, const CopyOp& copyop=CopyOp::SHALLOW_COPY): + Object(ap,copyop), + _timeControlPointMap(ap._timeControlPointMap), + _loopMode(ap._loopMode) {} + + META_Object(osg,AnimationPath); + + class ControlPoint + { + public: + ControlPoint(): + _scale(1.0,1.0,1.0) {} + + ControlPoint(const osg::Vec3d& position): + _position(position), + _rotation(), + _scale(1.0,1.0,1.0) {} + + ControlPoint(const osg::Vec3d& position, const osg::Quat& rotation): + _position(position), + _rotation(rotation), + _scale(1.0,1.0,1.0) {} + + ControlPoint(const osg::Vec3d& position, const osg::Quat& rotation, const osg::Vec3d& scale): + _position(position), + _rotation(rotation), + _scale(scale) {} + + void setPosition(const osg::Vec3d& position) { _position = position; } + const osg::Vec3d& getPosition() const { return _position; } + + void setRotation(const osg::Quat& rotation) { _rotation = rotation; } + const osg::Quat& getRotation() const { return _rotation; } + + void setScale(const osg::Vec3d& scale) { _scale = scale; } + const osg::Vec3d& getScale() const { return _scale; } + + inline void interpolate(float ratio,const ControlPoint& first, const ControlPoint& second) + { + float one_minus_ratio = 1.0f-ratio; + _position = first._position*one_minus_ratio + second._position*ratio; + _rotation.slerp(ratio,first._rotation,second._rotation); + _scale = first._scale*one_minus_ratio + second._scale*ratio; + } + + inline void interpolate(double ratio,const ControlPoint& first, const ControlPoint& second) + { + double one_minus_ratio = 1.0-ratio; + _position = first._position*one_minus_ratio + second._position*ratio; + _rotation.slerp(ratio,first._rotation,second._rotation); + _scale = first._scale*one_minus_ratio + second._scale*ratio; + } + + inline void getMatrix(Matrixf& matrix) const + { + matrix.makeRotate(_rotation); + matrix.preMultScale(_scale); + matrix.postMultTranslate(_position); + } + + inline void getMatrix(Matrixd& matrix) const + { + matrix.makeRotate(_rotation); + matrix.preMultScale(_scale); + matrix.postMultTranslate(_position); + } + + inline void getInverse(Matrixf& matrix) const + { + matrix.makeRotate(_rotation.inverse()); + matrix.postMultScale(osg::Vec3d(1.0/_scale.x(),1.0/_scale.y(),1.0/_scale.z())); + matrix.preMultTranslate(-_position); + } + + inline void getInverse(Matrixd& matrix) const + { + matrix.makeRotate(_rotation.inverse()); + matrix.postMultScale(osg::Vec3d(1.0/_scale.x(),1.0/_scale.y(),1.0/_scale.z())); + matrix.preMultTranslate(-_position); + } + + protected: + + osg::Vec3d _position; + osg::Quat _rotation; + osg::Vec3d _scale; + + }; + + + /** Given a specific time, return the transformation matrix for a point. */ + bool getMatrix(double time,Matrixf& matrix) const + { + ControlPoint cp; + if (!getInterpolatedControlPoint(time,cp)) return false; + cp.getMatrix(matrix); + return true; + } + + /** Given a specific time, return the transformation matrix for a point. */ + bool getMatrix(double time,Matrixd& matrix) const + { + ControlPoint cp; + if (!getInterpolatedControlPoint(time,cp)) return false; + cp.getMatrix(matrix); + return true; + } + + /** Given a specific time, return the inverse transformation matrix for a point. */ + bool getInverse(double time,Matrixf& matrix) const + { + ControlPoint cp; + if (!getInterpolatedControlPoint(time,cp)) return false; + cp.getInverse(matrix); + return true; + } + + bool getInverse(double time,Matrixd& matrix) const + { + ControlPoint cp; + if (!getInterpolatedControlPoint(time,cp)) return false; + cp.getInverse(matrix); + return true; + } + + /** Given a specific time, return the local ControlPoint frame for a point. */ + virtual bool getInterpolatedControlPoint(double time,ControlPoint& controlPoint) const; + + /** Insert a control point into the AnimationPath.*/ + void insert(double time,const ControlPoint& controlPoint); + + double getFirstTime() const { if (!_timeControlPointMap.empty()) return _timeControlPointMap.begin()->first; else return 0.0;} + double getLastTime() const { if (!_timeControlPointMap.empty()) return _timeControlPointMap.rbegin()->first; else return 0.0;} + double getPeriod() const { return getLastTime()-getFirstTime();} + + enum LoopMode + { + SWING, + LOOP, + NO_LOOPING + }; + + void setLoopMode(LoopMode lm) { _loopMode = lm; } + + LoopMode getLoopMode() const { return _loopMode; } + + + typedef std::map TimeControlPointMap; + + void setTimeControlPointMap(TimeControlPointMap& tcpm) { _timeControlPointMap=tcpm; } + + TimeControlPointMap& getTimeControlPointMap() { return _timeControlPointMap; } + + const TimeControlPointMap& getTimeControlPointMap() const { return _timeControlPointMap; } + + bool empty() const { return _timeControlPointMap.empty(); } + + void clear() { _timeControlPointMap.clear(); } + + /** Read the animation path from a flat ASCII file stream. */ + void read(std::istream& in); + + /** Write the animation path to a flat ASCII file stream. */ + void write(std::ostream& out) const; + + /** Write the control point to a flat ASCII file stream. */ + void write(TimeControlPointMap::const_iterator itr, std::ostream& out) const; + + protected: + + virtual ~AnimationPath() {} + + TimeControlPointMap _timeControlPointMap; + LoopMode _loopMode; + +}; + + +class OSG_EXPORT AnimationPathCallback : public NodeCallback +{ + public: + + AnimationPathCallback(): + _pivotPoint(0.0,0.0,0.0), + _useInverseMatrix(false), + _timeOffset(0.0), + _timeMultiplier(1.0), + _firstTime(DBL_MAX), + _latestTime(0.0), + _pause(false), + _pauseTime(0.0) {} + + AnimationPathCallback(const AnimationPathCallback& apc,const CopyOp& copyop): + NodeCallback(apc,copyop), + _animationPath(apc._animationPath), + _pivotPoint(apc._pivotPoint), + _useInverseMatrix(apc._useInverseMatrix), + _timeOffset(apc._timeOffset), + _timeMultiplier(apc._timeMultiplier), + _firstTime(apc._firstTime), + _latestTime(apc._latestTime), + _pause(apc._pause), + _pauseTime(apc._pauseTime) {} + + + META_Object(osg,AnimationPathCallback); + + /** Construct an AnimationPathCallback with a specified animation path.*/ + AnimationPathCallback(AnimationPath* ap,double timeOffset=0.0,double timeMultiplier=1.0): + _animationPath(ap), + _pivotPoint(0.0,0.0,0.0), + _useInverseMatrix(false), + _timeOffset(timeOffset), + _timeMultiplier(timeMultiplier), + _firstTime(DBL_MAX), + _latestTime(0.0), + _pause(false), + _pauseTime(0.0) {} + + /** Construct an AnimationPathCallback and automatically create an animation path to produce a rotation about a point.*/ + AnimationPathCallback(const osg::Vec3d& pivot,const osg::Vec3d& axis,float angularVelocity); + + + void setAnimationPath(AnimationPath* path) { _animationPath = path; } + AnimationPath* getAnimationPath() { return _animationPath.get(); } + const AnimationPath* getAnimationPath() const { return _animationPath.get(); } + + inline void setPivotPoint(const Vec3d& pivot) { _pivotPoint = pivot; } + inline const Vec3d& getPivotPoint() const { return _pivotPoint; } + + void setUseInverseMatrix(bool useInverseMatrix) { _useInverseMatrix = useInverseMatrix; } + bool getUseInverseMatrix() const { return _useInverseMatrix; } + + void setTimeOffset(double offset) { _timeOffset = offset; } + double getTimeOffset() const { return _timeOffset; } + + void setTimeMultiplier(double multiplier) { _timeMultiplier = multiplier; } + double getTimeMultiplier() const { return _timeMultiplier; } + + + virtual void reset(); + + void setPause(bool pause); + bool getPause() const { return _pause; } + + /** Get the animation time that is used to specify the position along + * the AnimationPath. Animation time is computed from the formula: + * ((_latestTime-_firstTime)-_timeOffset)*_timeMultiplier.*/ + virtual double getAnimationTime() const; + + /** Implements the callback. */ + virtual void operator()(Node* node, NodeVisitor* nv); + + void update(osg::Node& node); + + public: + + ref_ptr _animationPath; + osg::Vec3d _pivotPoint; + bool _useInverseMatrix; + double _timeOffset; + double _timeMultiplier; + double _firstTime; + double _latestTime; + bool _pause; + double _pauseTime; + + protected: + + ~AnimationPathCallback(){} + +}; + +} + +#endif diff --git a/libs/include/android/osg/ApplicationUsage b/libs/include/android/osg/ApplicationUsage new file mode 100755 index 0000000..fb6866e --- /dev/null +++ b/libs/include/android/osg/ApplicationUsage @@ -0,0 +1,124 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_APPLICATIONUSAGE +#define OSG_APPLICATIONUSAGE 1 + +#include + +#include +#include +#include + +namespace osg { + +class OSG_EXPORT ApplicationUsage : public osg::Referenced +{ + public: + + static ApplicationUsage* instance(); + + ApplicationUsage() {} + + ApplicationUsage(const std::string& commandLineUsage); + + typedef std::map UsageMap; + + + /** The ApplicationName is often displayed when logging errors, and frequently incorporated into the Description (below). */ + void setApplicationName(const std::string& name) { _applicationName = name; } + const std::string& getApplicationName() const { return _applicationName; } + + /** If non-empty, the Description is typically shown by the Help Handler + * as text on the Help display (which also lists keyboard abbreviations. */ + void setDescription(const std::string& desc) { _description = desc; } + const std::string& getDescription() const { return _description; } + + enum Type + { + NO_HELP = 0x0, + COMMAND_LINE_OPTION = 0x1, + ENVIRONMENTAL_VARIABLE = 0x2, + KEYBOARD_MOUSE_BINDING = 0x4, + HELP_ALL = KEYBOARD_MOUSE_BINDING|ENVIRONMENTAL_VARIABLE|COMMAND_LINE_OPTION + }; + + void addUsageExplanation(Type type,const std::string& option,const std::string& explanation); + + void setCommandLineUsage(const std::string& explanation) { _commandLineUsage=explanation; } + const std::string& getCommandLineUsage() const { return _commandLineUsage; } + + + void addCommandLineOption(const std::string& option,const std::string& explanation, const std::string &defaultValue = ""); + + void setCommandLineOptions(const UsageMap& usageMap) { _commandLineOptions=usageMap; } + const UsageMap& getCommandLineOptions() const { return _commandLineOptions; } + + void setCommandLineOptionsDefaults(const UsageMap& usageMap) { _commandLineOptionsDefaults=usageMap; } + const UsageMap& getCommandLineOptionsDefaults() const { return _commandLineOptionsDefaults; } + + + void addEnvironmentalVariable(const std::string& option,const std::string& explanation, const std::string& defaultValue = ""); + + void setEnvironmentalVariables(const UsageMap& usageMap) { _environmentalVariables=usageMap; } + const UsageMap& getEnvironmentalVariables() const { return _environmentalVariables; } + + void setEnvironmentalVariablesDefaults(const UsageMap& usageMap) { _environmentalVariablesDefaults=usageMap; } + const UsageMap& getEnvironmentalVariablesDefaults() const { return _environmentalVariablesDefaults; } + + + void addKeyboardMouseBinding(const std::string& prefix, int key, const std::string& explanation); + void addKeyboardMouseBinding(int key, const std::string& explanation); + void addKeyboardMouseBinding(const std::string& option,const std::string& explanation); + + void setKeyboardMouseBindings(const UsageMap& usageMap) { _keyboardMouse=usageMap; } + const UsageMap& getKeyboardMouseBindings() const { return _keyboardMouse; } + + + void getFormattedString(std::string& str, const UsageMap& um,unsigned int widthOfOutput=80,bool showDefaults=false,const UsageMap& ud=UsageMap()); + + void write(std::ostream& output,const UsageMap& um,unsigned int widthOfOutput=80,bool showDefaults=false,const UsageMap& ud=UsageMap()); + + void write(std::ostream& output,unsigned int type=COMMAND_LINE_OPTION, unsigned int widthOfOutput=80,bool showDefaults=false); + + void writeEnvironmentSettings(std::ostream& output); + + protected: + + virtual ~ApplicationUsage() {} + + std::string _applicationName; + std::string _description; + std::string _commandLineUsage; + UsageMap _commandLineOptions; + UsageMap _environmentalVariables; + UsageMap _keyboardMouse; + UsageMap _environmentalVariablesDefaults; + UsageMap _commandLineOptionsDefaults; + +}; + +class ApplicationUsageProxy +{ + public: + + /** register an explanation of commandline/environmentvariable/keyboard mouse usage.*/ + ApplicationUsageProxy(ApplicationUsage::Type type,const std::string& option,const std::string& explanation) + { + ApplicationUsage::instance()->addUsageExplanation(type,option,explanation); + } +}; + +} + +#endif diff --git a/libs/include/android/osg/ArgumentParser b/libs/include/android/osg/ArgumentParser new file mode 100755 index 0000000..21b8ca3 --- /dev/null +++ b/libs/include/android/osg/ArgumentParser @@ -0,0 +1,213 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_ARGUMENTPARSER +#define OSG_ARGUMENTPARSER 1 + +#include +#include +#include + +#include +#include +#include + +namespace osg { + +class OSG_EXPORT ArgumentParser +{ + public: + + class OSG_EXPORT Parameter + { + public: + enum ParameterType + { + BOOL_PARAMETER, + FLOAT_PARAMETER, + DOUBLE_PARAMETER, + INT_PARAMETER, + UNSIGNED_INT_PARAMETER, + STRING_PARAMETER + }; + + union ValueUnion + { + bool* _bool; + float* _float; + double* _double; + int* _int; + unsigned int* _uint; + std::string* _string; + }; + + Parameter(bool& value) { _type = BOOL_PARAMETER; _value._bool = &value; } + + Parameter(float& value) { _type = FLOAT_PARAMETER; _value._float = &value; } + + Parameter(double& value) { _type = DOUBLE_PARAMETER; _value._double = &value; } + + Parameter(int& value) { _type = INT_PARAMETER; _value._int = &value; } + + Parameter(unsigned int& value) { _type = UNSIGNED_INT_PARAMETER; _value._uint = &value; } + + Parameter(std::string& value) { _type = STRING_PARAMETER; _value._string = &value; } + + Parameter(const Parameter& param) { _type = param._type; _value = param._value; } + + Parameter& operator = (const Parameter& param) { _type = param._type; _value = param._value; return *this; } + + bool valid(const char* str) const; + bool assign(const char* str); + + protected: + + ParameterType _type; + ValueUnion _value; + }; + + /** Return true if the specified string is an option in the form + * -option or --option. */ + static bool isOption(const char* str); + + /** Return true if string is non-NULL and not an option in the form + * -option or --option. */ + static bool isString(const char* str); + + /** Return true if specified parameter is a number. */ + static bool isNumber(const char* str); + + /** Return true if specified parameter is a bool. */ + static bool isBool(const char* str); + + public: + + ArgumentParser(int* argc,char **argv); + + void setApplicationUsage(ApplicationUsage* usage) { _usage = usage; } + ApplicationUsage* getApplicationUsage() { return _usage.get(); } + const ApplicationUsage* getApplicationUsage() const { return _usage.get(); } + + /** Return the argument count. */ + int& argc() { return *_argc; } + + /** Return the argument array. */ + char** argv() { return _argv; } + + /** Return the char* argument at the specified position. */ + char* operator [] (int pos) { return _argv[pos]; } + + /** Return the const char* argument at the specified position. */ + const char* operator [] (int pos) const { return _argv[pos]; } + + /** Return the application name, as specified by argv[0] */ + std::string getApplicationName() const; + + /** Return the position of an occurrence of a string in the argument list. + * Return -1 if no string is found. */ + int find(const std::string& str) const; + + /** Return true if the specified parameter is an option in the form of + * -option or --option. */ + bool isOption(int pos) const; + + /** Return true if the specified parameter is a string not in + * the form of an option. */ + bool isString(int pos) const; + + /** Return true if the specified parameter is a number. */ + bool isNumber(int pos) const; + + bool containsOptions() const; + + /** Remove one or more arguments from the argv argument list, + * and decrement the argc respectively. */ + void remove(int pos,int num=1); + + /** Return true if the specified argument matches the given string. */ + bool match(int pos, const std::string& str) const; + + /** Search for an occurrence of a string in the argument list. If found, + * remove that occurrence and return true. Otherwise, return false. */ + bool read(const std::string& str); + bool read(const std::string& str, Parameter value1); + bool read(const std::string& str, Parameter value1, Parameter value2); + bool read(const std::string& str, Parameter value1, Parameter value2, Parameter value3); + bool read(const std::string& str, Parameter value1, Parameter value2, Parameter value3, Parameter value4); + bool read(const std::string& str, Parameter value1, Parameter value2, Parameter value3, Parameter value4, Parameter value5); + bool read(const std::string& str, Parameter value1, Parameter value2, Parameter value3, Parameter value4, Parameter value5, Parameter value6); + bool read(const std::string& str, Parameter value1, Parameter value2, Parameter value3, Parameter value4, Parameter value5, Parameter value6, Parameter value7); + bool read(const std::string& str, Parameter value1, Parameter value2, Parameter value3, Parameter value4, Parameter value5, Parameter value6, Parameter value7, Parameter value8); + + + /** If the argument value at the specified position matches the given string, + * and subsequent parameters are also matched, then set the parameter values, + * remove the arguments from the list, and return true. Otherwise, return false. */ + bool read(int pos, const std::string& str); + bool read(int pos, const std::string& str, Parameter value1); + bool read(int pos, const std::string& str, Parameter value1, Parameter value2); + bool read(int pos, const std::string& str, Parameter value1, Parameter value2, Parameter value3); + bool read(int pos, const std::string& str, Parameter value1, Parameter value2, Parameter value3, Parameter value4); + bool read(int pos, const std::string& str, Parameter value1, Parameter value2, Parameter value3, Parameter value4, Parameter value5); + bool read(int pos, const std::string& str, Parameter value1, Parameter value2, Parameter value3, Parameter value4, Parameter value5, Parameter value6); + bool read(int pos, const std::string& str, Parameter value1, Parameter value2, Parameter value3, Parameter value4, Parameter value5, Parameter value6, Parameter value7); + bool read(int pos, const std::string& str, Parameter value1, Parameter value2, Parameter value3, Parameter value4, Parameter value5, Parameter value6, Parameter value7, Parameter value8); + + + enum ErrorSeverity + { + BENIGN = 0, + CRITICAL = 1 + }; + + typedef std::map ErrorMessageMap; + + /** Return the error flag, true if an error has occurred when reading arguments. */ + bool errors(ErrorSeverity severity=BENIGN) const; + + /** Report an error message by adding to the ErrorMessageMap. */ + void reportError(const std::string& message,ErrorSeverity severity=CRITICAL); + + /** For each remaining option, report it as unrecognized. */ + void reportRemainingOptionsAsUnrecognized(ErrorSeverity severity=BENIGN); + + /** Return the error message, if any has occurred. */ + ErrorMessageMap& getErrorMessageMap() { return _errorMessageMap; } + + /** Return the error message, if any has occurred. */ + const ErrorMessageMap& getErrorMessageMap() const { return _errorMessageMap; } + + /** Write error messages to the given ostream, if at or above the given severity. */ + void writeErrorMessages(std::ostream& output,ErrorSeverity sevrity=BENIGN); + + + /** This convenience method handles help requests on the command line. + * Return the type(s) of help requested. The return value of this + * function is suitable for passing into getApplicationUsage()->write(). + * If ApplicationUsage::NO_HELP is returned then no help commandline option + * was found on the command line. */ + ApplicationUsage::Type readHelpType(); + + + protected: + + int* _argc; + char** _argv; + ErrorMessageMap _errorMessageMap; + ref_ptr _usage; + +}; + +} + +#endif diff --git a/libs/include/android/osg/Array b/libs/include/android/osg/Array new file mode 100755 index 0000000..3c82063 --- /dev/null +++ b/libs/include/android/osg/Array @@ -0,0 +1,685 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_ARRAY +#define OSG_ARRAY 1 + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include + +namespace osg { + +class ArrayVisitor; +class ConstArrayVisitor; + +class ValueVisitor; +class ConstValueVisitor; + +class OSG_EXPORT Array : public BufferData +{ + + public: + + enum Type + { + ArrayType = 0, + + ByteArrayType = 1, + ShortArrayType = 2, + IntArrayType = 3, + + UByteArrayType = 4, + UShortArrayType = 5, + UIntArrayType = 6, + + FloatArrayType = 7, + DoubleArrayType = 8, + + Vec2bArrayType = 9, + Vec3bArrayType = 10, + Vec4bArrayType = 11, + + Vec2sArrayType = 12, + Vec3sArrayType = 13, + Vec4sArrayType = 14, + + Vec2iArrayType = 15, + Vec3iArrayType = 16, + Vec4iArrayType = 17, + + Vec2ubArrayType = 18, + Vec3ubArrayType = 19, + Vec4ubArrayType = 20, + + Vec2usArrayType = 21, + Vec3usArrayType = 22, + Vec4usArrayType = 23, + + Vec2uiArrayType = 24, + Vec3uiArrayType = 25, + Vec4uiArrayType = 26, + + Vec2ArrayType = 27, + Vec3ArrayType = 28, + Vec4ArrayType = 29, + + Vec2dArrayType = 30, + Vec3dArrayType = 31, + Vec4dArrayType = 32, + + MatrixArrayType = 33, + MatrixdArrayType = 34 + }; + + enum Binding + { + BIND_UNDEFINED=-1, + BIND_OFF=0, + BIND_OVERALL=1, + BIND_PER_PRIMITIVE_SET=2, + BIND_PER_VERTEX=4 + }; + + Array(Type arrayType=ArrayType,GLint dataSize=0,GLenum dataType=0, Binding binding=BIND_UNDEFINED): + _arrayType(arrayType), + _dataSize(dataSize), + _dataType(dataType), + _binding(binding), + _normalize(false), + _preserveDataType(false) {} + + Array(const Array& array,const CopyOp& copyop=CopyOp::SHALLOW_COPY): + BufferData(array,copyop), + _arrayType(array._arrayType), + _dataSize(array._dataSize), + _dataType(array._dataType), + _binding(array._binding), + _normalize(array._normalize), + _preserveDataType(array._preserveDataType) {} + + virtual bool isSameKindAs(const Object* obj) const { return dynamic_cast(obj)!=NULL; } + virtual const char* libraryName() const { return "osg"; } + virtual const char* className() const; + + virtual void accept(ArrayVisitor&) = 0; + virtual void accept(ConstArrayVisitor&) const = 0; + + virtual void accept(unsigned int index,ValueVisitor&) = 0; + virtual void accept(unsigned int index,ConstValueVisitor&) const = 0; + + /** Return -1 if lhs element is less than rhs element, 0 if equal, + * 1 if lhs element is greater than rhs element. */ + virtual int compare(unsigned int lhs,unsigned int rhs) const = 0; + + Type getType() const { return _arrayType; } + GLint getDataSize() const { return _dataSize; } + GLenum getDataType() const { return _dataType; } + + virtual osg::Array* asArray() { return this; } + virtual const osg::Array* asArray() const { return this; } + + virtual unsigned int getElementSize() const = 0; + virtual const GLvoid* getDataPointer() const = 0; + virtual unsigned int getTotalDataSize() const = 0; + virtual unsigned int getNumElements() const = 0; + virtual void reserveArray(unsigned int num) = 0; + virtual void resizeArray(unsigned int num) = 0; + + + /** Specify how this array should be passed to OpenGL.*/ + void setBinding(Binding binding) { _binding = binding; } + + /** Get how this array should be passed to OpenGL.*/ + Binding getBinding() const { return _binding; } + + + /** Specify whether the array data should be normalized by OpenGL.*/ + void setNormalize(bool normalize) { _normalize = normalize; } + + /** Get whether the array data should be normalized by OpenGL.*/ + bool getNormalize() const { return _normalize; } + + + /** Set hint to ask that the array data is passed via integer or double, or normal setVertexAttribPointer function.*/ + void setPreserveDataType(bool preserve) { _preserveDataType = preserve; } + + /** Get hint to ask that the array data is passed via integer or double, or normal setVertexAttribPointer function.*/ + bool getPreserveDataType() const { return _preserveDataType; } + + + /** Frees unused space on this vector - i.e. the difference between size() and max_size() of the underlying vector.*/ + virtual void trim() {} + + /** Set the VertexBufferObject.*/ + inline void setVertexBufferObject(osg::VertexBufferObject* vbo) { setBufferObject(vbo); } + + /** Get the VertexBufferObject. If no VBO is assigned returns NULL*/ + inline osg::VertexBufferObject* getVertexBufferObject() { return dynamic_cast(_bufferObject.get()); } + + /** Get the const VertexBufferObject. If no VBO is assigned returns NULL*/ + inline const osg::VertexBufferObject* getVertexBufferObject() const { return dynamic_cast(_bufferObject.get()); } + + protected: + + virtual ~Array() {} + + Type _arrayType; + GLint _dataSize; + GLenum _dataType; + Binding _binding; + bool _normalize; + bool _preserveDataType; +}; + +/** convinience function for getting the binding of array via a ptr that may be null.*/ +inline osg::Array::Binding getBinding(const osg::Array* array) { return array ? array->getBinding() : osg::Array::BIND_OFF; } + +/** convinience function for getting the binding of array via a ptr that may be null.*/ +inline bool getNormalize(const osg::Array* array) { return array ? array->getNormalize() : false; } + + +template +class TemplateArray : public Array, public MixinVector +{ + public: + + TemplateArray(Binding binding=BIND_UNDEFINED) : Array(ARRAYTYPE,DataSize,DataType, binding) {} + + TemplateArray(const TemplateArray& ta,const CopyOp& copyop=CopyOp::SHALLOW_COPY): + Array(ta,copyop), + MixinVector(ta) {} + + TemplateArray(unsigned int no) : + Array(ARRAYTYPE,DataSize,DataType), + MixinVector(no) {} + + TemplateArray(unsigned int no,const T* ptr) : + Array(ARRAYTYPE,DataSize,DataType), + MixinVector(ptr,ptr+no) {} + + TemplateArray(Binding binding, unsigned int no) : + Array(ARRAYTYPE,DataSize,DataType, binding), + MixinVector(no) {} + + TemplateArray(Binding binding, unsigned int no,const T* ptr) : + Array(ARRAYTYPE,DataSize,DataType, binding), + MixinVector(ptr,ptr+no) {} + + template + TemplateArray(InputIterator first,InputIterator last) : + Array(ARRAYTYPE,DataSize,DataType), + MixinVector(first,last) {} + + TemplateArray& operator = (const TemplateArray& array) + { + if (this==&array) return *this; + this->assign(array.begin(),array.end()); + return *this; + } + + virtual Object* cloneType() const { return new TemplateArray(); } + virtual Object* clone(const CopyOp& copyop) const { return new TemplateArray(*this,copyop); } + + inline virtual void accept(ArrayVisitor& av); + inline virtual void accept(ConstArrayVisitor& av) const; + + inline virtual void accept(unsigned int index,ValueVisitor& vv); + inline virtual void accept(unsigned int index,ConstValueVisitor& vv) const; + + virtual int compare(unsigned int lhs,unsigned int rhs) const + { + const T& elem_lhs = (*this)[lhs]; + const T& elem_rhs = (*this)[rhs]; + if (elem_lhs( *this ).swap( *this ); + } + + virtual unsigned int getElementSize() const { return sizeof(ElementDataType); } + virtual const GLvoid* getDataPointer() const { if (!this->empty()) return &this->front(); else return 0; } + virtual unsigned int getTotalDataSize() const { return static_cast(this->size()*sizeof(ElementDataType)); } + virtual unsigned int getNumElements() const { return static_cast(this->size()); } + virtual void reserveArray(unsigned int num) { this->reserve(num); } + virtual void resizeArray(unsigned int num) { this->resize(num); } + + typedef T ElementDataType; // expose T + + protected: + + virtual ~TemplateArray() {} +}; + +class OSG_EXPORT IndexArray : public Array +{ + + public: + + IndexArray(Type arrayType=ArrayType,GLint dataSize=0,GLenum dataType=0): + Array(arrayType,dataSize,dataType) {} + + IndexArray(const Array& array,const CopyOp& copyop=CopyOp::SHALLOW_COPY): + Array(array,copyop) {} + + virtual bool isSameKindAs(const Object* obj) const { return dynamic_cast(obj)!=NULL; } + + virtual unsigned int index(unsigned int pos) const = 0; + + protected: + + virtual ~IndexArray() {} +}; + +template +class TemplateIndexArray : public IndexArray, public MixinVector +{ + public: + + TemplateIndexArray() : IndexArray(ARRAYTYPE,DataSize,DataType) {} + + TemplateIndexArray(const TemplateIndexArray& ta,const CopyOp& copyop=CopyOp::SHALLOW_COPY): + IndexArray(ta,copyop), + MixinVector(ta) {} + + TemplateIndexArray(unsigned int no) : + IndexArray(ARRAYTYPE,DataSize,DataType), + MixinVector(no) {} + + TemplateIndexArray(unsigned int no,T* ptr) : + IndexArray(ARRAYTYPE,DataSize,DataType), + MixinVector(ptr,ptr+no) {} + + template + TemplateIndexArray(InputIterator first,InputIterator last) : + IndexArray(ARRAYTYPE,DataSize,DataType), + MixinVector(first,last) {} + + TemplateIndexArray& operator = (const TemplateIndexArray& array) + { + if (this==&array) return *this; + this->assign(array.begin(),array.end()); + return *this; + } + + virtual Object* cloneType() const { return new TemplateIndexArray(); } + virtual Object* clone(const CopyOp& copyop) const { return new TemplateIndexArray(*this,copyop); } + + inline virtual void accept(ArrayVisitor& av); + inline virtual void accept(ConstArrayVisitor& av) const; + + inline virtual void accept(unsigned int index,ValueVisitor& vv); + inline virtual void accept(unsigned int index,ConstValueVisitor& vv) const; + + virtual int compare(unsigned int lhs,unsigned int rhs) const + { + const T& elem_lhs = (*this)[lhs]; + const T& elem_rhs = (*this)[rhs]; + if (elem_lhs( *this ).swap( *this ); + } + + virtual unsigned int getElementSize() const { return sizeof(ElementDataType); } + virtual const GLvoid* getDataPointer() const { if (!this->empty()) return &this->front(); else return 0; } + virtual unsigned int getTotalDataSize() const { return static_cast(this->size()*sizeof(T)); } + virtual unsigned int getNumElements() const { return static_cast(this->size()); } + virtual void reserveArray(unsigned int num) { this->reserve(num); } + virtual void resizeArray(unsigned int num) { this->resize(num); } + + virtual unsigned int index(unsigned int pos) const { return (*this)[pos]; } + + typedef T ElementDataType; // expose T + + protected: + + virtual ~TemplateIndexArray() {} +}; + +typedef TemplateIndexArray ByteArray; +typedef TemplateIndexArray ShortArray; +typedef TemplateIndexArray IntArray; + +typedef TemplateIndexArray UByteArray; +typedef TemplateIndexArray UShortArray; +typedef TemplateIndexArray UIntArray; + +typedef TemplateArray FloatArray; +typedef TemplateArray DoubleArray; + + +typedef TemplateArray Vec2bArray; +typedef TemplateArray Vec3bArray; +typedef TemplateArray Vec4bArray; + +typedef TemplateArray Vec2sArray; +typedef TemplateArray Vec3sArray; +typedef TemplateArray Vec4sArray; + +typedef TemplateArray Vec2iArray; +typedef TemplateArray Vec3iArray; +typedef TemplateArray Vec4iArray; + +typedef TemplateArray Vec2ubArray; +typedef TemplateArray Vec3ubArray; +typedef TemplateArray Vec4ubArray; + +typedef TemplateArray Vec2usArray; +typedef TemplateArray Vec3usArray; +typedef TemplateArray Vec4usArray; + +typedef TemplateArray Vec2uiArray; +typedef TemplateArray Vec3uiArray; +typedef TemplateArray Vec4uiArray; + +typedef TemplateArray Vec2Array; +typedef TemplateArray Vec3Array; +typedef TemplateArray Vec4Array; + +typedef TemplateArray Vec2dArray; +typedef TemplateArray Vec3dArray; +typedef TemplateArray Vec4dArray; + +typedef TemplateArray MatrixfArray; +typedef TemplateArray MatrixdArray; + + +class ArrayVisitor +{ + public: + ArrayVisitor() {} + virtual ~ArrayVisitor() {} + + virtual void apply(Array&) {} + + virtual void apply(ByteArray&) {} + virtual void apply(ShortArray&) {} + virtual void apply(IntArray&) {} + + virtual void apply(UByteArray&) {} + virtual void apply(UShortArray&) {} + virtual void apply(UIntArray&) {} + + virtual void apply(FloatArray&) {} + virtual void apply(DoubleArray&) {} + + + virtual void apply(Vec2bArray&) {} + virtual void apply(Vec3bArray&) {} + virtual void apply(Vec4bArray&) {} + + virtual void apply(Vec2sArray&) {} + virtual void apply(Vec3sArray&) {} + virtual void apply(Vec4sArray&) {} + + virtual void apply(Vec2iArray&) {} + virtual void apply(Vec3iArray&) {} + virtual void apply(Vec4iArray&) {} + + virtual void apply(Vec2ubArray&) {} + virtual void apply(Vec3ubArray&) {} + virtual void apply(Vec4ubArray&) {} + + virtual void apply(Vec2usArray&) {} + virtual void apply(Vec3usArray&) {} + virtual void apply(Vec4usArray&) {} + + virtual void apply(Vec2uiArray&) {} + virtual void apply(Vec3uiArray&) {} + virtual void apply(Vec4uiArray&) {} + + virtual void apply(Vec2Array&) {} + virtual void apply(Vec3Array&) {} + virtual void apply(Vec4Array&) {} + + virtual void apply(Vec2dArray&) {} + virtual void apply(Vec3dArray&) {} + virtual void apply(Vec4dArray&) {} + + virtual void apply(MatrixfArray&) {} + virtual void apply(MatrixdArray&) {} +}; + +class ConstArrayVisitor +{ + public: + ConstArrayVisitor() {} + virtual ~ConstArrayVisitor() {} + + virtual void apply(const Array&) {} + + virtual void apply(const ByteArray&) {} + virtual void apply(const ShortArray&) {} + virtual void apply(const IntArray&) {} + + virtual void apply(const UByteArray&) {} + virtual void apply(const UShortArray&) {} + virtual void apply(const UIntArray&) {} + + virtual void apply(const FloatArray&) {} + virtual void apply(const DoubleArray&) {} + + + virtual void apply(const Vec2bArray&) {} + virtual void apply(const Vec3bArray&) {} + virtual void apply(const Vec4bArray&) {} + + virtual void apply(const Vec2sArray&) {} + virtual void apply(const Vec3sArray&) {} + virtual void apply(const Vec4sArray&) {} + + virtual void apply(const Vec2iArray&) {} + virtual void apply(const Vec3iArray&) {} + virtual void apply(const Vec4iArray&) {} + + virtual void apply(const Vec2ubArray&) {} + virtual void apply(const Vec3ubArray&) {} + virtual void apply(const Vec4ubArray&) {} + + virtual void apply(const Vec2usArray&) {} + virtual void apply(const Vec3usArray&) {} + virtual void apply(const Vec4usArray&) {} + + virtual void apply(const Vec2uiArray&) {} + virtual void apply(const Vec3uiArray&) {} + virtual void apply(const Vec4uiArray&) {} + + virtual void apply(const Vec2Array&) {} + virtual void apply(const Vec3Array&) {} + virtual void apply(const Vec4Array&) {} + + virtual void apply(const Vec2dArray&) {} + virtual void apply(const Vec3dArray&) {} + virtual void apply(const Vec4dArray&) {} + + virtual void apply(const MatrixfArray&) {} + virtual void apply(const MatrixdArray&) {} +}; + + +class ValueVisitor +{ + public: + ValueVisitor() {} + virtual ~ValueVisitor() {} + + virtual void apply(GLbyte&) {} + virtual void apply(GLshort&) {} + virtual void apply(GLint&) {} + + virtual void apply(GLushort&) {} + virtual void apply(GLubyte&) {} + virtual void apply(GLuint&) {} + + virtual void apply(GLfloat&) {} + virtual void apply(GLdouble&) {} + + + virtual void apply(Vec2b&) {} + virtual void apply(Vec3b&) {} + virtual void apply(Vec4b&) {} + + virtual void apply(Vec2s&) {} + virtual void apply(Vec3s&) {} + virtual void apply(Vec4s&) {} + + virtual void apply(Vec2i&) {} + virtual void apply(Vec3i&) {} + virtual void apply(Vec4i&) {} + + virtual void apply(Vec2ub&) {} + virtual void apply(Vec3ub&) {} + virtual void apply(Vec4ub&) {} + + virtual void apply(Vec2us&) {} + virtual void apply(Vec3us&) {} + virtual void apply(Vec4us&) {} + + virtual void apply(Vec2ui&) {} + virtual void apply(Vec3ui&) {} + virtual void apply(Vec4ui&) {} + + virtual void apply(Vec2&) {} + virtual void apply(Vec3&) {} + virtual void apply(Vec4&) {} + + virtual void apply(Vec2d&) {} + virtual void apply(Vec3d&) {} + virtual void apply(Vec4d&) {} + + virtual void apply(Matrixf&) {} + virtual void apply(Matrixd&) {} +}; + +class ConstValueVisitor +{ + public: + ConstValueVisitor() {} + virtual ~ConstValueVisitor() {} + + virtual void apply(const GLbyte&) {} + virtual void apply(const GLshort&) {} + virtual void apply(const GLint&) {} + + virtual void apply(const GLushort&) {} + virtual void apply(const GLubyte&) {} + virtual void apply(const GLuint&) {} + + virtual void apply(const GLfloat&) {} + virtual void apply(const GLdouble&) {} + + + virtual void apply(const Vec2b&) {} + virtual void apply(const Vec3b&) {} + virtual void apply(const Vec4b&) {} + + virtual void apply(const Vec2s&) {} + virtual void apply(const Vec3s&) {} + virtual void apply(const Vec4s&) {} + + virtual void apply(const Vec2i&) {} + virtual void apply(const Vec3i&) {} + virtual void apply(const Vec4i&) {} + + virtual void apply(const Vec2ub&) {} + virtual void apply(const Vec3ub&) {} + virtual void apply(const Vec4ub&) {} + + virtual void apply(const Vec2us&) {} + virtual void apply(const Vec3us&) {} + virtual void apply(const Vec4us&) {} + + virtual void apply(const Vec2ui&) {} + virtual void apply(const Vec3ui&) {} + virtual void apply(const Vec4ui&) {} + + virtual void apply(const Vec2&) {} + virtual void apply(const Vec3&) {} + virtual void apply(const Vec4&) {} + + virtual void apply(const Vec2d&) {} + virtual void apply(const Vec3d&) {} + virtual void apply(const Vec4d&) {} + + virtual void apply(const Matrixf&) {} + virtual void apply(const Matrixd&) {} +}; + +template +inline void TemplateArray::accept(ArrayVisitor& av) { av.apply(*this); } + +template +inline void TemplateArray::accept(ConstArrayVisitor& av) const { av.apply(*this); } + +template +inline void TemplateArray::accept(unsigned int index,ValueVisitor& vv) { vv.apply( (*this)[index] ); } + +template +inline void TemplateArray::accept(unsigned int index,ConstValueVisitor& vv) const { vv.apply( (*this)[index] );} + +template +inline void TemplateIndexArray::accept(ArrayVisitor& av) { av.apply(*this); } + +template +inline void TemplateIndexArray::accept(ConstArrayVisitor& av) const { av.apply(*this); } + +template +inline void TemplateIndexArray::accept(unsigned int index,ValueVisitor& vv) { vv.apply( (*this)[index] ); } + +template +inline void TemplateIndexArray::accept(unsigned int index,ConstValueVisitor& vv) const { vv.apply( (*this)[index] );} + +} + +#endif diff --git a/libs/include/android/osg/ArrayDispatchers b/libs/include/android/osg/ArrayDispatchers new file mode 100755 index 0000000..1833926 --- /dev/null +++ b/libs/include/android/osg/ArrayDispatchers @@ -0,0 +1,112 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_ArrayDispatchers +#define OSG_ArrayDispatchers 1 + +#include +#include +#include + +namespace osg { + +// forward declare +class State; +class AttributeDispatchMap; + +struct AttributeDispatch : public osg::Referenced +{ + virtual void assign(const GLvoid*) {} + virtual void operator() (unsigned int) {}; +}; + +/** Helper class for managing the dispatch to OpenGL of various attribute arrays such as stored in osg::Geometry.*/ +class OSG_EXPORT ArrayDispatchers : public osg::Referenced +{ + public: + + ArrayDispatchers(); + ~ArrayDispatchers(); + + void setState(osg::State* state); + + void reset(); + + void setUseVertexAttribAlias(bool flag) { _useVertexAttribAlias = flag; } + bool getUseVertexAttribAlias() const { return _useVertexAttribAlias; } + + void activate(unsigned int binding, AttributeDispatch* at) + { + if (at) _activeDispatchList[binding].push_back(at); + } + + void activateVertexArray(osg::Array* array) { if (array && array->getBinding()>osg::Array::BIND_OFF) activate(array->getBinding(), vertexDispatcher(array)); } + void activateColorArray(osg::Array* array) { if (array && array->getBinding()>osg::Array::BIND_OFF) activate(array->getBinding(), colorDispatcher(array)); } + void activateNormalArray(osg::Array* array) { if (array && array->getBinding()>osg::Array::BIND_OFF) activate(array->getBinding(), normalDispatcher(array)); } + void activateSecondaryColorArray(osg::Array* array) { if (array && array->getBinding()>osg::Array::BIND_OFF) activate(array->getBinding(), secondaryColorDispatcher(array)); } + void activateFogCoordArray(osg::Array* array) { if (array && array->getBinding()>osg::Array::BIND_OFF) activate(array->getBinding(), fogCoordDispatcher(array)); } + void activateTexCoordArray(unsigned int unit, osg::Array* array) { if (array && array->getBinding()>osg::Array::BIND_OFF) activate(array->getBinding(), texCoordDispatcher(unit, array)); } + void activateVertexAttribArray(unsigned int unit, osg::Array* array) { if (array && array->getBinding()>osg::Array::BIND_OFF) activate(array->getBinding(), vertexAttribDispatcher(unit, array)); } + + AttributeDispatch* vertexDispatcher(Array* array); + AttributeDispatch* normalDispatcher(Array* array); + AttributeDispatch* colorDispatcher(Array* array); + AttributeDispatch* secondaryColorDispatcher(Array* array); + AttributeDispatch* fogCoordDispatcher(Array* array); + AttributeDispatch* texCoordDispatcher(unsigned int unit, Array* array); + AttributeDispatch* vertexAttribDispatcher(unsigned int unit, Array* array); + + void dispatch(unsigned int binding, unsigned int index) + { + AttributeDispatchList& ad = _activeDispatchList[binding]; + for(AttributeDispatchList::iterator itr = ad.begin(); + itr != ad.end(); + ++itr) + { + (*(*itr))(index); + } + } + + bool active(unsigned int binding) const { return !_activeDispatchList[binding].empty(); } + + protected: + + void init(); + + void assignTexCoordDispatchers(unsigned int unit); + void assignVertexAttribDispatchers(unsigned int unit); + + bool _initialized; + State* _state; + + AttributeDispatchMap* _vertexDispatchers; + AttributeDispatchMap* _normalDispatchers; + AttributeDispatchMap* _colorDispatchers; + AttributeDispatchMap* _secondaryColorDispatchers; + AttributeDispatchMap* _fogCoordDispatchers; + + typedef std::vector AttributeDispatchMapList; + AttributeDispatchMapList _texCoordDispatchers; + AttributeDispatchMapList _vertexAttribDispatchers; + + typedef std::vector AttributeDispatchList; + + typedef std::vector ActiveDispatchList; + ActiveDispatchList _activeDispatchList; + + bool _useVertexAttribAlias; +}; + +} + +#endif diff --git a/libs/include/android/osg/AudioStream b/libs/include/android/osg/AudioStream new file mode 100755 index 0000000..a13ac9d --- /dev/null +++ b/libs/include/android/osg/AudioStream @@ -0,0 +1,86 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_AUDIOSTREAM +#define OSG_AUDIOSTREAM 1 + +#include +#include + +namespace osg { + +/** Pure virtual AudioSink bass class that is used to connect the audio system with AudioStreams. */ +class OSG_EXPORT AudioSink : public osg::Object +{ +public: + + AudioSink(); + + virtual const char * libraryName() const { return "osg"; } + virtual const char * className() const { return "AudioSinkInterface"; } + + virtual void play() = 0; + virtual void pause() = 0; + virtual void stop() = 0; + + virtual bool playing() const = 0; + + virtual double getDelay() const { return _delay; } + virtual void setDelay(const double delay) { _delay = delay; } + + virtual void setVolume(float) {} + virtual float getVolume() const { return 0.0f; } + +private: + + virtual AudioSink * cloneType() const { return 0; } + virtual AudioSink * clone(const osg::CopyOp &) const { return 0; } + + double _delay; +}; + +/** Pure virtual AudioStream base class. Subclasses provide mechanism for reading/generating audio data*/ +class OSG_EXPORT AudioStream : public osg::Object +{ + public: + AudioStream(); + + /** Copy constructor using CopyOp to manage deep vs shallow copy. */ + AudioStream(const AudioStream& audio,const CopyOp& copyop=CopyOp::SHALLOW_COPY); + + virtual bool isSameKindAs(const Object* obj) const { return dynamic_cast(obj)!=0; } + virtual const char* libraryName() const { return "osg"; } + virtual const char* className() const { return "AudioStream"; } + + virtual void setAudioSink(osg::AudioSink* audio_sink) = 0; + + virtual void consumeAudioBuffer(void * const buffer, const size_t size) = 0; + + virtual int audioFrequency() const = 0; + virtual int audioNbChannels() const = 0; + + enum SampleFormat + { + SAMPLE_FORMAT_U8, + SAMPLE_FORMAT_S16, + SAMPLE_FORMAT_S24, + SAMPLE_FORMAT_S32, + SAMPLE_FORMAT_F32 + }; + + virtual SampleFormat audioSampleFormat() const = 0; +}; + +} // namespace + +#endif diff --git a/libs/include/android/osg/AutoTransform b/libs/include/android/osg/AutoTransform new file mode 100755 index 0000000..efa0f65 --- /dev/null +++ b/libs/include/android/osg/AutoTransform @@ -0,0 +1,161 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_AUTOTRANSFORM +#define OSG_AUTOTRANSFORM 1 + +#include +#include +#include +#include + +namespace osg { + +/** AutoTransform is a derived form of Transform that automatically + * scales or rotates to keep its children aligned with screen coordinates. +*/ +class OSG_EXPORT AutoTransform : public Transform +{ + public : + AutoTransform(); + + AutoTransform(const AutoTransform& pat,const CopyOp& copyop=CopyOp::SHALLOW_COPY); + + virtual osg::Object* cloneType() const { return new AutoTransform (); } + virtual osg::Object* clone(const osg::CopyOp& copyop) const { return new AutoTransform (*this,copyop); } + virtual bool isSameKindAs(const osg::Object* obj) const { return dynamic_cast(obj)!=NULL; } + virtual const char* className() const { return "AutoTransform"; } + virtual const char* libraryName() const { return "osg"; } + + virtual void accept(NodeVisitor& nv); + + virtual AutoTransform* asAutoTransform() { return this; } + virtual const AutoTransform* asAutoTransform() const { return this; } + + inline void setPosition(const Vec3d& pos) { _position = pos; _matrixDirty=true; dirtyBound(); } + inline const Vec3d& getPosition() const { return _position; } + + + inline void setRotation(const Quat& quat) { _rotation = quat; _matrixDirty=true; dirtyBound(); } + inline const Quat& getRotation() const { return _rotation; } + + inline void setScale(double scale) { setScale(osg::Vec3(scale,scale,scale)); } + + void setScale(const Vec3d& scale); + inline const Vec3d& getScale() const { return _scale; } + + void setMinimumScale(double minimumScale) { _minimumScale = minimumScale; } + double getMinimumScale() const { return _minimumScale; } + + void setMaximumScale(double maximumScale) { _maximumScale = maximumScale; } + double getMaximumScale() const { return _maximumScale; } + + inline void setPivotPoint(const Vec3d& pivot) { _pivotPoint = pivot; _matrixDirty=true; dirtyBound(); } + inline const Vec3d& getPivotPoint() const { return _pivotPoint; } + + + void setAutoUpdateEyeMovementTolerance(float tolerance) { _autoUpdateEyeMovementTolerance = tolerance; } + float getAutoUpdateEyeMovementTolerance() const { return _autoUpdateEyeMovementTolerance; } + + + enum AutoRotateMode + { + NO_ROTATION, + ROTATE_TO_SCREEN, + ROTATE_TO_CAMERA, + ROTATE_TO_AXIS + }; + + void setAutoRotateMode(AutoRotateMode mode); + + AutoRotateMode getAutoRotateMode() const { return _autoRotateMode; } + + /** Set the rotation axis for the AutoTransform's child nodes. + * Only utilized when _autoRotateMode==ROTATE_TO_AXIS. */ + void setAxis(const Vec3& axis); + /** Get the rotation axis. */ + inline const Vec3& getAxis() const { return _axis; } + + /** This normal defines child Nodes' front face direction when unrotated. */ + void setNormal(const Vec3& normal); + /** Get the front face direction normal. */ + inline const Vec3& getNormal() const { return _normal; } + + void setAutoScaleToScreen(bool autoScaleToScreen) { _autoScaleToScreen = autoScaleToScreen; _matrixDirty=true; } + + bool getAutoScaleToScreen() const { return _autoScaleToScreen; } + + void setAutoScaleTransitionWidthRatio(float ratio) { _autoScaleTransitionWidthRatio = ratio; } + float getAutoScaleTransitionWidthRatio() const { return _autoScaleTransitionWidthRatio; } + + + virtual bool computeLocalToWorldMatrix(Matrix& matrix,NodeVisitor* nv) const; + + virtual bool computeWorldToLocalMatrix(Matrix& matrix,NodeVisitor* nv) const; + + virtual BoundingSphere computeBound() const; + + + protected : + + virtual ~AutoTransform() {} + + Vec3d _position; + Vec3d _pivotPoint; + double _autoUpdateEyeMovementTolerance; + + AutoRotateMode _autoRotateMode; + + bool _autoScaleToScreen; + + mutable Quat _rotation; + mutable Vec3d _scale; + mutable bool _firstTimeToInitEyePoint; + mutable osg::Vec3 _previousEyePoint; + mutable osg::Vec3 _previousLocalUp; + mutable Viewport::value_type _previousWidth; + mutable Viewport::value_type _previousHeight; + mutable osg::Matrixd _previousProjection; + mutable osg::Vec3d _previousPosition; + + double _minimumScale; + double _maximumScale; + double _autoScaleTransitionWidthRatio; + + void computeMatrix() const; + + mutable bool _matrixDirty; + mutable osg::Matrixd _cachedMatrix; + + enum AxisAligned + { + AXIAL_ROT_X_AXIS=ROTATE_TO_AXIS+1, + AXIAL_ROT_Y_AXIS, + AXIAL_ROT_Z_AXIS, + CACHE_DIRTY + }; + + Vec3 _axis; + Vec3 _normal; + + // used internally as cache of which what _axis is aligned to help + // decide which method of rotation to use. + int _cachedMode; + Vec3 _side; + void updateCache(); + +}; + +} + +#endif diff --git a/libs/include/android/osg/Billboard b/libs/include/android/osg/Billboard new file mode 100755 index 0000000..85fa6c9 --- /dev/null +++ b/libs/include/android/osg/Billboard @@ -0,0 +1,132 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_BILLBOARD +#define OSG_BILLBOARD 1 + +#include +#include + +namespace osg { + +/** Billboard is a derived form of Geode that orients its osg::Drawable + * children to face the eye point. Typical uses include trees and + * particle explosions, +*/ +class OSG_EXPORT Billboard : public Geode +{ + public: + + enum Mode { + POINT_ROT_EYE, + POINT_ROT_WORLD, + AXIAL_ROT + }; + + Billboard(); + + /** Copy constructor using CopyOp to manage deep vs shallow copy. */ + Billboard(const Billboard&,const CopyOp& copyop=CopyOp::SHALLOW_COPY); + + META_Node(osg, Billboard); + + /** Set the billboard rotation mode. */ + void setMode(Mode mode); + /** Get the billboard rotation mode. */ + inline Mode getMode() const { return _mode; } + + /** Set the rotation axis for the billboard's child Drawables. + * Only utilized when mode==AXIAL_ROT. */ + void setAxis(const Vec3& axis); + /** Get the rotation axis. */ + inline const Vec3& getAxis() const { return _axis; } + + /** This normal defines child Drawables' front face direction when unrotated. */ + void setNormal(const Vec3& normal); + /** Get the front face direction normal. */ + inline const Vec3& getNormal() const { return _normal; } + + + /** Set the specified child Drawable's position. */ + inline void setPosition(unsigned int i,const Vec3& pos) { _positionList[i] = pos; } + /** Get the specified child Drawable's position. */ + inline const Vec3& getPosition(unsigned int i) const { return _positionList[i]; } + + /** Type definition for pivot point position list. */ + typedef std::vector PositionList; + + /** Set the list of pivot point positions. */ + inline void setPositionList(PositionList& pl) { _positionList=pl; } + + /** Get the list of pivot point positions. */ + inline PositionList& getPositionList() { return _positionList; } + + /** Get a const list of pivot point positions. */ + inline const PositionList& getPositionList() const { return _positionList; } + + /** Add a Drawable with a default position of Vec3(0,0,0). + * Call the base-class Geode::addDrawble() to add the given Drawable + * gset as a child. If Geode::addDrawable() returns true, add the + * default position to the pivot point position list and return true. + * Otherwise, return false. */ + virtual bool addDrawable( Drawable *gset ); + + /** Add a Drawable with a specified position. + * Call the base-class Geode::addDrawble() to add the given Drawable + * gset as a child. If Geode::addDrawable() returns true, add the + * given position pos to the pivot point position list and return true. + * Otherwise, return false. */ + virtual bool addDrawable(Drawable *gset,const Vec3& pos); + + /** Remove a Drawable and its associated position. + * If gset is a child, remove it, decrement its reference count, + * remove its pivot point position. and return true. + * Otherwise, return false. */ + virtual bool removeDrawable( Drawable *gset ); + + + bool computeMatrix(Matrix& modelview, const Vec3& eye_local, const Vec3& pos_local) const; + + virtual BoundingSphere computeBound() const; + + protected: + + virtual ~Billboard(); + + enum AxisAligned + { + AXIAL_ROT_X_AXIS=AXIAL_ROT+1, + AXIAL_ROT_Y_AXIS, + AXIAL_ROT_Z_AXIS, + POINT_ROT_WORLD_Z_AXIS, + CACHE_DIRTY + }; + + + Mode _mode; + Vec3 _axis; + Vec3 _normal; + Matrix _rotateNormalToZAxis; + PositionList _positionList; + + // used internally as cache of which what _axis is aligned to help + // decide which method of rotation to use. + int _cachedMode; + Vec3 _side; + void updateCache(); + +}; + +} + +#endif diff --git a/libs/include/android/osg/BlendColor b/libs/include/android/osg/BlendColor new file mode 100755 index 0000000..f3932bb --- /dev/null +++ b/libs/include/android/osg/BlendColor @@ -0,0 +1,125 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_BLENDCOLOR +#define OSG_BLENDCOLOR 1 + +#include +#include +#include +#include + + + +namespace osg { + +/** Encapsulates OpenGL blend/transparency state. */ +class OSG_EXPORT BlendColor : public StateAttribute +{ + public : + + BlendColor(); + + BlendColor(const osg::Vec4& constantColor); + + /** Copy constructor using CopyOp to manage deep vs shallow copy.*/ + BlendColor(const BlendColor& trans,const CopyOp& copyop=CopyOp::SHALLOW_COPY): + StateAttribute(trans,copyop), + _constantColor(trans._constantColor) {} + + META_StateAttribute(osg, BlendColor,BLENDCOLOR); + + /** Return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs. */ + virtual int compare(const StateAttribute& sa) const + { + // Check for equal types, then create the rhs variable + // used by the COMPARE_StateAttribute_Parameter macros below. + COMPARE_StateAttribute_Types(BlendColor,sa) + + // Compare each parameter in turn against the rhs. + COMPARE_StateAttribute_Parameter(_constantColor) + + return 0; // Passed all the above comparison macros, so must be equal. + } + + virtual bool getModeUsage(StateAttribute::ModeUsage& usage) const + { + usage.usesMode(GL_BLEND); + return true; + } + + void setConstantColor(const osg::Vec4& color) { _constantColor = color; } + + inline osg::Vec4& getConstantColor() { return _constantColor; } + + inline const osg::Vec4& getConstantColor() const { return _constantColor; } + + virtual void apply(State& state) const; + + + + + /** Encapsulates queries of extension availability, obtains extension + * function pointers, and provides convenience wrappers for + * calling extension functions. */ + class OSG_EXPORT Extensions : public osg::Referenced + { + public: + Extensions(unsigned int contextID); + + Extensions(const Extensions& rhs); + + void lowestCommonDenominator(const Extensions& rhs); + + void setupGLExtensions(unsigned int contextID); + + void setBlendColorSupported(bool flag) { _isBlendColorSupported=flag; } + bool isBlendColorSupported() const { return _isBlendColorSupported; } + + void glBlendColor(GLclampf red , GLclampf green , GLclampf blue , GLclampf alpha) const; + + protected: + + ~Extensions() {} + + + typedef void (GL_APIENTRY * GLBlendColorProc) (GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha); + bool _isBlendColorSupported; + GLBlendColorProc _glBlendColor; + + }; + + /** Returns the Extensions object for the given context. + * If createIfNotInitalized is true and the Extensions object doesn't + * exist, getExtensions() creates it on the given context. + * Returns NULL if createIfNotInitalized is false and the Extensions + * object doesn't exist. */ + static Extensions* getExtensions(unsigned int contextID,bool createIfNotInitalized); + + /** setExtensions() allows users to override the extensions across graphics contexts. + * Typically used when you have different extensions supported across graphics pipes, + * but need to ensure that they all use the same low common denominator extensions. */ + static void setExtensions(unsigned int contextID,Extensions* extensions); + + + + protected : + + virtual ~BlendColor(); + + osg::Vec4 _constantColor; +}; + +} + +#endif diff --git a/libs/include/android/osg/BlendEquation b/libs/include/android/osg/BlendEquation new file mode 100755 index 0000000..d0da4b0 --- /dev/null +++ b/libs/include/android/osg/BlendEquation @@ -0,0 +1,161 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_BLENDEQUATION +#define OSG_BLENDEQUATION 1 + +#include + +#ifndef GL_VERSION_1_2 +/* Logic Ops */ +#define GL_MIN 0x8007 +#define GL_MAX 0x8008 +#define GL_FUNC_ADD 0x8006 +#define GL_FUNC_SUBTRACT 0x800A +#define GL_FUNC_REVERSE_SUBTRACT 0x800B +#endif + +#ifndef GL_LOGIC_OP +#define GL_LOGIC_OP 0x0BF1 +#endif + +#ifndef GL_ALPHA_MIN_SGIX +#define GL_ALPHA_MIN_SGIX 0x8320 +#define GL_ALPHA_MAX_SGIX 0x8321 +#endif + +namespace osg { + +/** Encapsulates OpenGL BlendEquation state. */ +class OSG_EXPORT BlendEquation : public StateAttribute +{ + public : + + enum Equation { + RGBA_MIN = GL_MIN, + RGBA_MAX = GL_MAX, + ALPHA_MIN = GL_ALPHA_MIN_SGIX, + ALPHA_MAX = GL_ALPHA_MAX_SGIX, + LOGIC_OP = GL_LOGIC_OP, + FUNC_ADD = GL_FUNC_ADD, + FUNC_SUBTRACT = GL_FUNC_SUBTRACT, + FUNC_REVERSE_SUBTRACT = GL_FUNC_REVERSE_SUBTRACT + }; + + BlendEquation(); + + BlendEquation(Equation equation); + + BlendEquation(Equation equationRGB, Equation equationAlpha); + + /** Copy constructor using CopyOp to manage deep vs shallow copy. */ + BlendEquation(const BlendEquation& trans,const CopyOp& copyop=CopyOp::SHALLOW_COPY): + StateAttribute(trans,copyop), + _equationRGB(trans._equationRGB), + _equationAlpha(trans._equationAlpha){} + + META_StateAttribute(osg, BlendEquation,BLENDEQUATION); + + /** Return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs. */ + virtual int compare(const StateAttribute& sa) const + { + // Check for equal types, then create the rhs variable + // used by the COMPARE_StateAttribute_Parameter macros below. + COMPARE_StateAttribute_Types(BlendEquation,sa) + + // Compare each parameter in turn against the rhs. + COMPARE_StateAttribute_Parameter(_equationRGB) + COMPARE_StateAttribute_Parameter(_equationAlpha) + + return 0; // Passed all the above comparison macros, so must be equal. + } + + virtual bool getModeUsage(StateAttribute::ModeUsage& usage) const + { + usage.usesMode(GL_BLEND); + return true; + } + + + inline void setEquation(Equation equation) { _equationRGB = _equationAlpha = equation; } + inline Equation getEquation() const { return _equationRGB; } + + inline void setEquationRGB(Equation equation) { _equationRGB = equation; } + inline Equation getEquationRGB() const { return _equationRGB; } + + inline void setEquationAlpha(Equation equation) { _equationAlpha = equation; } + inline Equation getEquationAlpha() const { return _equationAlpha; } + + virtual void apply(State& state) const; + /** Encapsulates queries of extension availability, obtains extension + * function pointers, and provides convenience wrappers for + * calling extension functions. */ + class OSG_EXPORT Extensions : public osg::Referenced + { + public: + Extensions(unsigned int contextID); + + Extensions(const Extensions& rhs); + + void lowestCommonDenominator(const Extensions& rhs); + + void setupGLExtensions(unsigned int contextID); + + bool isBlendEquationSupported() const { return _isBlendEquationSupported; } + bool isBlendEquationSeparateSupported() const { return _isBlendEquationSeparateSupported; } + bool isSGIXMinMaxSupported() const { return _isSGIXMinMaxSupported; } + bool isLogicOpSupported() const { return _isLogicOpSupported; } + + void glBlendEquation(GLenum mode) const; + void glBlendEquationSeparate(GLenum modeRGB, GLenum modeAlpha) const; + + protected: + + ~Extensions() {} + + typedef void (GL_APIENTRY * GLBlendEquationProc)(GLenum mode); + typedef void (GL_APIENTRY * GLBlendEquationSeparateProc)(GLenum modeRGB, GLenum modeAlpha); + + bool _isBlendEquationSupported; + bool _isBlendEquationSeparateSupported; + bool _isSGIXMinMaxSupported; + bool _isLogicOpSupported; + + GLBlendEquationProc _glBlendEquation; + GLBlendEquationSeparateProc _glBlendEquationSeparate; + }; + + /** Returns the Extensions object for the given context. + * If createIfNotInitalized is true and the Extensions object doesn't + * exist, getExtensions() creates it on the given context. + * Returns NULL if createIfNotInitalized is false and the Extensions + * object doesn't exist. */ + static Extensions* getExtensions(unsigned int contextID,bool createIfNotInitalized); + + /** setExtensions() allows users to override the extensions across graphics contexts. + * Typically used when you have different extensions supported across graphics pipes, + * but need to ensure that they all use the same low common denominator extensions. */ + static void setExtensions(unsigned int contextID,Extensions* extensions); + + + protected : + + virtual ~BlendEquation(); + + + Equation _equationRGB, _equationAlpha; +}; + +} + +#endif diff --git a/libs/include/android/osg/BlendFunc b/libs/include/android/osg/BlendFunc new file mode 100755 index 0000000..d2cb3d2 --- /dev/null +++ b/libs/include/android/osg/BlendFunc @@ -0,0 +1,221 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_BLENDFUNC +#define OSG_BLENDFUNC 1 + +#include + + +#ifndef GL_VERSION_1_2 +#define GL_CONSTANT_COLOR 0x8001 +#define GL_ONE_MINUS_CONSTANT_COLOR 0x8002 +#define GL_CONSTANT_ALPHA 0x8003 +#define GL_ONE_MINUS_CONSTANT_ALPHA 0x8004 +#define GL_BLEND_COLOR 0x8005 +#endif + +#ifndef GL_VERSION_1_4 +#define GL_BLEND_DST_RGB 0x80C8 +#define GL_BLEND_SRC_RGB 0x80C9 +#define GL_BLEND_DST_ALPHA 0x80CA +#define GL_BLEND_SRC_ALPHA 0x80CB +#endif + + +namespace osg { + +/** Encapsulates OpenGL blend/transparency state. + * + * Blending combines incoming fragment with a fragment + * already present in the target buffer. + * + * OpenGL 1.1 supports following source and destination blending factors: + * GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, + * GL_DST_ALPHA, GL_ONE_MINUS_DST_ALPHA, + * GL_ZERO, GL_ONE. + * + * Moreover, there are three source-only blending factors: + * GL_DST_COLOR, GL_ONE_MINUS_DST_COLOR, GL_SRC_ALPHA_SATURATE + * and two destination-only blending factors: + * GL_SRC_COLOR, GL_ONE_MINUS_SRC_COLOR. + * OpenGL 1.4 allowed to use these five blending factors + * as both - source and destination blending factors. + * + * Following four source and destination blending factors + * were added by Imaging subset of OpenGL 1.2 + * and made mandatory by OpenGL 1.4: + * GL_CONSTANT_COLOR, GL_ONE_MINUS_CONSTANT_COLOR, + * GL_CONSTANT_ALPHA, GL_ONE_MINUS_CONSTANT_ALPHA + * + * OpenGL 1.4 further provides glBlendFuncSeparate + * (promoted from GL_EXT_blend_func_separate). + * It makes possible to set blending functions for RGB and Alpha separately. + * Before, it was possible to set just one blending function for RGBA. + */ +class OSG_EXPORT BlendFunc : public StateAttribute +{ + public : + + BlendFunc(); + + BlendFunc(GLenum source, GLenum destination); + BlendFunc(GLenum source, GLenum destination, GLenum source_alpha, GLenum destination_alpha); + + /** Copy constructor using CopyOp to manage deep vs shallow copy. */ + BlendFunc(const BlendFunc& trans,const CopyOp& copyop=CopyOp::SHALLOW_COPY): + StateAttribute(trans,copyop), + _source_factor(trans._source_factor), + _destination_factor(trans._destination_factor), + _source_factor_alpha(trans._source_factor_alpha), + _destination_factor_alpha(trans._destination_factor_alpha) {} + + META_StateAttribute(osg, BlendFunc,BLENDFUNC); + + /** Return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs. */ + virtual int compare(const StateAttribute& sa) const + { + // Check for equal types, then create the rhs variable + // used by the COMPARE_StateAttribute_Parameter macros below. + COMPARE_StateAttribute_Types(BlendFunc,sa) + + // Compare each parameter in turn against the rhs. + COMPARE_StateAttribute_Parameter(_source_factor) + COMPARE_StateAttribute_Parameter(_destination_factor) + COMPARE_StateAttribute_Parameter(_source_factor_alpha) + COMPARE_StateAttribute_Parameter(_destination_factor_alpha) + + return 0; // Passed all the above comparison macros, so must be equal. + } + + virtual bool getModeUsage(StateAttribute::ModeUsage& usage) const + { + usage.usesMode(GL_BLEND); + return true; + } + + enum BlendFuncMode { + DST_ALPHA = GL_DST_ALPHA, + DST_COLOR = GL_DST_COLOR, + ONE = GL_ONE, + ONE_MINUS_DST_ALPHA = GL_ONE_MINUS_DST_ALPHA, + ONE_MINUS_DST_COLOR = GL_ONE_MINUS_DST_COLOR, + ONE_MINUS_SRC_ALPHA = GL_ONE_MINUS_SRC_ALPHA, + ONE_MINUS_SRC_COLOR = GL_ONE_MINUS_SRC_COLOR, + SRC_ALPHA = GL_SRC_ALPHA, + SRC_ALPHA_SATURATE = GL_SRC_ALPHA_SATURATE, + SRC_COLOR = GL_SRC_COLOR, + CONSTANT_COLOR = GL_CONSTANT_COLOR, + ONE_MINUS_CONSTANT_COLOR = GL_ONE_MINUS_CONSTANT_COLOR, + CONSTANT_ALPHA = GL_CONSTANT_ALPHA, + ONE_MINUS_CONSTANT_ALPHA = GL_ONE_MINUS_CONSTANT_ALPHA, + ZERO = GL_ZERO + }; + + inline void setFunction( GLenum source, GLenum destination ) + { + _source_factor = source; + _destination_factor = destination; + _source_factor_alpha = source; + _destination_factor_alpha = destination; + } + + inline void setFunction( GLenum source_rgb, GLenum destination_rgb, GLenum source_alpha, GLenum destination_alpha ) + { + _source_factor = source_rgb; + _destination_factor = destination_rgb; + _source_factor_alpha = source_alpha; + _destination_factor_alpha = destination_alpha; + } + + void setSource(GLenum source) { _source_factor = _source_factor_alpha = source; } + inline GLenum getSource() const { return _source_factor; } + + void setSourceRGB(GLenum source) { _source_factor = source; } + inline GLenum getSourceRGB() const { return _source_factor; } + + void setSourceAlpha(GLenum source) { _source_factor_alpha = source; } + inline GLenum getSourceAlpha() const { return _source_factor_alpha; } + + void setDestination(GLenum destination) { _destination_factor = _destination_factor_alpha = destination; } + inline GLenum getDestination() const { return _destination_factor; } + + void setDestinationRGB(GLenum destination) { _destination_factor = destination; } + inline GLenum getDestinationRGB() const { return _destination_factor; } + + void setDestinationAlpha(GLenum destination) { _destination_factor_alpha = destination; } + inline GLenum getDestinationAlpha() const { return _destination_factor_alpha; } + + virtual void apply(State& state) const; + /** Encapsulates queries of extension availability, obtains extension + * function pointers, and provides convenience wrappers for + * calling extension functions. */ + class OSG_EXPORT Extensions : public osg::Referenced + { + public: + Extensions(unsigned int contextID); + + Extensions(const Extensions& rhs); + + void lowestCommonDenominator(const Extensions& rhs); + + void setupGLExtensions(unsigned int contextID); + + void setBlendFuncSeparateSupported(bool flag) { _isBlendFuncSeparateSupported=flag; } + bool isBlendFuncSeparateSupported() const { return _isBlendFuncSeparateSupported; } + + void glBlendFuncSeparate(GLenum sfactorRGB, + GLenum dfactorRGB, + GLenum sfactorAlpha, + GLenum dfactorAlpha) const; + + protected: + + ~Extensions() {} + + + typedef void (GL_APIENTRY * GLBlendFuncSeparateProc) (GLenum sfactorRGB, + GLenum dfactorRGB, + GLenum sfactorAlpha, + GLenum dfactorAlpha); + bool _isBlendFuncSeparateSupported; + GLBlendFuncSeparateProc _glBlendFuncSeparate; + + }; + + /** Returns the Extensions object for the given context. + * If createIfNotInitalized is true and the Extensions object doesn't + * exist, getExtensions() creates it on the given context. + * Returns NULL if createIfNotInitalized is false and the Extensions + * object doesn't exist. */ + static Extensions* getExtensions(unsigned int contextID,bool createIfNotInitalized); + + /** setExtensions() allows users to override the extensions across graphics contexts. + * Typically used when you have different extensions supported across graphics pipes, + * but need to ensure that they all use the same low common denominator extensions. */ + static void setExtensions(unsigned int contextID,Extensions* extensions); + + + protected : + + virtual ~BlendFunc(); + + GLenum _source_factor; + GLenum _destination_factor; + GLenum _source_factor_alpha; + GLenum _destination_factor_alpha; +}; + +} + +#endif diff --git a/libs/include/android/osg/BoundingBox b/libs/include/android/osg/BoundingBox new file mode 100755 index 0000000..e6c5b46 --- /dev/null +++ b/libs/include/android/osg/BoundingBox @@ -0,0 +1,262 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_BOUNDINGBOX +#define OSG_BOUNDINGBOX 1 + +#include +#include +#include +#include +#include + +namespace osg { + +template +class BoundingSphereImpl; + +/** General purpose axis-aligned bounding box class for enclosing objects/vertices. + * Bounds leaf objects in a scene such as osg::Drawable objects. Used for frustum + * culling etc. +*/ +template +class BoundingBoxImpl +{ + public: + typedef VT vec_type; + typedef typename VT::value_type value_type; + + /** Minimum extent. (Smallest X, Y, and Z values of all coordinates.) */ + vec_type _min; + /** Maximum extent. (Greatest X, Y, and Z values of all coordinates.) */ + vec_type _max; + + /** Creates an uninitialized bounding box. */ + inline BoundingBoxImpl() : + _min(FLT_MAX, + FLT_MAX, + FLT_MAX), + _max(-FLT_MAX, + -FLT_MAX, + -FLT_MAX) + {} + + template + inline BoundingBoxImpl(const BoundingBoxImpl& bb) : + _min(bb._min), + _max(bb._max) + {} + + /** Creates a bounding box initialized to the given extents. */ + inline BoundingBoxImpl(value_type xmin, value_type ymin, value_type zmin, + value_type xmax, value_type ymax, value_type zmax) : + _min(xmin,ymin,zmin), + _max(xmax,ymax,zmax) {} + + /** Creates a bounding box initialized to the given extents. */ + inline BoundingBoxImpl(const vec_type& min,const vec_type& max) : + _min(min), + _max(max) {} + + /** Clear the bounding box. Erases existing minimum and maximum extents. */ + inline void init() + { + _min.set(FLT_MAX, + FLT_MAX, + FLT_MAX); + _max.set(-FLT_MAX, + -FLT_MAX, + -FLT_MAX); + } + + inline bool operator == (const BoundingBoxImpl& rhs) const { return _min==rhs._min && _max==rhs._max; } + inline bool operator != (const BoundingBoxImpl& rhs) const { return _min!=rhs._min || _max!=rhs._max; } + + /** Returns true if the bounding box extents are valid, false otherwise. */ + inline bool valid() const + { + return _max.x()>=_min.x() && _max.y()>=_min.y() && _max.z()>=_min.z(); + } + + /** Sets the bounding box extents. */ + inline void set (value_type xmin, value_type ymin, value_type zmin, + value_type xmax, value_type ymax, value_type zmax) + { + _min.set(xmin,ymin,zmin); + _max.set(xmax,ymax,zmax); + } + + /** Sets the bounding box extents. */ + inline void set(const vec_type& min,const vec_type& max) + { + _min = min; + _max = max; + } + + + inline value_type& xMin() { return _min.x(); } + inline value_type xMin() const { return _min.x(); } + + inline value_type& yMin() { return _min.y(); } + inline value_type yMin() const { return _min.y(); } + + inline value_type& zMin() { return _min.z(); } + inline value_type zMin() const { return _min.z(); } + + inline value_type& xMax() { return _max.x(); } + inline value_type xMax() const { return _max.x(); } + + inline value_type& yMax() { return _max.y(); } + inline value_type yMax() const { return _max.y(); } + + inline value_type& zMax() { return _max.z(); } + inline value_type zMax() const { return _max.z(); } + + /** Calculates and returns the bounding box center. */ + inline const vec_type center() const + { + return (_min+_max)*0.5; + } + + /** Calculates and returns the bounding box radius. */ + inline value_type radius() const + { + return sqrt(radius2()); + } + + /** Calculates and returns the squared length of the bounding box radius. + * Note, radius2() is faster to calculate than radius(). */ + inline value_type radius2() const + { + return 0.25*((_max-_min).length2()); + } + + /** Returns a specific corner of the bounding box. + * pos specifies the corner as a number between 0 and 7. + * Each bit selects an axis, X, Y, or Z from least- to + * most-significant. Unset bits select the minimum value + * for that axis, and set bits select the maximum. */ + inline const vec_type corner(unsigned int pos) const + { + return vec_type(pos&1?_max.x():_min.x(),pos&2?_max.y():_min.y(),pos&4?_max.z():_min.z()); + } + + /** Expands the bounding box to include the given coordinate. + * If the box is uninitialized, set its min and max extents to v. */ + inline void expandBy(const vec_type& v) + { + if(v.x()<_min.x()) _min.x() = v.x(); + if(v.x()>_max.x()) _max.x() = v.x(); + + if(v.y()<_min.y()) _min.y() = v.y(); + if(v.y()>_max.y()) _max.y() = v.y(); + + if(v.z()<_min.z()) _min.z() = v.z(); + if(v.z()>_max.z()) _max.z() = v.z(); + } + + /** Expands the bounding box to include the given coordinate. + * If the box is uninitialized, set its min and max extents to + * Vec3(x,y,z). */ + inline void expandBy(value_type x,value_type y,value_type z) + { + if(x<_min.x()) _min.x() = x; + if(x>_max.x()) _max.x() = x; + + if(y<_min.y()) _min.y() = y; + if(y>_max.y()) _max.y() = y; + + if(z<_min.z()) _min.z() = z; + if(z>_max.z()) _max.z() = z; + } + + /** Expands this bounding box to include the given bounding box. + * If this box is uninitialized, set it equal to bb. */ + void expandBy(const BoundingBoxImpl& bb) + { + if (!bb.valid()) return; + + if(bb._min.x()<_min.x()) _min.x() = bb._min.x(); + if(bb._max.x()>_max.x()) _max.x() = bb._max.x(); + + if(bb._min.y()<_min.y()) _min.y() = bb._min.y(); + if(bb._max.y()>_max.y()) _max.y() = bb._max.y(); + + if(bb._min.z()<_min.z()) _min.z() = bb._min.z(); + if(bb._max.z()>_max.z()) _max.z() = bb._max.z(); + } + + /** Expands this bounding box to include the given sphere. + * If this box is uninitialized, set it to include sh. */ + template + void expandBy(const BoundingSphereImpl& sh) + { + if (!sh.valid()) return; + + if(sh._center.x()-sh._radius<_min.x()) _min.x() = sh._center.x()-sh._radius; + if(sh._center.x()+sh._radius>_max.x()) _max.x() = sh._center.x()+sh._radius; + + if(sh._center.y()-sh._radius<_min.y()) _min.y() = sh._center.y()-sh._radius; + if(sh._center.y()+sh._radius>_max.y()) _max.y() = sh._center.y()+sh._radius; + + if(sh._center.z()-sh._radius<_min.z()) _min.z() = sh._center.z()-sh._radius; + if(sh._center.z()+sh._radius>_max.z()) _max.z() = sh._center.z()+sh._radius; + } + + + /** Returns the intersection of this bounding box and the specified bounding box. */ + BoundingBoxImpl intersect(const BoundingBoxImpl& bb) const + { return BoundingBoxImpl(osg::maximum(xMin(),bb.xMin()),osg::maximum(yMin(),bb.yMin()),osg::maximum(zMin(),bb.zMin()), + osg::minimum(xMax(),bb.xMax()),osg::minimum(yMax(),bb.yMax()),osg::minimum(zMax(),bb.zMax())); + + } + + /** Return true if this bounding box intersects the specified bounding box. */ + bool intersects(const BoundingBoxImpl& bb) const + { return osg::maximum(xMin(),bb.xMin()) <= osg::minimum(xMax(),bb.xMax()) && + osg::maximum(yMin(),bb.yMin()) <= osg::minimum(yMax(),bb.yMax()) && + osg::maximum(zMin(),bb.zMin()) <= osg::minimum(zMax(),bb.zMax()); + + } + + /** Returns true if this bounding box contains the specified coordinate. */ + inline bool contains(const vec_type& v) const + { + return valid() && + (v.x()>=_min.x() && v.x()<=_max.x()) && + (v.y()>=_min.y() && v.y()<=_max.y()) && + (v.z()>=_min.z() && v.z()<=_max.z()); + } + + /** Returns true if this bounding box contains the specified coordinate allowing for specific epsilon. */ + inline bool contains(const vec_type& v, value_type epsilon) const + { + return valid() && + ((v.x()+epsilon)>=_min.x() && (v.x()-epsilon)<=_max.x()) && + ((v.y()+epsilon)>=_min.y() && (v.y()-epsilon)<=_max.y()) && + ((v.z()+epsilon)>=_min.z() && (v.z()-epsilon)<=_max.z()); + } +}; + +typedef BoundingBoxImpl BoundingBoxf; +typedef BoundingBoxImpl BoundingBoxd; + +#ifdef OSG_USE_FLOAT_BOUNDINGBOX +typedef BoundingBoxf BoundingBox; +#else +typedef BoundingBoxd BoundingBox; +#endif + +} + +#endif diff --git a/libs/include/android/osg/BoundingSphere b/libs/include/android/osg/BoundingSphere new file mode 100755 index 0000000..eb93ac2 --- /dev/null +++ b/libs/include/android/osg/BoundingSphere @@ -0,0 +1,313 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_BOUNDINGSPHERE +#define OSG_BOUNDINGSPHERE 1 + +#include +#include +#include +#include + +namespace osg { + +template +class BoundingBoxImpl; + +/** General purpose bounding sphere class for enclosing nodes/objects/vertices. + * Bounds internal osg::Nodes in the scene, assists in view frustum culling, + * etc. Similar in function to BoundingBox, it's quicker for evaluating + * culling but generally will not cull as aggressively because it encloses a + * greater volume. +*/ +template +class BoundingSphereImpl +{ + public: + typedef VT vec_type; + typedef typename VT::value_type value_type; + + vec_type _center; + value_type _radius; + + /** Construct a default bounding sphere with radius to -1.0f, representing an invalid/unset bounding sphere.*/ + BoundingSphereImpl() : _center(0.0,0.0,0.0),_radius(-1.0) {} + + /** Creates a bounding sphere initialized to the given extents. */ + BoundingSphereImpl(const vec_type& center, value_type radius) : _center(center),_radius(radius) {} + + /** Creates a bounding sphere initialized to the given extents. */ + BoundingSphereImpl(const BoundingSphereImpl& bs) : _center(bs._center),_radius(bs._radius) {} + + /** Creates a bounding sphere initialized to the given extents. */ + BoundingSphereImpl(const BoundingBoxImpl& bb) : _center(0.0,0.0,0.0),_radius(-1.0) { expandBy(bb); } + + /** Clear the bounding sphere. Reset to default values. */ + inline void init() + { + _center.set(0.0,0.0,0.0); + _radius = -1.0; + } + + /** Returns true of the bounding sphere extents are valid, false + * otherwise. */ + inline bool valid() const { return _radius>=0.0; } + + inline bool operator == (const BoundingSphereImpl& rhs) const { return _center==rhs._center && _radius==rhs._radius; } + inline bool operator != (const BoundingSphereImpl& rhs) const { return _center!=rhs._center || _radius==rhs._radius; } + + /** Set the bounding sphere to the given center/radius using floats. */ + inline void set(const vec_type& center,value_type radius) + { + _center = center; + _radius = radius; + } + + /** Returns the center of the bounding sphere. */ + inline vec_type& center() { return _center; } + + /** Returns the const center of the bounding sphere. */ + inline const vec_type& center() const { return _center; } + + /** Returns the radius of the bounding sphere. */ + inline value_type& radius() { return _radius; } + /** Returns the const radius of the bounding sphere. */ + inline value_type radius() const { return _radius; } + + /** Returns the squared length of the radius. Note, For performance + * reasons, the calling method is responsible for checking to make + * sure the sphere is valid. */ + inline value_type radius2() const { return _radius*_radius; } + + /** Expands the sphere to encompass the given point. Repositions the + * sphere center to minimize the radius increase. If the sphere is + * uninitialized, set its center to v and radius to zero. */ + template + void expandBy(const vector_type& v); + + /** Expands the sphere to encompass the given point. Does not + * reposition the sphere center. If the sphere is + * uninitialized, set its center to v and radius to zero. */ + template + void expandRadiusBy(const vector_type& v); + + /** Expands the sphere to encompass the given sphere. Repositions the + * sphere center to minimize the radius increase. If the sphere is + * uninitialized, set its center and radius to match sh. */ + void expandBy(const BoundingSphereImpl& sh); + + /** Expands the sphere to encompass the given sphere. Does not + * repositions the sphere center. If the sphere is + * uninitialized, set its center and radius to match sh. */ + void expandRadiusBy(const BoundingSphereImpl& sh); + + /** Expands the sphere to encompass the given box. Repositions the + * sphere center to minimize the radius increase. */ + template + void expandBy(const BoundingBoxImpl& bb); + + /** Expands the sphere to encompass the given box. Does not + * repositions the sphere center. */ + template + void expandRadiusBy(const BoundingBoxImpl& bb); + + /** Returns true if v is within the sphere. */ + inline bool contains(const vec_type& v) const + { + return valid() && ((v-_center).length2()<=radius2()); + } + + + /** Returns true if there is a non-empty intersection with the given + * bounding sphere. */ + inline bool intersects( const BoundingSphereImpl& bs ) const + { + return valid() && bs.valid() && + ((_center - bs._center).length2() <= (_radius + bs._radius)*(_radius + bs._radius)); + } + +}; + + +template +template +void BoundingSphereImpl::expandBy(const vector_type& v) +{ + if (valid()) + { + vec_type dv = vec_type(v)-_center; + value_type r = dv.length(); + if (r>_radius) + { + value_type dr = (r-_radius)*0.5; + _center += dv*(dr/r); + _radius += dr; + } // else do nothing as vertex is within sphere. + } + else + { + _center = v; + _radius = 0.0; + } +} + +template +template +void BoundingSphereImpl::expandRadiusBy(const vector_type& v) +{ + if (valid()) + { + value_type r = (vec_type(v)-_center).length(); + if (r>_radius) _radius = r; + // else do nothing as vertex is within sphere. + } + else + { + _center = v; + _radius = 0.0; + } +} + +template +void BoundingSphereImpl::expandBy(const BoundingSphereImpl& sh) +{ + // ignore operation if incomming BoundingSphere is invalid. + if (!sh.valid()) return; + + // This sphere is not set so use the inbound sphere + if (!valid()) + { + _center = sh._center; + _radius = sh._radius; + + return; + } + + + // Calculate d == The distance between the sphere centers + double d = ( _center - sh.center() ).length(); + + // New sphere is already inside this one + if ( d + sh.radius() <= _radius ) + { + return; + } + + // New sphere completely contains this one + if ( d + _radius <= sh.radius() ) + { + _center = sh._center; + _radius = sh._radius; + return; + } + + + // Build a new sphere that completely contains the other two: + // + // The center point lies halfway along the line between the furthest + // points on the edges of the two spheres. + // + // Computing those two points is ugly - so we'll use similar triangles + double new_radius = (_radius + d + sh.radius() ) * 0.5; + double ratio = ( new_radius - _radius ) / d ; + + _center[0] += ( sh.center()[0] - _center[0] ) * ratio; + _center[1] += ( sh.center()[1] - _center[1] ) * ratio; + _center[2] += ( sh.center()[2] - _center[2] ) * ratio; + + _radius = new_radius; + +} + +template +void BoundingSphereImpl::expandRadiusBy(const BoundingSphereImpl& sh) +{ + if (sh.valid()) + { + if (valid()) + { + value_type r = (sh._center-_center).length()+sh._radius; + if (r>_radius) _radius = r; + // else do nothing as vertex is within sphere. + } + else + { + _center = sh._center; + _radius = sh._radius; + } + } +} + +template +template +void BoundingSphereImpl::expandBy(const BoundingBoxImpl& bb) +{ + if (bb.valid()) + { + if (valid()) + { + BoundingBoxImpl newbb(bb); + + for(unsigned int c=0;c<8;++c) + { + vec_type v = bb.corner(c)-_center; // get the direction vector from corner + v.normalize(); // normalise it. + v *= -_radius; // move the vector in the opposite direction distance radius. + v += _center; // move to absolute position. + newbb.expandBy(v); // add it into the new bounding box. + } + + _center = newbb.center(); + _radius = newbb.radius(); + + } + else + { + _center = bb.center(); + _radius = bb.radius(); + } + } +} + +template +template +void BoundingSphereImpl::expandRadiusBy(const BoundingBoxImpl& bb) +{ + if (bb.valid()) + { + if (valid()) + { + for(unsigned int c=0;c<8;++c) + { + expandRadiusBy(bb.corner(c)); + } + } + else + { + _center = bb.center(); + _radius = bb.radius(); + } + } +} + +typedef BoundingSphereImpl BoundingSpheref; +typedef BoundingSphereImpl BoundingSphered; + +#ifdef OSG_USE_FLOAT_BOUNDINGSPHERE + typedef BoundingSpheref BoundingSphere; +#else + typedef BoundingSphered BoundingSphere; +#endif +} + +#endif diff --git a/libs/include/android/osg/BoundsChecking b/libs/include/android/osg/BoundsChecking new file mode 100755 index 0000000..2b6b8c7 --- /dev/null +++ b/libs/include/android/osg/BoundsChecking @@ -0,0 +1,216 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_BOUNDSCHECKING +#define OSG_BOUNDSCHECKING 1 + +#include + +namespace osg { + + +/** If value is greater than or equal to minValue do nothing - legal value, + * Otherwise set value to minValue, and warn that valueName was clamped. + * Note this is effectively A=max(A,B). */ +template +inline void clampGEQUAL(T& value,const T minValue,const char* valueName) +{ + if (value +inline void clampLEQUAL(T& value,const T maxValue,const char* valueName) +{ + if (value>maxValue) + { + notify(WARN) << "Warning: "< +inline void clampBetweenRange(T& value,const T minValue,const T maxValue,const char* valueName) +{ + if (valuemaxValue) + { + notify(WARN) << "Warning: "< +inline void clampArrayElementGEQUAL(A& value,unsigned int i,const T minValue,const char* valueName) +{ + if (value[i] +inline void clampArrayElementLEQUAL(A& value,unsigned int i,const T maxValue,const char* valueName) +{ + if (value[i]>maxValue) + { + notify(WARN) << "Warning: "< +inline void clampArrayElementBetweenRange(A& value,unsigned int i,const T minValue,const T maxValue,const char* valueName) +{ + if (value[i]maxValue) + { + notify(WARN) << "Warning: "< +inline void clampArrayElementsGEQUAL(A& value,unsigned int first,unsigned int last,const T minValue,const char* valueName) +{ + for(unsigned int i=first;i<=last;++i) + clampArrayElementGEQUAL(value,i,minValue,valueName); +} + +/** For each element of value[] in the range (first,last), if the element is + * less than or equal to maxValue do nothing - legal value, Otherwise clamp + * the element to maxValue, and warn that valueName[i] was clamped. */ +template +inline void clampArrayElementsLEQUAL(A& value,unsigned int first,unsigned int last,const T maxValue,const char* valueName) +{ + for(unsigned int i=first;i<=last;++i) + clampArrayElementLEQUAL(value,i,maxValue,valueName); +} + +/** For each element of value[] in the range (first,last), if the element is + * between or equal to minValue and maxValue do nothing - legal value, + * Otherwise clamp the element to the range and warn that valueName[i] was + * clamped. Equivalent to calling + * clampArrayElementsGEQUAL( value, first, last, minValue, valueName); + * clampArrayElementsLEQUAL( value, first, last, maxValue, valueName); */ +template +inline void clampArrayElementsBetweenRange(A& value,unsigned int first,unsigned int last,const T minValue,const T maxValue,const char* valueName) +{ + for(unsigned int i=first;i<=last;++i) + clampArrayElementBetweenRange(value,i,minValue,maxValue,valueName); +} + + +/** For each element of the three-element array value[], if the element is + * greater than or equal to minValue do nothing - legal value, Otherwise + * clamp the element to minValue, and warn that valueName[i] was clamped. */ +template +inline void clampArray3GEQUAL(A& value,const T minValue,const char* valueName) +{ + clampArrayElementsGEQUAL(value,0u,2u,minValue,valueName); +} + +/** For each element of the three-element array value[], if the element is + * less than or equal to maxValue do nothing - legal value, Otherwise clamp + * the element to maxValue, and warn that valueName[i] was clamped. */ +template +inline void clampArray3LEQUAL(A& value,const T maxValue,const char* valueName) +{ + clampArrayElementsLEQUAL(value,0u,2u,maxValue,valueName); +} + +/** For each element of the three-element array value[], if the element is + * between or equal to minValue and maxValue do nothing - legal value, + * Otherwise clamp the element to the range and warn that valueName[i] was + * clamped. Equivalent to calling + * clampArray3GEQUAL( value, minValue, valueName); + * clampArray3LEQUAL( value, maxValue, valueName); */ +template +inline void clampArray3BetweenRange(A& value,const T minValue,const T maxValue,const char* valueName) +{ + clampArrayElementsBetweenRange(value,0u,2u,minValue,maxValue,valueName); +} + + + +/** For each element of the four-element array value[], if the element is + * greater than or equal to minValue do nothing - legal value, Otherwise + * clamp the element to minValue, and warn that valueName[i] was clamped. */ +template +inline void clampArray4GEQUAL(A& value,const T minValue,const char* valueName) +{ + clampArrayElementsGEQUAL(value,0u,3u,minValue,valueName); +} + +/** For each element of the four-element array value[], if the element is + * less than or equal to maxValue do nothing - legal value, Otherwise clamp + * the element to maxValue, and warn that valueName[i] was clamped. */ +template +inline void clampArray4LEQUAL(A& value,const T maxValue,const char* valueName) +{ + clampArrayElementsLEQUAL(value,0u,3u,maxValue,valueName); +} + +/** For each element of the four-element array value[], if the element is + * between or equal to minValue and maxValue do nothing - legal value, + * Otherwise clamp the element to the range and warn that valueName[i] was + * clamped. Equivalent to calling + * clampArray4GEQUAL( value, minValue, valueName); + * clampArray4LEQUAL( value, maxValue, valueName); */ +template +inline void clampArray4BetweenRange(A& value,const T minValue,const T maxValue,const char* valueName) +{ + clampArrayElementsBetweenRange(value,0u,3u,minValue,maxValue,valueName); +} + +} + +#endif diff --git a/libs/include/android/osg/BufferIndexBinding b/libs/include/android/osg/BufferIndexBinding new file mode 100755 index 0000000..83a4594 --- /dev/null +++ b/libs/include/android/osg/BufferIndexBinding @@ -0,0 +1,169 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * Copyright (C) 2010 Tim Moore + * Copyright (C) 2012 David Callu + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_BUFFERINDEXBINDING +#define OSG_BUFFERINDEXBINDING 1 + +#include +#include +#include +#include + +#ifndef GL_TRANSFORM_FEEDBACK_BUFFER + #define GL_TRANSFORM_FEEDBACK_BUFFER 0x8C8E +#endif + + +namespace osg { + +class State; + +/** Encapsulate binding buffer objects to index targets. This + * specifically supports the uniform buffer and transform feedback + * targets. + */ + +// Common implementation superclass +class OSG_EXPORT BufferIndexBinding : public StateAttribute +{ + protected: + BufferIndexBinding(GLenum target, GLuint index); + BufferIndexBinding(GLenum target, GLuint index, BufferObject* bo, GLintptr offset, + GLsizeiptr size); + BufferIndexBinding(const BufferIndexBinding& rhs, const CopyOp& copyop=CopyOp::SHALLOW_COPY); + public: + // The member value is part of the key to this state attribute in + // the State class. Using the index target, we can seperately + // track the bindings for many different index targets. + virtual unsigned getMember() const { return static_cast(_index); } + + GLenum getTarget() const { return _target; } + /** Get the index target. + */ + GLuint getIndex() const { return _index; } + /** Set the buffer object that will be bound to the index target. + */ + void setBufferObject(BufferObject *bo) { _bufferObject = bo; } + /** Get the buffer object to be bound. + */ + BufferObject* getBufferObject() const { return _bufferObject.get(); } + /** Set the starting offset into the buffer object for data for + the indexed target. Note: the required alignment on the offset + may be quite large (e.g., 256 bytes on NVidia 8600M). This + should be checked with glGetIntegerv(GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT...). + */ + void setOffset(GLintptr offset) { _offset = offset; } + GLintptr getOffset() const { return _offset; } + /** Set the size of data for the indexed target. + */ + void setSize(GLsizeiptr size) { _size = size; } + GLsizeiptr getSize() const { return _size; } + virtual void apply(State& state) const; + protected: + virtual ~BufferIndexBinding(); + const GLenum _target; + const GLuint _index; + ref_ptr _bufferObject; + GLintptr _offset; + GLsizeiptr _size; +}; + +/** StateAttribute for binding a uniform buffer index target. + */ +class OSG_EXPORT UniformBufferBinding : public BufferIndexBinding +{ + public: + UniformBufferBinding(); + UniformBufferBinding(GLuint index); + /** Create a binding for a uniform buffer index target. + * @param index the index target + * @param bo associated buffer object + * @param offset offset into buffer object + * @param size size of data in buffer object + */ + UniformBufferBinding(GLuint index, BufferObject* bo, GLintptr offset, GLsizeiptr size); + UniformBufferBinding(const UniformBufferBinding& rhs, const CopyOp& copyop=CopyOp::SHALLOW_COPY); + META_StateAttribute(osg, UniformBufferBinding, UNIFORMBUFFERBINDING); + + virtual int compare(const StateAttribute& bb) const + { + COMPARE_StateAttribute_Types(UniformBufferBinding, bb) + + COMPARE_StateAttribute_Parameter(_target) + COMPARE_StateAttribute_Parameter(_index) + COMPARE_StateAttribute_Parameter(_bufferObject) + COMPARE_StateAttribute_Parameter(_offset) + COMPARE_StateAttribute_Parameter(_size) + return 0; + } +}; + +/** StateAttribute for binding a transform feedback index target. + */ +class OSG_EXPORT TransformFeedbackBufferBinding : public BufferIndexBinding +{ + public: + TransformFeedbackBufferBinding(GLuint index = 0); + TransformFeedbackBufferBinding(GLuint index, BufferObject* bo, GLintptr offset, GLsizeiptr size); + TransformFeedbackBufferBinding(const TransformFeedbackBufferBinding& rhs, const CopyOp& copyop=CopyOp::SHALLOW_COPY); + META_StateAttribute(osg, TransformFeedbackBufferBinding, TRANSFORMFEEDBACKBUFFERBINDING); + + virtual int compare(const StateAttribute& bb) const + { + COMPARE_StateAttribute_Types(TransformFeedbackBufferBinding, bb) + + COMPARE_StateAttribute_Parameter(_target) + COMPARE_StateAttribute_Parameter(_index) + COMPARE_StateAttribute_Parameter(_bufferObject) + COMPARE_StateAttribute_Parameter(_offset) + COMPARE_StateAttribute_Parameter(_size) + return 0; + } +}; + +/** StateAttribute for binding a atomic counter buffer index target. + */ +class OSG_EXPORT AtomicCounterBufferBinding : public BufferIndexBinding +{ + public: + AtomicCounterBufferBinding(GLuint index=0); + /** Create a binding for a atomic counter buffer index target. + * @param index the index target + * @param bo associated buffer object + * @param offset offset into buffer object + * @param size size of data in buffer object + */ + AtomicCounterBufferBinding(GLuint index, BufferObject* bo, GLintptr offset, GLsizeiptr size); + AtomicCounterBufferBinding(const AtomicCounterBufferBinding& rhs, const CopyOp& copyop=CopyOp::SHALLOW_COPY); + META_StateAttribute(osg, AtomicCounterBufferBinding, ATOMICCOUNTERBUFFERBINDING); + + void readData(osg::State & state, osg::UIntArray & uintArray) const; + + virtual int compare(const StateAttribute& bb) const + { + COMPARE_StateAttribute_Types(AtomicCounterBufferBinding, bb) + + COMPARE_StateAttribute_Parameter(_target) + COMPARE_StateAttribute_Parameter(_index) + COMPARE_StateAttribute_Parameter(_bufferObject) + COMPARE_StateAttribute_Parameter(_offset) + COMPARE_StateAttribute_Parameter(_size) + return 0; + } +}; + +} // namespace osg + +#endif diff --git a/libs/include/android/osg/BufferObject b/libs/include/android/osg/BufferObject new file mode 100755 index 0000000..cdb668a --- /dev/null +++ b/libs/include/android/osg/BufferObject @@ -0,0 +1,876 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * Copyright (C) 2012 David Callu + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_BUFFEROBJECT +#define OSG_BUFFEROBJECT 1 + +#include +#include +#include +#include + +#include +#include +#include + +// identify GLES 1.1 +#if (defined(GL_VERSION_ES_CM_1_0) && GL_VERSION_ES_CM_1_0 > 0) || \ + (defined(GL_VERSION_ES_CM_1_1) && GL_VERSION_ES_CM_1_1 > 0) + + #define OPENGLES_1_1_FOUND 1 + +#endif + +// for compatibility with gl.h headers that don't support VBO, +//GL_VERSION_1_5 and GL_ARB_vertex_buffer_object provide these types for OpenGL +//all ES versions except GL_OES_VERSION_1_0 provide these types for OpenGL ES +#if !defined(GL_VERSION_1_5) && !defined(GL_ARB_vertex_buffer_object) \ + && !defined(GL_ES_VERSION_2_0) && !defined(OPENGLES_1_1_FOUND) + #if defined(_WIN64) + typedef __int64 GLintptr; + typedef __int64 GLsizeiptr; + #elif defined(__ia64__) || defined(__x86_64__) || defined(ANDROID) + typedef long int GLintptr; + typedef long int GLsizeiptr; + #else + typedef int GLintptr; + typedef int GLsizeiptr; + #endif +#endif + +#ifndef GL_ARB_vertex_buffer_object + #define GL_ARB_vertex_buffer_object + + typedef GLintptr GLintptrARB; + typedef GLsizeiptr GLsizeiptrARB; + + #define GL_ARRAY_BUFFER_ARB 0x8892 + #define GL_ELEMENT_ARRAY_BUFFER_ARB 0x8893 + #define GL_ARRAY_BUFFER_BINDING_ARB 0x8894 + #define GL_ELEMENT_ARRAY_BUFFER_BINDING_ARB 0x8895 + #define GL_VERTEX_ARRAY_BUFFER_BINDING_ARB 0x8896 + #define GL_NORMAL_ARRAY_BUFFER_BINDING_ARB 0x8897 + #define GL_COLOR_ARRAY_BUFFER_BINDING_ARB 0x8898 + #define GL_INDEX_ARRAY_BUFFER_BINDING_ARB 0x8899 + #define GL_TEXTURE_COORD_ARRAY_BUFFER_BINDING_ARB 0x889A + #define GL_EDGE_FLAG_ARRAY_BUFFER_BINDING_ARB 0x889B + #define GL_SECONDARY_COLOR_ARRAY_BUFFER_BINDING_ARB 0x889C + #define GL_FOG_COORDINATE_ARRAY_BUFFER_BINDING_ARB 0x889D + #define GL_WEIGHT_ARRAY_BUFFER_BINDING_ARB 0x889E + #define GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING_ARB 0x889F + #define GL_STREAM_DRAW_ARB 0x88E0 + #define GL_STREAM_READ_ARB 0x88E1 + #define GL_STREAM_COPY_ARB 0x88E2 + #define GL_STATIC_DRAW_ARB 0x88E4 + #define GL_STATIC_READ_ARB 0x88E5 + #define GL_STATIC_COPY_ARB 0x88E6 + #define GL_DYNAMIC_DRAW_ARB 0x88E8 + #define GL_DYNAMIC_READ_ARB 0x88E9 + #define GL_DYNAMIC_COPY_ARB 0x88EA + #define GL_READ_ONLY_ARB 0x88B8 + #define GL_WRITE_ONLY_ARB 0x88B9 + #define GL_READ_WRITE_ARB 0x88BA + #define GL_BUFFER_SIZE_ARB 0x8764 + #define GL_BUFFER_USAGE_ARB 0x8765 + #define GL_BUFFER_ACCESS_ARB 0x88BB + #define GL_BUFFER_MAPPED_ARB 0x88BC + #define GL_BUFFER_MAP_POINTER_ARB 0x88BD +#endif + +#ifndef GL_VERSION_1_5 + #define GL_STREAM_DRAW 0x88E0 + #define GL_STREAM_READ 0x88E1 + #define GL_STREAM_COPY 0x88E2 + #define GL_STATIC_DRAW 0x88E4 + #define GL_STATIC_READ 0x88E5 + #define GL_STATIC_COPY 0x88E6 + #define GL_DYNAMIC_DRAW 0x88E8 + #define GL_DYNAMIC_READ 0x88E9 + #define GL_DYNAMIC_COPY 0x88EA +#endif + +#ifndef GL_VERSION_2_1 + #define GL_PIXEL_PACK_BUFFER 0x88EB + #define GL_PIXEL_UNPACK_BUFFER 0x88EC + #define GL_PIXEL_PACK_BUFFER_BINDING 0x88ED + #define GL_PIXEL_UNPACK_BUFFER_BINDING 0x88EF +#endif + + +#ifndef GL_ARB_pixel_buffer_object + #define GL_PIXEL_PACK_BUFFER_ARB 0x88EB + #define GL_PIXEL_UNPACK_BUFFER_ARB 0x88EC + #define GL_PIXEL_PACK_BUFFER_BINDING_ARB 0x88ED + #define GL_PIXEL_UNPACK_BUFFER_BINDING_ARB 0x88EF +#endif + +namespace osg +{ + +class State; +class BufferData; +class BufferObject; + +class BufferObjectProfile +{ + public: + BufferObjectProfile(): + _target(0), + _usage(0), + _size(0) {} + + BufferObjectProfile(GLenum target, GLenum usage, unsigned int size): + _target(target), + _usage(usage), + _size(size) {} + + BufferObjectProfile(const BufferObjectProfile& bpo): + _target(bpo._target), + _usage(bpo._usage), + _size(bpo._size) {} + + bool operator < (const BufferObjectProfile& rhs) const + { + if (_target < rhs._target) return true; + else if (_target > rhs._target) return false; + if (_usage < rhs._usage) return true; + else if (_usage > rhs._usage) return false; + return _size < rhs._size; + } + + bool operator == (const BufferObjectProfile& rhs) const + { + return (_target == rhs._target) && + (_usage == rhs._usage) && + (_size == rhs._size); + } + + void setProfile(GLenum target, GLenum usage, unsigned int size) + { + _target = target; + _usage = usage; + _size = size; + } + + BufferObjectProfile& operator = (const BufferObjectProfile& rhs) + { + _target = rhs._target; + _usage = rhs._usage; + _size = rhs._size; + return *this; + } + + GLenum _target; + GLenum _usage; + GLenum _size; +}; + +// forward declare +class GLBufferObjectSet; +class GLBufferObjectManager; + +class OSG_EXPORT GLBufferObject : public Referenced +{ + public: + + GLBufferObject(unsigned int contextID, BufferObject* bufferObject, unsigned int glObjectID=0); + + void setProfile(const BufferObjectProfile& profile) { _profile = profile; } + const BufferObjectProfile& getProfile() const { return _profile; } + + void setBufferObject(BufferObject* bufferObject); + BufferObject* getBufferObject() { return _bufferObject; } + + struct BufferEntry + { + BufferEntry(): numRead(0), modifiedCount(0),dataSize(0),offset(0),dataSource(0) {} + + BufferEntry(const BufferEntry& rhs): + numRead(rhs.numRead), + modifiedCount(rhs.modifiedCount), + dataSize(rhs.dataSize), + offset(rhs.offset), + dataSource(rhs.dataSource) {} + + BufferEntry& operator = (const BufferEntry& rhs) + { + if (&rhs==this) return *this; + numRead = rhs.numRead; + modifiedCount = rhs.modifiedCount; + dataSize = rhs.dataSize; + offset = rhs.offset; + dataSource = rhs.dataSource; + return *this; + } + + unsigned int getNumClients() const; + + unsigned int numRead; + unsigned int modifiedCount; + unsigned int dataSize; + unsigned int offset; + BufferData* dataSource; + }; + + inline unsigned int getContextID() const { return _contextID; } + + inline GLuint& getGLObjectID() { return _glObjectID; } + inline GLuint getGLObjectID() const { return _glObjectID; } + inline GLsizeiptrARB getOffset(unsigned int i) const { return _bufferEntries[i].offset; } + + inline void bindBuffer(); + + inline void unbindBuffer() + { + _extensions->glBindBuffer(_profile._target,0); + } + + inline bool isDirty() const { return _dirty; } + + void dirty() { _dirty = true; } + + void clear(); + + void compileBuffer(); + + void deleteGLObject(); + + void assign(BufferObject* bufferObject); + + bool isPBOSupported() const { return _extensions->isPBOSupported(); } + + static GLBufferObject* createGLBufferObject(unsigned int contextID, const BufferObject* bufferObject); + + static void deleteAllBufferObjects(unsigned int contextID); + static void discardAllBufferObjects(unsigned int contextID); + static void flushAllDeletedBufferObjects(unsigned int contextID); + static void discardAllDeletedBufferObjects(unsigned int contextID); + static void flushDeletedBufferObjects(unsigned int contextID,double currentTime, double& availbleTime); + static void releaseGLBufferObject(unsigned int contextID, GLBufferObject* to); + + /** Extensions class which encapsulates the querying of extensions and + * associated function pointers, and provide convenience wrappers to + * check for the extensions or use the associated functions.*/ + class OSG_EXPORT Extensions : public osg::Referenced + { + public: + Extensions(unsigned int contextID); + + Extensions(const Extensions& rhs); + + void lowestCommonDenominator(const Extensions& rhs); + + void setupGLExtensions(unsigned int contextID); + + bool isBufferObjectSupported() const { return _glGenBuffers!=0; } + bool isPBOSupported() const { return _isPBOSupported; } + bool isUniformBufferObjectSupported() const { return _isUniformBufferObjectSupported; } + bool isTBOSupported() const { return _isTBOSupported; } + + void glGenBuffers (GLsizei n, GLuint *buffers) const; + void glBindBuffer (GLenum target, GLuint buffer) const; + void glBufferData (GLenum target, GLsizeiptrARB size, const GLvoid *data, GLenum usage) const; + void glBufferSubData (GLenum target, GLintptrARB offset, GLsizeiptrARB size, const GLvoid *data) const; + void glDeleteBuffers (GLsizei n, const GLuint *buffers) const; + GLboolean glIsBuffer (GLuint buffer) const; + void glGetBufferSubData (GLenum target, GLintptrARB offset, GLsizeiptrARB size, GLvoid *data) const; + GLvoid* glMapBuffer (GLenum target, GLenum access) const; + GLboolean glUnmapBuffer (GLenum target) const; + void glGetBufferParameteriv (GLenum target, GLenum pname, GLint *params) const; + void glGetBufferPointerv (GLenum target, GLenum pname, GLvoid* *params) const; + void glBindBufferRange (GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size); + void glBindBufferBase (GLenum target, GLuint index, GLuint buffer); + void glTexBuffer( GLenum target, GLenum internalFormat, GLuint buffer ) const; + + protected: + + typedef void (GL_APIENTRY * GenBuffersProc) (GLsizei n, GLuint *buffers); + typedef void (GL_APIENTRY * BindBufferProc) (GLenum target, GLuint buffer); + typedef void (GL_APIENTRY * BufferDataProc) (GLenum target, GLsizeiptrARB size, const GLvoid *data, GLenum usage); + typedef void (GL_APIENTRY * BufferSubDataProc) (GLenum target, GLintptrARB offset, GLsizeiptrARB size, const GLvoid *data); + typedef void (GL_APIENTRY * DeleteBuffersProc) (GLsizei n, const GLuint *buffers); + typedef GLboolean (GL_APIENTRY * IsBufferProc) (GLuint buffer); + typedef void (GL_APIENTRY * GetBufferSubDataProc) (GLenum target, GLintptrARB offset, GLsizeiptrARB size, GLvoid *data); + typedef GLvoid* (GL_APIENTRY * MapBufferProc) (GLenum target, GLenum access); + typedef GLboolean (GL_APIENTRY * UnmapBufferProc) (GLenum target); + typedef void (GL_APIENTRY * GetBufferParameterivProc) (GLenum target, GLenum pname, GLint *params); + typedef void (GL_APIENTRY * GetBufferPointervProc) (GLenum target, GLenum pname, GLvoid* *params); + typedef void (GL_APIENTRY * BindBufferRangeProc) (GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size); + typedef void (GL_APIENTRY * BindBufferBaseProc) (GLenum target, GLuint index, GLuint buffer); + typedef void (GL_APIENTRY *TexBufferProc ) ( GLenum target, GLenum internalFormat, GLuint buffer ); + + + GenBuffersProc _glGenBuffers; + BindBufferProc _glBindBuffer; + BufferDataProc _glBufferData; + BufferSubDataProc _glBufferSubData; + DeleteBuffersProc _glDeleteBuffers; + IsBufferProc _glIsBuffer; + GetBufferSubDataProc _glGetBufferSubData; + MapBufferProc _glMapBuffer; + UnmapBufferProc _glUnmapBuffer; + GetBufferParameterivProc _glGetBufferParameteriv; + GetBufferPointervProc _glGetBufferPointerv; + BindBufferRangeProc _glBindBufferRange; + BindBufferBaseProc _glBindBufferBase; + TexBufferProc _glTexBuffer; + + bool _isPBOSupported; + bool _isUniformBufferObjectSupported; + bool _isTBOSupported; + }; + + /** Function to call to get the extension of a specified context. + * If the Extension object for that context has not yet been created + * and the 'createIfNotInitalized' flag been set to false then returns NULL. + * If 'createIfNotInitalized' is true then the Extensions object is + * automatically created. However, in this case the extension object is + * only created with the graphics context associated with ContextID..*/ + static Extensions* getExtensions(unsigned int contextID,bool createIfNotInitalized); + + /** setExtensions allows users to override the extensions across graphics contexts. + * typically used when you have different extensions supported across graphics pipes + * but need to ensure that they all use the same low common denominator extensions.*/ + static void setExtensions(unsigned int contextID,Extensions* extensions); + + bool hasAllBufferDataBeenRead() const; + + void setBufferDataHasBeenRead(const osg::BufferData* bd); + + protected: + + virtual ~GLBufferObject(); + + unsigned int computeBufferAlignment(unsigned int pos, unsigned int bufferAlignment) const + { + if (bufferAlignment<2) return pos; + if ((pos%bufferAlignment)==0) return pos; + return ((pos/bufferAlignment)+1)*bufferAlignment; + } + + unsigned int _contextID; + GLuint _glObjectID; + + BufferObjectProfile _profile; + unsigned int _allocatedSize; + + bool _dirty; + + typedef std::vector BufferEntries; + BufferEntries _bufferEntries; + + BufferObject* _bufferObject; + + public: + + GLBufferObjectSet* _set; + GLBufferObject* _previous; + GLBufferObject* _next; + unsigned int _frameLastUsed; + + public: + Extensions* _extensions; + +}; + +typedef std::list< ref_ptr > GLBufferObjectList; + +class OSG_EXPORT GLBufferObjectSet : public Referenced +{ + public: + GLBufferObjectSet(GLBufferObjectManager* parent, const BufferObjectProfile& profile); + + const BufferObjectProfile& getProfile() const { return _profile; } + + void handlePendingOrphandedGLBufferObjects(); + + void deleteAllGLBufferObjects(); + void discardAllGLBufferObjects(); + void flushAllDeletedGLBufferObjects(); + void discardAllDeletedGLBufferObjects(); + void flushDeletedGLBufferObjects(double currentTime, double& availableTime); + + GLBufferObject* takeFromOrphans(BufferObject* bufferObject); + GLBufferObject* takeOrGenerate(BufferObject* bufferObject); + + void moveToBack(GLBufferObject* to); + void addToBack(GLBufferObject* to); + void orphan(GLBufferObject* to); + void remove(GLBufferObject* to); + void moveToSet(GLBufferObject* to, GLBufferObjectSet* set); + + unsigned int size() const { return _profile._size * _numOfGLBufferObjects; } + + bool makeSpace(unsigned int& size); + + bool checkConsistency() const; + + GLBufferObjectManager* getParent() { return _parent; } + + unsigned int computeNumGLBufferObjectsInList() const; + unsigned int getNumOfGLBufferObjects() const { return _numOfGLBufferObjects; } + unsigned int getNumOrphans() const { return static_cast(_orphanedGLBufferObjects.size()); } + unsigned int getNumPendingOrphans() const { return static_cast(_pendingOrphanedGLBufferObjects.size()); } + + + protected: + + virtual ~GLBufferObjectSet(); + + OpenThreads::Mutex _mutex; + + GLBufferObjectManager* _parent; + unsigned int _contextID; + BufferObjectProfile _profile; + unsigned int _numOfGLBufferObjects; + GLBufferObjectList _orphanedGLBufferObjects; + GLBufferObjectList _pendingOrphanedGLBufferObjects; + + GLBufferObject* _head; + GLBufferObject* _tail; +}; + +class OSG_EXPORT GLBufferObjectManager : public osg::Referenced +{ + public: + GLBufferObjectManager(unsigned int contextID); + + unsigned int getContextID() const { return _contextID; } + + + void setNumberActiveGLBufferObjects(unsigned int size) { _numActiveGLBufferObjects = size; } + unsigned int& getNumberActiveGLBufferObjects() { return _numActiveGLBufferObjects; } + unsigned int getNumberActiveGLBufferObjects() const { return _numActiveGLBufferObjects; } + + void setNumberOrphanedGLBufferObjects(unsigned int size) { _numOrphanedGLBufferObjects = size; } + unsigned int& getNumberOrphanedGLBufferObjects() { return _numOrphanedGLBufferObjects; } + unsigned int getNumberOrphanedGLBufferObjects() const { return _numOrphanedGLBufferObjects; } + + void setCurrGLBufferObjectPoolSize(unsigned int size) { _currGLBufferObjectPoolSize = size; } + unsigned int& getCurrGLBufferObjectPoolSize() { return _currGLBufferObjectPoolSize; } + unsigned int getCurrGLBufferObjectPoolSize() const { return _currGLBufferObjectPoolSize; } + + void setMaxGLBufferObjectPoolSize(unsigned int size); + unsigned int getMaxGLBufferObjectPoolSize() const { return _maxGLBufferObjectPoolSize; } + + bool hasSpace(unsigned int size) const { return (_currGLBufferObjectPoolSize+size)<=_maxGLBufferObjectPoolSize; } + bool makeSpace(unsigned int size); + + GLBufferObject* generateGLBufferObject(const osg::BufferObject* bufferObject); + + void handlePendingOrphandedGLBufferObjects(); + + void deleteAllGLBufferObjects(); + void discardAllGLBufferObjects(); + void flushAllDeletedGLBufferObjects(); + void discardAllDeletedGLBufferObjects(); + void flushDeletedGLBufferObjects(double currentTime, double& availableTime); + void releaseGLBufferObject(GLBufferObject* to); + + GLBufferObjectSet* getGLBufferObjectSet(const BufferObjectProfile& profile); + + void newFrame(osg::FrameStamp* fs); + void resetStats(); + void reportStats(std::ostream& out); + void recomputeStats(std::ostream& out); + + unsigned int& getFrameNumber() { return _frameNumber; } + unsigned int& getNumberFrames() { return _numFrames; } + + unsigned int& getNumberDeleted() { return _numDeleted; } + double& getDeleteTime() { return _deleteTime; } + + unsigned int& getNumberGenerated() { return _numGenerated; } + double& getGenerateTime() { return _generateTime; } + + unsigned int& getNumberApplied() { return _numApplied; } + double& getApplyTime() { return _applyTime; } + + static osg::ref_ptr& getGLBufferObjectManager(unsigned int contextID); + + protected: + + typedef std::map< BufferObjectProfile, osg::ref_ptr > GLBufferObjectSetMap; + unsigned int _contextID; + unsigned int _numActiveGLBufferObjects; + unsigned int _numOrphanedGLBufferObjects; + unsigned int _currGLBufferObjectPoolSize; + unsigned int _maxGLBufferObjectPoolSize; + GLBufferObjectSetMap _glBufferObjectSetMap; + + unsigned int _frameNumber; + + unsigned int _numFrames; + unsigned int _numDeleted; + double _deleteTime; + + unsigned int _numGenerated; + double _generateTime; + + unsigned int _numApplied; + double _applyTime; + +}; + + +class OSG_EXPORT BufferObject : public Object +{ + public: + + BufferObject(); + + /** Copy constructor using CopyOp to manage deep vs shallow copy.*/ + BufferObject(const BufferObject& bo,const CopyOp& copyop=CopyOp::SHALLOW_COPY); + + virtual bool isSameKindAs(const Object* obj) const { return dynamic_cast(obj)!=NULL; } + virtual const char* libraryName() const { return "osg"; } + virtual const char* className() const { return "BufferObject"; } + + void setTarget(GLenum target) { _profile._target = target; } + GLenum getTarget() const { return _profile._target; } + + /** Set what type of usage the buffer object will have. Options are: + * GL_STREAM_DRAW, GL_STREAM_READ, GL_STREAM_COPY, + * GL_STATIC_DRAW, GL_STATIC_READ, GL_STATIC_COPY, + * GL_DYNAMIC_DRAW, GL_DYNAMIC_READ, or GL_DYNAMIC_COPY. + */ + void setUsage(GLenum usage) { _profile._usage = usage; } + + /** Get the type of usage the buffer object has been set up for.*/ + GLenum getUsage() const { return _profile._usage; } + + BufferObjectProfile& getProfile() { return _profile; } + const BufferObjectProfile& getProfile() const { return _profile; } + + + /** Set whether the BufferObject should use a GLBufferObject just for copying the BufferData and release it immmediately so that it may be reused.*/ + void setCopyDataAndReleaseGLBufferObject(bool copyAndRelease) { _copyDataAndReleaseGLBufferObject = copyAndRelease; } + + /** Get whether the BufferObject should use a GLBufferObject just for copying the BufferData and release it immmediately.*/ + bool getCopyDataAndReleaseGLBufferObject() const { return _copyDataAndReleaseGLBufferObject; } + + + void dirty(); + + /** Resize any per context GLObject buffers to specified size. */ + virtual void resizeGLObjectBuffers(unsigned int maxSize); + + /** If State is non-zero, this function releases OpenGL objects for + * the specified graphics context. Otherwise, releases OpenGL objects + * for all graphics contexts. */ + void releaseGLObjects(State* state=0) const; + + unsigned int addBufferData(BufferData* bd); + void removeBufferData(unsigned int index); + void removeBufferData(BufferData* bd); + + void setBufferData(unsigned int index, BufferData* bd); + BufferData* getBufferData(unsigned int index) { return _bufferDataList[index]; } + const BufferData* getBufferData(unsigned int index) const { return _bufferDataList[index]; } + + unsigned int getNumBufferData() const { return static_cast(_bufferDataList.size()); } + + void setGLBufferObject(unsigned int contextID, GLBufferObject* glbo) { _glBufferObjects[contextID] = glbo; } + + GLBufferObject* getGLBufferObject(unsigned int contextID) const { return _glBufferObjects[contextID].get(); } + + GLBufferObject* getOrCreateGLBufferObject(unsigned int contextID) const + { + if (!_glBufferObjects[contextID]) _glBufferObjects[contextID] = GLBufferObject::createGLBufferObject(contextID, this); + return _glBufferObjects[contextID].get(); + } + + unsigned int computeRequiredBufferSize() const; + + /** deprecated, provided for backwards compatibility.*/ + static void deleteBufferObject(unsigned int contextID,GLuint globj); + + protected: + + ~BufferObject(); + + typedef std::vector< BufferData* > BufferDataList; + typedef osg::buffered_object< osg::ref_ptr > GLBufferObjects; + + BufferObjectProfile _profile; + + bool _copyDataAndReleaseGLBufferObject; + + BufferDataList _bufferDataList; + + mutable GLBufferObjects _glBufferObjects; +}; + +class OSG_EXPORT BufferData : public Object +{ + public: + + BufferData(): + Object(true), + _modifiedCount(0), + _bufferIndex(0), + _numClients(0) {} + + /** Copy constructor using CopyOp to manage deep vs shallow copy.*/ + BufferData(const BufferData& bd,const CopyOp& copyop=CopyOp::SHALLOW_COPY): + osg::Object(bd,copyop), + _modifiedCount(0), + _bufferIndex(0), + _modifiedCallback(bd._modifiedCallback), + _numClients(0) {} + + virtual bool isSameKindAs(const Object* obj) const { return dynamic_cast(obj)!=NULL; } + virtual const char* libraryName() const { return "osg"; } + virtual const char* className() const { return "BufferData"; } + + virtual const GLvoid* getDataPointer() const = 0; + virtual unsigned int getTotalDataSize() const = 0; + + virtual osg::Array* asArray() { return 0; } + virtual const osg::Array* asArray() const { return 0; } + + virtual osg::PrimitiveSet* asPrimitiveSet() { return 0; } + virtual const osg::PrimitiveSet* asPrimitiveSet() const { return 0; } + + virtual osg::Image* asImage() { return 0; } + virtual const osg::Image* asImage() const { return 0; } + + void setBufferObject(BufferObject* bufferObject); + BufferObject* getBufferObject() { return _bufferObject.get(); } + const BufferObject* getBufferObject() const { return _bufferObject.get(); } + + void setBufferIndex(unsigned int index) { _bufferIndex = index; } + unsigned int getBufferIndex() const { return _bufferIndex; } + + GLBufferObject* getGLBufferObject(unsigned int contextID) const { return _bufferObject.valid() ? _bufferObject->getGLBufferObject(contextID) : 0; } + GLBufferObject* getOrCreateGLBufferObject(unsigned int contextID) const { return _bufferObject.valid() ? _bufferObject->getOrCreateGLBufferObject(contextID) : 0; } + + struct ModifiedCallback : public virtual osg::Object + { + ModifiedCallback() {} + + ModifiedCallback(const ModifiedCallback&,const CopyOp&) {} + + META_Object(osg,ModifiedCallback); + + virtual void modified(BufferData* /*bufferData*/) const {} + }; + + void setModifiedCallback(ModifiedCallback* md) { _modifiedCallback = md; } + ModifiedCallback* getModifiedCallback() { return _modifiedCallback.get(); } + const ModifiedCallback* getModifiedCallback() const { return _modifiedCallback.get(); } + + /** Dirty the primitive, which increments the modified count, to force buffer objects to update. + * If a ModifiedCallback is attached to this BufferData then the callback is called prior to the bufferObject's dirty is called. */ + inline void dirty() + { + ++_modifiedCount; + if (_modifiedCallback.valid()) _modifiedCallback->modified(this); + if (_bufferObject.valid()) _bufferObject->dirty(); + } + + /** Set the modified count value.*/ + inline void setModifiedCount(unsigned int value) { _modifiedCount=value; } + + /** Get modified count value.*/ + inline unsigned int getModifiedCount() const { return _modifiedCount; } + + /** Resize any per context GLObject buffers to specified size. */ + virtual void resizeGLObjectBuffers(unsigned int maxSize); + + /** If State is non-zero, this function releases OpenGL objects for + * the specified graphics context. Otherwise, releases OpenGL objects + * for all graphics contexts. */ + void releaseGLObjects(State* state=0) const; + + unsigned int getNumClients() const { return _numClients; } + + void addClient(osg::Object * /*client*/) { ++_numClients; } + + void removeClient(osg::Object * /*client*/) { --_numClients; } + +protected: + + virtual ~BufferData(); + + unsigned int _modifiedCount; + + unsigned int _bufferIndex; + osg::ref_ptr _bufferObject; + osg::ref_ptr _modifiedCallback; + + unsigned int _numClients; +}; + + +class Array; +class OSG_EXPORT VertexBufferObject : public BufferObject +{ + public: + + VertexBufferObject(); + + /** Copy constructor using CopyOp to manage deep vs shallow copy.*/ + VertexBufferObject(const VertexBufferObject& vbo,const CopyOp& copyop=CopyOp::SHALLOW_COPY); + + META_Object(osg,VertexBufferObject); + + unsigned int addArray(osg::Array* array); + void removeArray(osg::Array* array); + + void setArray(unsigned int i, Array* array); + Array* getArray(unsigned int i); + const Array* getArray(unsigned int i) const; + + protected: + virtual ~VertexBufferObject(); +}; + +class DrawElements; +class OSG_EXPORT ElementBufferObject : public BufferObject +{ + public: + + ElementBufferObject(); + + /** Copy constructor using CopyOp to manage deep vs shallow copy.*/ + ElementBufferObject(const ElementBufferObject& pbo,const CopyOp& copyop=CopyOp::SHALLOW_COPY); + + META_Object(osg,ElementBufferObject); + + unsigned int addDrawElements(osg::DrawElements* PrimitiveSet); + void removeDrawElements(osg::DrawElements* PrimitiveSet); + + void setDrawElements(unsigned int i, DrawElements* PrimitiveSet); + DrawElements* getDrawElements(unsigned int i); + const DrawElements* getDrawElements(unsigned int i) const; + + protected: + + virtual ~ElementBufferObject(); +}; + +class Image; +class OSG_EXPORT PixelBufferObject : public BufferObject +{ + public: + + PixelBufferObject(osg::Image* image=0); + + /** Copy constructor using CopyOp to manage deep vs shallow copy.*/ + PixelBufferObject(const PixelBufferObject& pbo,const CopyOp& copyop=CopyOp::SHALLOW_COPY); + + META_Object(osg,PixelBufferObject); + + void setImage(osg::Image* image); + + Image* getImage(); + const Image* getImage() const; + + bool isPBOSupported(unsigned int contextID) const { return _glBufferObjects[contextID]->isPBOSupported(); } + + protected: + + virtual ~PixelBufferObject(); +}; + +/** + * This object represent a general class of pixel buffer objects, + * which are capable of allocating buffer object (memory) + * on the GPU. The memory can then be used either for CPU-GPU + * pixel transfer or directly for GPU-GPU transfer, without CPU intervention. + **/ +class OSG_EXPORT PixelDataBufferObject : public BufferObject +{ + public: + PixelDataBufferObject(); + PixelDataBufferObject(const PixelDataBufferObject& pbo, const CopyOp& copyop=CopyOp::SHALLOW_COPY); + + META_Object(osg, PixelDataBufferObject); + + //! Set new size of the buffer object. This will reallocate the memory on the next compile + inline void setDataSize(unsigned int size) { _profile._size = size; dirty(); } + + //! Get data size of the used buffer + inline unsigned int getDataSize() const { return _profile._size; } + + //! Compile the buffer (reallocate the memory if buffer is dirty) + virtual void compileBuffer(State& state) const; + + //! Bind the buffer in read mode, which means that data can be downloaded from the buffer (note: GL_PIXEL_UNPACK_BUFFER_ARB) + virtual void bindBufferInReadMode(State& state); + + //! Bind the buffer in write mode, which means following OpenGL instructions will write data into the buffer (note: GL_PIXEL_PACK_BUFFER_ARB) + virtual void bindBufferInWriteMode(State& state); + + //! Unbind the buffer + virtual void unbindBuffer(unsigned int contextID) const; + + /** Resize any per context GLObject buffers to specified size. */ + virtual void resizeGLObjectBuffers(unsigned int maxSize); + + enum Mode + { + //! A normal mode of this data buffer + NONE = 0, + + //! Buffer is in read mode (@see bindBufferInReadMode) + READ = 1, + + //! Buffer is in write mode (@see bindBufferInWriteMode) + WRITE = 2 + }; + + Mode getMode(unsigned int contextID) const { return (Mode)_mode[contextID]; } + + protected: + + virtual ~PixelDataBufferObject(); + + typedef osg::buffered_value ModeList; + + mutable ModeList _mode; + +}; + +class OSG_EXPORT UniformBufferObject : public BufferObject +{ + public: + UniformBufferObject(); + UniformBufferObject(const UniformBufferObject& ubo, const CopyOp& copyop=CopyOp::SHALLOW_COPY); + META_Object(osg, UniformBufferObject); + protected: + virtual ~UniformBufferObject(); +}; + +class OSG_EXPORT AtomicCounterBufferObject : public BufferObject +{ + public: + AtomicCounterBufferObject(); + AtomicCounterBufferObject(const AtomicCounterBufferObject& ubo, const CopyOp& copyop=CopyOp::SHALLOW_COPY); + META_Object(osg, AtomicCounterBufferObject); + + protected: + virtual ~AtomicCounterBufferObject(); +}; + +inline void GLBufferObject::bindBuffer() +{ + _extensions->glBindBuffer(_profile._target,_glObjectID); + if (_set) _set->moveToBack(this); +} + +} + +#endif diff --git a/libs/include/android/osg/Camera b/libs/include/android/osg/Camera new file mode 100755 index 0000000..3a2219a --- /dev/null +++ b/libs/include/android/osg/Camera @@ -0,0 +1,698 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_CAMERA +#define OSG_CAMERA 1 + +#include +#include +#include +#include +#include +#include +#include +#include + +#include + + +#if defined(OSG_GLES1_AVAILABLE) || defined(OSG_GLES2_AVAILABLE) && !defined(OSG_GL3_AVAILABLE) + #define GL_FRONT_LEFT 0x0400 + #define GL_FRONT_RIGHT 0x0401 + #define GL_BACK_LEFT 0x0402 + #define GL_BACK_RIGHT 0x0403 +#endif + +namespace osg { + +// forward declare View to allow Camera to point back to the View that its within +class View; +class RenderInfo; + +/** Camera - is a subclass of Transform which represents encapsulates the settings of a Camera. +*/ +class OSG_EXPORT Camera : public Transform, public CullSettings +{ + public : + + + Camera(); + + /** Copy constructor using CopyOp to manage deep vs shallow copy.*/ + Camera(const Camera&,const CopyOp& copyop=CopyOp::SHALLOW_COPY); + + META_Node(osg, Camera); + + virtual Camera* asCamera() { return this; } + virtual const Camera* asCamera() const { return this; } + + /** Set the View that this Camera is part of. */ + void setView(View* view) { _view = view; } + + /** Get the View that this Camera is part of. */ + View* getView() { return _view; } + + /** Get the const View that this Camera is part of. */ + const View* getView() const { return _view; } + + + /** Set the Stats object used for collect various frame related + * timing and scene graph stats. */ + void setStats(osg::Stats* stats) { _stats = stats; } + + /** Get the Stats object.*/ + osg::Stats* getStats() { return _stats.get(); } + + /** Get the const Stats object.*/ + const osg::Stats* getStats() const { return _stats.get(); } + + + /** Set whether this camera allows events to be generated by the + * associated graphics window to be associated with this camera. */ + void setAllowEventFocus(bool focus) { _allowEventFocus = focus; } + + /** Get whether this camera allows events to be generated by the + * associated graphics window to be associated with this camera. */ + bool getAllowEventFocus() const { return _allowEventFocus; } + + + /** Set the DisplaySettings object associated with this view.*/ + void setDisplaySettings(osg::DisplaySettings* ds) { _displaySettings = ds; } + + /** Get the DisplaySettings object associated with this view.*/ + osg::DisplaySettings* getDisplaySettings() { return _displaySettings.get(); } + + /** Get the const DisplaySettings object associated with this view.*/ + const osg::DisplaySettings* getDisplaySettings() const { return _displaySettings.get(); } + + + /** Set the clear mask used in glClear(). + * Defaults to GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT. */ + inline void setClearMask(GLbitfield mask) { _clearMask = mask; applyMaskAction(CLEAR_MASK); } + + /** Get the clear mask.*/ + inline GLbitfield getClearMask() const { return _clearMask; } + + /** Set the clear color used in glClearColor(). + * glClearColor is only called if mask & GL_COLOR_BUFFER_BIT is true*/ + void setClearColor(const osg::Vec4& color) { _clearColor=color; applyMaskAction(CLEAR_COLOR); } + + /** Get the clear color.*/ + const osg::Vec4& getClearColor() const { return _clearColor; } + + /** Set the clear accum used in glClearAccum(). + * glClearAcumm is only called if mask & GL_ACCUM_BUFFER_BIT is true. */ + void setClearAccum(const osg::Vec4& color) { _clearAccum=color; } + + /** Get the clear accum value.*/ + const osg::Vec4& getClearAccum() const { return _clearAccum; } + + /** Set the clear depth used in glClearDepth(). Defaults to 1.0 + * glClearDepth is only called if mask & GL_DEPTH_BUFFER_BIT is true. */ + void setClearDepth(double depth) { _clearDepth=depth; } + + /** Get the clear depth value.*/ + double getClearDepth() const { return _clearDepth; } + + /** Set the clear stencil value used in glClearStencil(). Defaults to 0; + * glClearStencil is only called if mask & GL_STENCIL_BUFFER_BIT is true*/ + void setClearStencil(int stencil) { _clearStencil=stencil; } + + /** Get the clear stencil value.*/ + int getClearStencil() const { return _clearStencil; } + + + /** Set the color mask of the camera to use specified osg::ColorMask. */ + void setColorMask(osg::ColorMask* colorMask); + + + /** Set the color mask of the camera to specified values. */ + void setColorMask(bool red, bool green, bool blue, bool alpha); + + /** Get the const ColorMask. */ + const ColorMask* getColorMask() const { return _colorMask.get(); } + + /** Get the ColorMask. */ + ColorMask* getColorMask() { return _colorMask.get(); } + + + /** Set the viewport of the camera to use specified osg::Viewport. */ + void setViewport(osg::Viewport* viewport); + + /** Set the viewport of the camera to specified dimensions. */ + void setViewport(int x,int y,int width,int height); + + /** Get the const viewport. */ + const Viewport* getViewport() const { return _viewport.get(); } + + /** Get the viewport. */ + Viewport* getViewport() { return _viewport.get(); } + + + enum TransformOrder + { + PRE_MULTIPLY, + POST_MULTIPLY + }; + + /** Set the transformation order for world-to-local and local-to-world transformation.*/ + void setTransformOrder(TransformOrder order) { _transformOrder = order; } + + /** Get the transformation order.*/ + TransformOrder getTransformOrder() const { return _transformOrder; } + + enum ProjectionResizePolicy + { + FIXED, /**< Keep the projection matrix fixed, despite window resizes.*/ + HORIZONTAL, /**< Adjust the HORIZONTAL field of view on window resizes.*/ + VERTICAL /**< Adjust the VERTICAL field of view on window resizes.*/ + + }; + + /** Set the policy used to determine if and how the projection matrix should be adjusted on window resizes. */ + inline void setProjectionResizePolicy(ProjectionResizePolicy policy) { _projectionResizePolicy = policy; } + + /** Get the policy used to determine if and how the projection matrix should be adjusted on window resizes. */ + inline ProjectionResizePolicy getProjectionResizePolicy() const { return _projectionResizePolicy; } + + + /** Set the projection matrix. Can be thought of as setting the lens of a camera. */ + inline void setProjectionMatrix(const osg::Matrixf& matrix) { _projectionMatrix.set(matrix); } + + /** Set the projection matrix. Can be thought of as setting the lens of a camera. */ + inline void setProjectionMatrix(const osg::Matrixd& matrix) { _projectionMatrix.set(matrix); } + + /** Set to an orthographic projection. See OpenGL glOrtho for documentation further details.*/ + void setProjectionMatrixAsOrtho(double left, double right, + double bottom, double top, + double zNear, double zFar); + + /** Set to a 2D orthographic projection. See OpenGL glOrtho2D documentation for further details.*/ + void setProjectionMatrixAsOrtho2D(double left, double right, + double bottom, double top); + + /** Set to a perspective projection. See OpenGL glFrustum documentation for further details.*/ + void setProjectionMatrixAsFrustum(double left, double right, + double bottom, double top, + double zNear, double zFar); + + /** Create a symmetrical perspective projection, See OpenGL gluPerspective documentation for further details. + * Aspect ratio is defined as width/height.*/ + void setProjectionMatrixAsPerspective(double fovy,double aspectRatio, + double zNear, double zFar); + + /** Get the projection matrix.*/ + osg::Matrixd& getProjectionMatrix() { return _projectionMatrix; } + + /** Get the const projection matrix.*/ + const osg::Matrixd& getProjectionMatrix() const { return _projectionMatrix; } + + /** Get the orthographic settings of the orthographic projection matrix. + * Returns false if matrix is not an orthographic matrix, where parameter values are undefined.*/ + bool getProjectionMatrixAsOrtho(double& left, double& right, + double& bottom, double& top, + double& zNear, double& zFar) const; + + /** Get the frustum setting of a perspective projection matrix. + * Returns false if matrix is not a perspective matrix, where parameter values are undefined.*/ + bool getProjectionMatrixAsFrustum(double& left, double& right, + double& bottom, double& top, + double& zNear, double& zFar) const; + + /** Get the frustum setting of a symmetric perspective projection matrix. + * Returns false if matrix is not a perspective matrix, where parameter values are undefined. + * Note, if matrix is not a symmetric perspective matrix then the shear will be lost. + * Asymmetric matrices occur when stereo, power walls, caves and reality center display are used. + * In these configurations one should use the 'getProjectionMatrixAsFrustum' method instead.*/ + bool getProjectionMatrixAsPerspective(double& fovy,double& aspectRatio, + double& zNear, double& zFar) const; + + + + /** Set the view matrix. Can be thought of as setting the position of the world relative to the camera in camera coordinates. */ + inline void setViewMatrix(const osg::Matrixf& matrix) { _viewMatrix.set(matrix); dirtyBound();} + + /** Set the view matrix. Can be thought of as setting the position of the world relative to the camera in camera coordinates. */ + inline void setViewMatrix(const osg::Matrixd& matrix) { _viewMatrix.set(matrix); dirtyBound();} + + /** Get the view matrix. */ + osg::Matrixd& getViewMatrix() { return _viewMatrix; } + + /** Get the const view matrix. */ + const osg::Matrixd& getViewMatrix() const { return _viewMatrix; } + + /** Set to the position and orientation of view matrix, using the same convention as gluLookAt. */ + void setViewMatrixAsLookAt(const osg::Vec3d& eye,const osg::Vec3d& center,const osg::Vec3d& up); + + /** Get to the position and orientation of a modelview matrix, using the same convention as gluLookAt. */ + void getViewMatrixAsLookAt(osg::Vec3d& eye,osg::Vec3d& center,osg::Vec3d& up,double lookDistance=1.0) const; + + /** Get to the position and orientation of a modelview matrix, using the same convention as gluLookAt. */ + void getViewMatrixAsLookAt(osg::Vec3f& eye,osg::Vec3f& center,osg::Vec3f& up,float lookDistance=1.0f) const; + + /** Get the inverse view matrix.*/ + Matrixd getInverseViewMatrix() const; + + + enum RenderOrder + { + PRE_RENDER, + NESTED_RENDER, + POST_RENDER + }; + + /** Set the rendering order of this camera's subgraph relative to any camera that this subgraph is nested within. + * For rendering to a texture, one typically uses PRE_RENDER. + * For Head Up Displays, one would typically use POST_RENDER.*/ + void setRenderOrder(RenderOrder order, int orderNum = 0) { _renderOrder = order; _renderOrderNum = orderNum; } + + /** Get the rendering order of this camera's subgraph relative to any camera that this subgraph is nested within.*/ + RenderOrder getRenderOrder() const { return _renderOrder; } + + /** Get the rendering order number of this camera relative to any sibling cameras in this subgraph.*/ + int getRenderOrderNum() const { return _renderOrderNum; } + + /** Return true if this Camera is set up as a render to texture camera, i.e. it has textures assigned to it.*/ + bool isRenderToTextureCamera() const; + + enum RenderTargetImplementation + { + FRAME_BUFFER_OBJECT, + PIXEL_BUFFER_RTT, + PIXEL_BUFFER, + FRAME_BUFFER, + SEPERATE_WINDOW + }; + + /** Set the render target.*/ + void setRenderTargetImplementation(RenderTargetImplementation impl); + + /** Set the render target and fall-back that's used if the former isn't available.*/ + void setRenderTargetImplementation(RenderTargetImplementation impl, RenderTargetImplementation fallback); + + /** Get the render target.*/ + RenderTargetImplementation getRenderTargetImplementation() const { return _renderTargetImplementation; } + + /** Get the render target fallback.*/ + RenderTargetImplementation getRenderTargetFallback() const { return _renderTargetFallback; } + + + /** Set the draw buffer used at the start of each frame draw. + * Note, a buffer value of GL_NONE is used to sepecify that the rendering back-end should choose the most appropriate buffer.*/ + void setDrawBuffer(GLenum buffer) { _drawBuffer = buffer; applyMaskAction( DRAW_BUFFER ); } + + /** Get the draw buffer used at the start of each frame draw. */ + GLenum getDrawBuffer() const { return _drawBuffer; } + + /** Set the read buffer for any required copy operations to use. + * Note, a buffer value of GL_NONE is used to sepecify that the rendering back-end should choose the most appropriate buffer.*/ + void setReadBuffer(GLenum buffer) { _readBuffer = buffer; applyMaskAction( READ_BUFFER ); } + + /** Get the read buffer for any required copy operations to use. */ + GLenum getReadBuffer() const { return _readBuffer; } + + enum BufferComponent + { + DEPTH_BUFFER, + STENCIL_BUFFER, + PACKED_DEPTH_STENCIL_BUFFER, + COLOR_BUFFER, + COLOR_BUFFER0, + COLOR_BUFFER1 = COLOR_BUFFER0+1, + COLOR_BUFFER2 = COLOR_BUFFER0+2, + COLOR_BUFFER3 = COLOR_BUFFER0+3, + COLOR_BUFFER4 = COLOR_BUFFER0+4, + COLOR_BUFFER5 = COLOR_BUFFER0+5, + COLOR_BUFFER6 = COLOR_BUFFER0+6, + COLOR_BUFFER7 = COLOR_BUFFER0+7, + COLOR_BUFFER8 = COLOR_BUFFER0+8, + COLOR_BUFFER9 = COLOR_BUFFER0+9, + COLOR_BUFFER10 = COLOR_BUFFER0+10, + COLOR_BUFFER11 = COLOR_BUFFER0+11, + COLOR_BUFFER12 = COLOR_BUFFER0+12, + COLOR_BUFFER13 = COLOR_BUFFER0+13, + COLOR_BUFFER14 = COLOR_BUFFER0+14, + COLOR_BUFFER15 = COLOR_BUFFER0+15 + }; + + static const unsigned int FACE_CONTROLLED_BY_GEOMETRY_SHADER; + + /** Attach a buffer with specified OpenGL internal format.*/ + void attach(BufferComponent buffer, GLenum internalFormat); + + /** Attach a Texture to specified buffer component. + * The level parameter controls the mip map level of the texture that is attached. + * The face parameter controls the face of texture cube map or z level of 3d texture. + * The mipMapGeneration flag controls whether mipmap generation should be done for texture.*/ + void attach(BufferComponent buffer, osg::Texture* texture, unsigned int level = 0, unsigned int face=0, bool mipMapGeneration=false, + unsigned int multisampleSamples = 0, + unsigned int multisampleColorSamples = 0); + + /** Attach a Image to specified buffer component.*/ + void attach(BufferComponent buffer, osg::Image* image, + unsigned int multisampleSamples = 0, + unsigned int multisampleColorSamples = 0); + + /** Detach specified buffer component.*/ + void detach(BufferComponent buffer); + + struct Attachment + { + Attachment(): + _internalFormat(GL_NONE), + _level(0), + _face(0), + _mipMapGeneration(false), + _multisampleSamples(0), + _multisampleColorSamples(0) {} + + int width() const + { + if (_texture.valid()) return _texture->getTextureWidth(); + if (_image.valid()) return _image->s(); + return 0; + }; + + int height() const + { + if (_texture.valid()) return _texture->getTextureHeight(); + if (_image.valid()) return _image->t(); + return 0; + }; + + int depth() const + { + if (_texture.valid()) return _texture->getTextureDepth(); + if (_image.valid()) return _image->r(); + return 0; + }; + + GLenum _internalFormat; + ref_ptr _image; + ref_ptr _texture; + unsigned int _level; + unsigned int _face; + bool _mipMapGeneration; + unsigned int _multisampleSamples; + unsigned int _multisampleColorSamples; + }; + + typedef std::map< BufferComponent, Attachment> BufferAttachmentMap; + + /** Get the BufferAttachmentMap, used to configure frame buffer objects, pbuffers and texture reads.*/ + BufferAttachmentMap& getBufferAttachmentMap() { return _bufferAttachmentMap; } + + /** Get the const BufferAttachmentMap, used to configure frame buffer objects, pbuffers and texture reads.*/ + const BufferAttachmentMap& getBufferAttachmentMap() const { return _bufferAttachmentMap; } + + + /** Explicit control over implicit allocation of buffers when using FBO. + Implicit buffers are automatically substituted when user have not attached such buffer. + + Camera may set up two FBOs: primary Render FBO and secondary Resolve FBO for multisample usage. + So in practive we have two masks defined for the Camera: + implicitBufferAttachmentRenderMask + implicitBufferAttachmentResolveMask + They can be set together by setImplicitBufferAttachmentMask method, or separately + by setImplicitBufferAttachmentRenderMask and setImplicitBufferAttachmentResolveMask. + + Camera defaults are USE_DISPLAY_SETTINGS_MASK which means that by default + Camera chooses to substitue buffer attachments as defined by DisplaySettings. + + Usually DisplaySettings implicit buffer attachment selection defaults to: DEPTH and COLOR + for both primary (Render) FBO and seconday Multisample (Resolve) FBO + ie: IMPLICT_DEPTH_BUFFER_ATTACHMENT | IMPLICIT_COLOR_BUFFER_ATTACHMENT + + If these masks are not changed and user did not attach depth buffer and/or color buffer + to Camera, then OSG implicitly substitues these buffers. + By default it does not implicitly allocate a stencil buffer. + Use implicti buffer attachment masks to override default behavior: + to turn off DEPTH or COLOR buffer substitution or to enforce STENCIL buffer substitution. + + Note that both values are ignored if not using FBO. + Note that the second mask value is ignored if not using MSFBO. + */ + enum ImplicitBufferAttachment + { + IMPLICIT_DEPTH_BUFFER_ATTACHMENT = DisplaySettings::IMPLICIT_DEPTH_BUFFER_ATTACHMENT, + IMPLICIT_STENCIL_BUFFER_ATTACHMENT = DisplaySettings::IMPLICIT_STENCIL_BUFFER_ATTACHMENT, + IMPLICIT_COLOR_BUFFER_ATTACHMENT = DisplaySettings::IMPLICIT_COLOR_BUFFER_ATTACHMENT, + USE_DISPLAY_SETTINGS_MASK = (~0) + }; + + typedef int ImplicitBufferAttachmentMask; + + void setImplicitBufferAttachmentMask(ImplicitBufferAttachmentMask renderMask = DisplaySettings::DEFAULT_IMPLICIT_BUFFER_ATTACHMENT, ImplicitBufferAttachmentMask resolveMask = DisplaySettings::DEFAULT_IMPLICIT_BUFFER_ATTACHMENT) + { + _implicitBufferAttachmentRenderMask = renderMask; + _implicitBufferAttachmentResolveMask = resolveMask; + } + + void setImplicitBufferAttachmentRenderMask(ImplicitBufferAttachmentMask implicitBufferAttachmentRenderMask) + { + _implicitBufferAttachmentRenderMask = implicitBufferAttachmentRenderMask; + } + + void setImplicitBufferAttachmentResolveMask(ImplicitBufferAttachmentMask implicitBufferAttachmentResolveMask) + { + _implicitBufferAttachmentResolveMask = implicitBufferAttachmentResolveMask; + } + + /** + Get mask selecting implict buffer attachments for Camera primary FBO + if effectiveMask parameter is set, method follows USE_DISPLAY_SETTINGS_MASK dependence and returns effective mask + if effectiveMask parameter is reset, method returns nominal mask set by the Camera + */ + ImplicitBufferAttachmentMask getImplicitBufferAttachmentRenderMask(bool effectiveMask = false) const + { + if( effectiveMask && _implicitBufferAttachmentRenderMask == USE_DISPLAY_SETTINGS_MASK ) + { + const DisplaySettings * ds = _displaySettings.valid() ? _displaySettings.get() : DisplaySettings::instance().get(); + return ds->getImplicitBufferAttachmentRenderMask(); + } + else + { + return _implicitBufferAttachmentRenderMask; + } + } + + /** + Get mask selecting implict buffer attachments for Camera secondary MULTISAMPLE FBO + if effectiveMask parameter is set, method follows USE_DISPLAY_SETTINGS_MASK dependence and returns effective mask + if effectiveMask parameter is reset, method returns nominal mask set by the Camera + */ + ImplicitBufferAttachmentMask getImplicitBufferAttachmentResolveMask(bool effectiveMask = false) const + { + if( effectiveMask && _implicitBufferAttachmentResolveMask == USE_DISPLAY_SETTINGS_MASK ) + { + const DisplaySettings * ds = _displaySettings.valid() ? _displaySettings.get() : DisplaySettings::instance().get(); + return ds->getImplicitBufferAttachmentResolveMask(); + } + else + { + return _implicitBufferAttachmentResolveMask; + } + } + + /** Create a operation thread for this camera.*/ + void createCameraThread(); + + /** Assign a operation thread to the camera.*/ + void setCameraThread(OperationThread* gt); + + /** Get the operation thread assigned to this camera.*/ + OperationThread* getCameraThread() { return _cameraThread.get(); } + + /** Get the const operation thread assigned to this camera.*/ + const OperationThread* getCameraThread() const { return _cameraThread.get(); } + + + + /** Set the GraphicsContext that provides the mechansim for managing the OpenGL graphics context associated with this camera.*/ + void setGraphicsContext(GraphicsContext* context); + + /** Get the GraphicsContext.*/ + GraphicsContext* getGraphicsContext() { return _graphicsContext.get(); } + + /** Get the const GraphicsContext.*/ + const GraphicsContext* getGraphicsContext() const { return _graphicsContext.get(); } + + + /** Set the Rendering object that is used to implement rendering of the subgraph.*/ + void setRenderer(osg::GraphicsOperation* rc) { _renderer = rc; } + + /** Get the Rendering object that is used to implement rendering of the subgraph.*/ + osg::GraphicsOperation* getRenderer() { return _renderer.get(); } + + /** Get the const Rendering object that is used to implement rendering of the subgraph.*/ + const osg::GraphicsOperation* getRenderer() const { return _renderer.get(); } + + + /** Set the Rendering cache that is used for cached objects associated with rendering of subgraphs.*/ + void setRenderingCache(osg::Object* rc) { _renderingCache = rc; } + + /** Get the Rendering cache that is used for cached objects associated with rendering of subgraphs.*/ + osg::Object* getRenderingCache() { return _renderingCache.get(); } + + /** Get the const Rendering cache that is used for cached objects associated with rendering of subgraphs.*/ + const osg::Object* getRenderingCache() const { return _renderingCache.get(); } + + + /** Draw callback for custom operations.*/ + struct OSG_EXPORT DrawCallback : virtual public Object + { + DrawCallback() {} + + DrawCallback(const DrawCallback&,const CopyOp&) {} + + META_Object(osg, DrawCallback); + + /** Functor method called by rendering thread. Users will typically override this method to carry tasks such as screen capture.*/ + virtual void operator () (osg::RenderInfo& renderInfo) const; + + /** Functor method, provided for backwards compatibility, called by operator() (osg::RenderInfo& renderInfo) method.*/ + virtual void operator () (const osg::Camera& /*camera*/) const {} + }; + + /** Set the initial draw callback for custom operations to be done before the drawing of the camera's subgraph and pre render stages.*/ + void setInitialDrawCallback(DrawCallback* cb) { _initialDrawCallback = cb; } + + /** Get the initial draw callback.*/ + DrawCallback* getInitialDrawCallback() { return _initialDrawCallback.get(); } + + /** Get the const initial draw callback.*/ + const DrawCallback* getInitialDrawCallback() const { return _initialDrawCallback.get(); } + + + /** Set the pre draw callback for custom operations to be done before the drawing of the camera's subgraph but after any pre render stages have been completed.*/ + void setPreDrawCallback(DrawCallback* cb) { _preDrawCallback = cb; } + + /** Get the pre draw callback.*/ + DrawCallback* getPreDrawCallback() { return _preDrawCallback.get(); } + + /** Get the const pre draw callback.*/ + const DrawCallback* getPreDrawCallback() const { return _preDrawCallback.get(); } + + + /** Set the post draw callback for custom operations to be done after the drawing of the camera's subgraph but before the any post render stages have been completed.*/ + void setPostDrawCallback(DrawCallback* cb) { _postDrawCallback = cb; } + + /** Get the post draw callback.*/ + DrawCallback* getPostDrawCallback() { return _postDrawCallback.get(); } + + /** Get the const post draw callback.*/ + const DrawCallback* getPostDrawCallback() const { return _postDrawCallback.get(); } + + + /** Set the final draw callback for custom operations to be done after the drawing of the camera's subgraph and all of the post render stages has been completed.*/ + void setFinalDrawCallback(DrawCallback* cb) { _finalDrawCallback = cb; } + + /** Get the final draw callback.*/ + DrawCallback* getFinalDrawCallback() { return _finalDrawCallback.get(); } + + /** Get the const final draw callback.*/ + const DrawCallback* getFinalDrawCallback() const { return _finalDrawCallback.get(); } + + + OpenThreads::Mutex* getDataChangeMutex() const { return &_dataChangeMutex; } + + /** Resize any per context GLObject buffers to specified size. */ + virtual void resizeGLObjectBuffers(unsigned int maxSize); + + /** If State is non-zero, this function releases any associated OpenGL objects for + * the specified graphics context. Otherwise, releases OpenGL objexts + * for all graphics contexts. */ + virtual void releaseGLObjects(osg::State* = 0) const; + + public: + + /** Transform method that must be defined to provide generic interface for scene graph traversals.*/ + virtual bool computeLocalToWorldMatrix(Matrix& matrix,NodeVisitor*) const; + + /** Transform method that must be defined to provide generic interface for scene graph traversals.*/ + virtual bool computeWorldToLocalMatrix(Matrix& matrix,NodeVisitor*) const; + + /** Inherit the local cull settings variable from specified CullSettings object, according to the inheritance mask.*/ + virtual void inheritCullSettings(const CullSettings& settings, unsigned int inheritanceMask); + + protected : + + virtual ~Camera(); + + mutable OpenThreads::Mutex _dataChangeMutex; + + + View* _view; + + osg::ref_ptr _stats; + + bool _allowEventFocus; + + osg::ref_ptr _displaySettings; + + GLbitfield _clearMask; + osg::Vec4 _clearColor; + osg::Vec4 _clearAccum; + double _clearDepth; + int _clearStencil; + + ref_ptr _colorMask; + ref_ptr _viewport; + + TransformOrder _transformOrder; + ProjectionResizePolicy _projectionResizePolicy; + + Matrixd _projectionMatrix; + Matrixd _viewMatrix; + + RenderOrder _renderOrder; + int _renderOrderNum; + + GLenum _drawBuffer; + GLenum _readBuffer; + + RenderTargetImplementation _renderTargetImplementation; + RenderTargetImplementation _renderTargetFallback; + BufferAttachmentMap _bufferAttachmentMap; + ImplicitBufferAttachmentMask _implicitBufferAttachmentRenderMask; + ImplicitBufferAttachmentMask _implicitBufferAttachmentResolveMask; + + ref_ptr _cameraThread; + + ref_ptr _graphicsContext; + + ref_ptr _renderer; + ref_ptr _renderingCache; + + ref_ptr _initialDrawCallback; + ref_ptr _preDrawCallback; + ref_ptr _postDrawCallback; + ref_ptr _finalDrawCallback; +}; + + +/** Functor to assist with ordering camers in the order they should be rendered in.*/ +struct CameraRenderOrderSortOp +{ + inline bool operator() (const Camera* lhs,const Camera* rhs) const + { + if (lhs->getRenderOrder()getRenderOrder()) return true; + if (rhs->getRenderOrder()getRenderOrder()) return false; + return lhs->getRenderOrderNum()getRenderOrderNum(); + } +}; + + +} + +#endif diff --git a/libs/include/android/osg/CameraNode b/libs/include/android/osg/CameraNode new file mode 100755 index 0000000..7bd132d --- /dev/null +++ b/libs/include/android/osg/CameraNode @@ -0,0 +1,27 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_CAMERANODE +#define OSG_CAMERANODE 1 + +#include + +namespace osg { + +#ifdef USE_DEPRECATED_API + typedef osg::Camera CameraNode; +#endif + +} + +#endif diff --git a/libs/include/android/osg/CameraView b/libs/include/android/osg/CameraView new file mode 100755 index 0000000..c97294b --- /dev/null +++ b/libs/include/android/osg/CameraView @@ -0,0 +1,105 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_CAMERAVIEW +#define OSG_CAMERAVIEW 1 + +#include +#include +#include +#include +#include + +namespace osg { + +/** CameraView - is a Transform that is used to specify camera views from within the scene graph. + * The application must attach a camera to a CameraView via the NodePath from the top of the scene graph + * to the CameraView node itself, and accumulate the view matrix from this NodePath. +*/ +class OSG_EXPORT CameraView : public Transform +{ + public : + CameraView(); + + CameraView(const CameraView& pat,const CopyOp& copyop=CopyOp::SHALLOW_COPY): + Transform(pat,copyop), + _position(pat._position), + _attitude(pat._attitude), + _fieldOfView(pat._fieldOfView), + _fieldOfViewMode(pat._fieldOfViewMode), + _focalLength(pat._focalLength) {} + + + META_Node(osg, CameraView); + + /** Set the position of the camera view.*/ + inline void setPosition(const Vec3d& pos) { _position = pos; dirtyBound(); } + + /** Get the position of the camera view.*/ + inline const Vec3d& getPosition() const { return _position; } + + /** Set the attitude of the camera view.*/ + inline void setAttitude(const Quat& quat) { _attitude = quat; dirtyBound(); } + + /** Get the attitude of the camera view.*/ + inline const Quat& getAttitude() const { return _attitude; } + + /** Set the field of view. + * The camera's field of view can be constrained to either the horizontal or vertical axis of the camera, or unconstrained + * in which case the camera/application are left to choose an appropriate field of view. + * The default value if 60 degrees. */ + inline void setFieldOfView(double fieldOfView) { _fieldOfView = fieldOfView; } + + /** Get the field of view.*/ + inline double getFieldOfView() const { return _fieldOfView; } + + enum FieldOfViewMode + { + UNCONSTRAINED, + HORIZONTAL, + VERTICAL + }; + + /** Set the field of view mode - controlling how the field of view of the camera is constrained by the CameraView settings.*/ + inline void setFieldOfViewMode(FieldOfViewMode mode) { _fieldOfViewMode = mode; } + + /** Get the field of view mode.*/ + inline FieldOfViewMode getFieldOfViewMode() const { return _fieldOfViewMode; } + + /** Set the focal length of the camera. + * A focal length of 0.0 indicates that the camera/application should determine the focal length. + * The default value is 0.0. */ + inline void setFocalLength(double focalLength) { _focalLength = focalLength; } + + /** Get the focal length of the camera.*/ + inline double getFocalLength() const { return _focalLength; } + + + virtual bool computeLocalToWorldMatrix(Matrix& matrix,NodeVisitor* nv) const; + virtual bool computeWorldToLocalMatrix(Matrix& matrix,NodeVisitor* nv) const; + + + protected : + + virtual ~CameraView() {} + + Vec3d _position; + Quat _attitude; + double _fieldOfView; + FieldOfViewMode _fieldOfViewMode; + double _focalLength; +}; + +} + +#endif diff --git a/libs/include/android/osg/ClampColor b/libs/include/android/osg/ClampColor new file mode 100755 index 0000000..e1882eb --- /dev/null +++ b/libs/include/android/osg/ClampColor @@ -0,0 +1,139 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_CLAMPCOLOR +#define OSG_CLAMPCOLOR 1 + +#include + +#ifndef GL_ARB_color_buffer_float +#define GL_RGBA_FLOAT_MODE_ARB 0x8820 +#define GL_CLAMP_VERTEX_COLOR_ARB 0x891A +#define GL_CLAMP_FRAGMENT_COLOR_ARB 0x891B +#define GL_CLAMP_READ_COLOR_ARB 0x891C +#define GL_FIXED_ONLY_ARB 0x891D +#endif + +#ifndef GL_FIXED_ONLY +#define GL_FIXED_ONLY GL_FIXED_ONLY_ARB +#define GL_CLAMP_VERTEX_COLOR GL_CLAMP_VERTEX_COLOR_ARB +#define GL_CLAMP_READ_COLOR GL_CLAMP_READ_COLOR_ARB +#define GL_CLAMP_FRAGMENT_COLOR GL_CLAMP_FRAGMENT_COLOR_ARB +#endif + +#if defined(OSG_GL3_AVAILABLE) + #define GL_CLAMP_VERTEX_COLOR 0x891A + #define GL_CLAMP_FRAGMENT_COLOR 0x891B +#endif + +namespace osg { + +/** Encapsulates OpenGL ClampColor state. */ +class OSG_EXPORT ClampColor : public StateAttribute +{ + public : + + ClampColor(); + + ClampColor(GLenum vertexMode, GLenum fragmentMode, GLenum readMode); + + /** Copy constructor using CopyOp to manage deep vs shallow copy. */ + ClampColor(const ClampColor& rhs,const CopyOp& copyop=CopyOp::SHALLOW_COPY): + StateAttribute(rhs,copyop), + _clampVertexColor(rhs._clampVertexColor), + _clampFragmentColor(rhs._clampFragmentColor), + _clampReadColor(rhs._clampReadColor) {} + + META_StateAttribute(osg, ClampColor,CLAMPCOLOR); + + /** Return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs. */ + virtual int compare(const StateAttribute& sa) const + { + // Check for equal types, then create the rhs variable + // used by the COMPARE_StateAttribute_Parameter macros below. + COMPARE_StateAttribute_Types(ClampColor,sa) + + // Compare each parameter in turn against the rhs. + COMPARE_StateAttribute_Parameter(_clampVertexColor) + COMPARE_StateAttribute_Parameter(_clampFragmentColor) + COMPARE_StateAttribute_Parameter(_clampReadColor) + + return 0; // Passed all the above comparison macros, so must be equal. + } + + void setClampVertexColor(GLenum mode) { _clampVertexColor = mode; } + GLenum getClampVertexColor() const { return _clampVertexColor; } + + void setClampFragmentColor(GLenum mode) { _clampFragmentColor = mode; } + GLenum getClampFragmentColor() const { return _clampFragmentColor; } + + void setClampReadColor(GLenum mode) { _clampReadColor = mode; } + GLenum getClampReadColor() const { return _clampReadColor; } + + + virtual void apply(State& state) const; + /** Encapsulates queries of extension availability, obtains extension + * function pointers, and provides convenience wrappers for + * calling extension functions. */ + class OSG_EXPORT Extensions : public osg::Referenced + { + public: + Extensions(unsigned int contextID); + + Extensions(const Extensions& rhs); + + void lowestCommonDenominator(const Extensions& rhs); + + void setupGLExtensions(unsigned int contextID); + + void setClampColorSupported(bool flag) { _isClampColorSupported=flag; } + bool isClampColorSupported() const { return _isClampColorSupported; } + + void glClampColor(GLenum target, GLenum mode) const; + + protected: + + ~Extensions() {} + + typedef void (GL_APIENTRY * GLClampColorProc) (GLenum target, GLenum mode); + bool _isClampColorSupported; + GLClampColorProc _glClampColor; + + }; + + /** Returns the Extensions object for the given context. + * If createIfNotInitalized is true and the Extensions object doesn't + * exist, getExtensions() creates it on the given context. + * Returns NULL if createIfNotInitalized is false and the Extensions + * object doesn't exist. */ + static Extensions* getExtensions(unsigned int contextID,bool createIfNotInitalized); + + /** setExtensions() allows users to override the extensions across graphics contexts. + * Typically used when you have different extensions supported across graphics pipes, + * but need to ensure that they all use the same low common denominator extensions. */ + static void setExtensions(unsigned int contextID,Extensions* extensions); + + + protected : + + virtual ~ClampColor(); + + GLenum _clampVertexColor; + GLenum _clampFragmentColor; + GLenum _clampReadColor; + +}; + +} + +#endif diff --git a/libs/include/android/osg/ClearNode b/libs/include/android/osg/ClearNode new file mode 100755 index 0000000..6da8188 --- /dev/null +++ b/libs/include/android/osg/ClearNode @@ -0,0 +1,75 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_CLEARNODE +#define OSG_CLEARNODE 1 + +#include +#include + +namespace osg { + +/** A Group node for clearing the color and depth buffers. Use setClearColor + * to change the clear color, and setRequiresClear to disable/enable the call + * clearing. You might want to disable clearing if you perform your clear by + * drawing fullscreen geometry. If you do this, add child nodes to perform + * such drawing. The default StateSet associated with this node places + * children in render bin -1 to ensure that children are rendered prior to + * the rest of the scene graph. +*/ +class OSG_EXPORT ClearNode : public Group +{ + public : + + ClearNode(); + + ClearNode(const ClearNode& cs, const CopyOp& copyop=CopyOp::SHALLOW_COPY): + Group(cs,copyop), + _requiresClear(cs._requiresClear), + _clearColor(cs._clearColor), + _clearMask(cs._clearMask) {} + + + META_Node(osg, ClearNode); + + /** Enable/disable clearing via glClear. */ + inline void setRequiresClear(bool requiresClear) { _requiresClear = requiresClear; } + + /** Gets whether clearing is enabled or disabled. */ + inline bool getRequiresClear() const { return _requiresClear; } + + /** Sets the clear color. */ + inline void setClearColor(const Vec4& color) { _clearColor = color; } + + /** Returns the clear color. */ + inline const Vec4& getClearColor() const { return _clearColor; } + + /** Set the clear mask used in glClear(..). + * Defaults to GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT. */ + inline void setClearMask(GLbitfield mask) { _clearMask = mask; } + + /** Get the clear mask.*/ + inline GLbitfield getClearMask() const { return _clearMask; } + + protected : + + virtual ~ClearNode() {} + + bool _requiresClear; + Vec4 _clearColor; + GLbitfield _clearMask; +}; + +} + +#endif diff --git a/libs/include/android/osg/ClipNode b/libs/include/android/osg/ClipNode new file mode 100755 index 0000000..a300e54 --- /dev/null +++ b/libs/include/android/osg/ClipNode @@ -0,0 +1,113 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_CLIPNODE +#define OSG_CLIPNODE 1 + +#include +#include + +namespace osg { + +/** Node for defining the position of ClipPlanes in the scene.*/ +class OSG_EXPORT ClipNode : public Group +{ + + public: + + typedef std::vector > ClipPlaneList; + + + ClipNode(); + + ClipNode(const ClipNode& es, const CopyOp& copyop=CopyOp::SHALLOW_COPY); + + META_Node(osg, ClipNode); + + enum ReferenceFrame + { + RELATIVE_RF, + ABSOLUTE_RF + }; + + /** Set the ClipNode's ReferenceFrame, either to be relative to its + * parent reference frame, or relative to an absolute coordinate + * frame. RELATIVE_RF is the default. + * Note: setting the ReferenceFrame to be ABSOLUTE_RF will + * also set the CullingActive flag to false on the ClipNode (and + * consequently all of its parents), thereby disabling culling of it and + * all its parents. This is necessary to prevent inappropriate + * culling, but may impact cull times if the absolute ClipNode is + * deep in the scene graph. It is therefore recommended to only use + * absolute ClipNode at the top of the scene. + */ + void setReferenceFrame(ReferenceFrame rf); + + ReferenceFrame getReferenceFrame() const { return _referenceFrame; } + + + /** Creates six clip planes corresponding to the given BoundingBox. */ + void createClipBox(const BoundingBox& bb,unsigned int clipPlaneNumberBase=0); + + /** Adds the clipplane. Returns true on success, and false if the plane + * has already been added, or if clipplane is NULL. */ + bool addClipPlane(ClipPlane* clipplane); + + /** Removes the clipplane. Returns true on success, false if clipplane + * isn't in this ClipNode.*/ + bool removeClipPlane(ClipPlane* clipplane); + + /** Remove the ClipPlane with the given index. Returns true on success, + * false if pos is not a valid plane index. */ + bool removeClipPlane(unsigned int pos); + + /** Returns the number of ClipPlanes. */ + inline unsigned int getNumClipPlanes() const { return _planes.size(); } + + + /** Get ClipPlane at the given index position. */ + inline ClipPlane* getClipPlane(unsigned int pos) { return _planes[pos].get(); } + + /** Get const ClipPlane at the given index position. */ + inline const ClipPlane* getClipPlane(unsigned int pos) const { return _planes[pos].get(); } + + /** Set the ClipPlaneList. */ + inline void setClipPlaneList(const ClipPlaneList& cpl) { _planes=cpl; } + + /** Get the ClipPlaneList. */ + inline ClipPlaneList& getClipPlaneList() { return _planes; } + + /** Get the const ClipPlaneList. */ + inline const ClipPlaneList& getClipPlaneList() const { return _planes; } + + /** Set the GLModes for all ClipPlanes, on the StateSet. */ + void setStateSetModes(StateSet&,StateAttribute::GLModeValue) const; + + /** Set up the local StateSet. */ + void setLocalStateSetModes(StateAttribute::GLModeValue=StateAttribute::ON); + + virtual BoundingSphere computeBound() const; + + protected: + + virtual ~ClipNode(); + + StateAttribute::GLModeValue _value; + ClipPlaneList _planes; + + ReferenceFrame _referenceFrame; +}; + +} + +#endif diff --git a/libs/include/android/osg/ClipPlane b/libs/include/android/osg/ClipPlane new file mode 100755 index 0000000..52f2a78 --- /dev/null +++ b/libs/include/android/osg/ClipPlane @@ -0,0 +1,127 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_CLIPPLANE +#define OSG_CLIPPLANE 1 + +#include +#include +#include + +#ifndef GL_CLIP_PLANE0 + #define GL_CLIP_PLANE0 0x3000 + #define GL_CLIP_PLANE1 0x3001 + #define GL_CLIP_PLANE2 0x3002 + #define GL_CLIP_PLANE3 0x3003 + #define GL_CLIP_PLANE4 0x3004 + #define GL_CLIP_PLANE5 0x3005 +#endif + +namespace osg { + +/** Encapsulates OpenGL glClipPlane(). +*/ +class OSG_EXPORT ClipPlane : public StateAttribute +{ + public : + + ClipPlane(); + inline ClipPlane(unsigned int no):_clipPlaneNum(no) {} + inline ClipPlane(unsigned int no,const Vec4d& plane):_clipPlaneNum(no) { setClipPlane(plane); } + inline ClipPlane(unsigned int no,const Plane& plane):_clipPlaneNum(no) { setClipPlane(plane); } + inline ClipPlane(unsigned int no,double a,double b,double c,double d): _clipPlaneNum(no) { setClipPlane(a,b,c,d); } + + /** Copy constructor using CopyOp to manage deep vs shallow copy. */ + ClipPlane(const ClipPlane& cp,const CopyOp& copyop=CopyOp::SHALLOW_COPY): + StateAttribute(cp,copyop) + { + _clipPlane[0]=cp._clipPlane[0]; + _clipPlane[1]=cp._clipPlane[1]; + _clipPlane[2]=cp._clipPlane[2]; + _clipPlane[3]=cp._clipPlane[3]; + _clipPlaneNum=cp._clipPlaneNum; + } + + virtual osg::Object* cloneType() const { return new ClipPlane( _clipPlaneNum ); } + virtual osg::Object* clone(const osg::CopyOp& copyop) const { return new ClipPlane(*this,copyop); } + virtual bool isSameKindAs(const osg::Object* obj) const { return dynamic_cast(obj)!=NULL; } + virtual const char* libraryName() const { return "osg"; } + virtual const char* className() const { return "ClipPlane"; } + virtual Type getType() const { return CLIPPLANE; } + + /** Return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs. */ + virtual int compare(const StateAttribute& sa) const + { + // Check for equal types, then create the rhs variable + // used by the COMPARE_StateAttribute_Parameter macros below. + COMPARE_StateAttribute_Types(ClipPlane,sa) + + // Compare each parameter in turn against the rhs. + COMPARE_StateAttribute_Parameter(_clipPlaneNum) + COMPARE_StateAttribute_Parameter(_clipPlane[0]) + COMPARE_StateAttribute_Parameter(_clipPlane[1]) + COMPARE_StateAttribute_Parameter(_clipPlane[2]) + COMPARE_StateAttribute_Parameter(_clipPlane[3]) + + return 0; // Passed all the above comparison macros, so must be equal. + } + + virtual unsigned int getMember() const { return _clipPlaneNum; } + + virtual bool getModeUsage(StateAttribute::ModeUsage& usage) const + { + usage.usesMode((GLMode)(GL_CLIP_PLANE0+_clipPlaneNum)); + return true; + } + + + /** Set the clip plane with the given Plane. */ + void setClipPlane(const Plane& plane) + { + _clipPlane.set(plane[0],plane[1],plane[2],plane[3]); + } + + /** Defines the plane as [ a b c d ]. */ + void setClipPlane(double a,double b,double c,double d) + { + _clipPlane.set(a,b,c,d); + } + + /** Set the clip plane with the given Vec4. */ + inline void setClipPlane(const Vec4d& plane) { _clipPlane = plane; } + + /** Gets the clip plane as a Vec4d. */ + const Vec4d& getClipPlane() const { return _clipPlane; } + + + /** Sets the clip plane number. */ + void setClipPlaneNum(unsigned int num); + + /** Gets the clip plane number. */ + unsigned int getClipPlaneNum() const; + + /** Applies the clip plane's state to the OpenGL state machine. */ + virtual void apply(State& state) const; + + protected : + + virtual ~ClipPlane(); + + Vec4d _clipPlane; + unsigned int _clipPlaneNum; + +}; + +} + +#endif diff --git a/libs/include/android/osg/ClusterCullingCallback b/libs/include/android/osg/ClusterCullingCallback new file mode 100755 index 0000000..339fcdc --- /dev/null +++ b/libs/include/android/osg/ClusterCullingCallback @@ -0,0 +1,75 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_CLUSTERCULLINGCALLBACK +#define OSG_CLUSTERCULLINGCALLBACK 1 + +#include +#include + +namespace osg { + +/** Implements cluster culling to cull back facing drawables. Derived from + * Drawable::CullCallback. +*/ +class OSG_EXPORT ClusterCullingCallback : public Drawable::CullCallback, public NodeCallback +{ + public: + + ClusterCullingCallback(); + ClusterCullingCallback(const ClusterCullingCallback& ccc,const CopyOp& copyop); + ClusterCullingCallback(const osg::Vec3& controlPoint, const osg::Vec3& normal, float deviation); + ClusterCullingCallback(const osg::Drawable* drawable); + + META_Object(osg,ClusterCullingCallback); + + /** Computes the control point, normal, and deviation from the + * given drawable contents. */ + void computeFrom(const osg::Drawable* drawable); + + /** Transform the ClusterCullingCallback's positional members to a new coordinate frame.*/ + void transform(const osg::Matrixd& matrix); + + void set(const osg::Vec3& controlPoint, const osg::Vec3& normal, float deviation, float radius); + + void setControlPoint(const osg::Vec3& controlPoint) { _controlPoint = controlPoint; } + const osg::Vec3& getControlPoint() const { return _controlPoint; } + + void setNormal(const osg::Vec3& normal) { _normal = normal; } + const osg::Vec3& getNormal() const { return _normal; } + + void setRadius(float radius) { _radius = radius; } + float getRadius() const { return _radius; } + + void setDeviation(float deviation) { _deviation = deviation; } + float getDeviation() const { return _deviation; } + + virtual bool cull(osg::NodeVisitor*, osg::Drawable*, osg::State*) const; + + /** Callback method called by the NodeVisitor when visiting a node.*/ + virtual void operator()(Node* node, NodeVisitor* nv); + + protected: + + virtual ~ClusterCullingCallback() {} + + osg::Vec3 _controlPoint; + osg::Vec3 _normal; + float _radius; + float _deviation; +}; + + +} + +#endif diff --git a/libs/include/android/osg/CollectOccludersVisitor b/libs/include/android/osg/CollectOccludersVisitor new file mode 100755 index 0000000..8ab9649 --- /dev/null +++ b/libs/include/android/osg/CollectOccludersVisitor @@ -0,0 +1,109 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_COLLECTOCCLUDERSVISITOR +#define OSG_COLLECTOCCLUDERSVISITOR 1 + +#include +#include + +#include + +namespace osg { + +class OSG_EXPORT CollectOccludersVisitor : public osg::NodeVisitor, public osg::CullStack +{ + public: + + + typedef std::set ShadowVolumeOccluderSet; + + CollectOccludersVisitor(); + virtual ~CollectOccludersVisitor(); + + META_NodeVisitor(osg, CollectOccludersVisitor) + + virtual CollectOccludersVisitor* cloneType() const { return new CollectOccludersVisitor(); } + + virtual void reset(); + + virtual float getDistanceToEyePoint(const Vec3& pos, bool withLODScale) const; + virtual float getDistanceToViewPoint(const Vec3& pos, bool withLODScale) const; + + virtual float getDistanceFromEyePoint(const Vec3& pos, bool withLODScale) const; + + virtual void apply(osg::Node&); + virtual void apply(osg::Transform& node); + virtual void apply(osg::Projection& node); + + virtual void apply(osg::Switch& node); + virtual void apply(osg::LOD& node); + virtual void apply(osg::OccluderNode& node); + + /** Sets the minimum shadow occluder volume that an active occluder + * must have. vol is units relative the clip space volume where 1.0 + * is the whole clip space. */ + void setMinimumShadowOccluderVolume(float vol) { _minimumShadowOccluderVolume = vol; } + float getMinimumShadowOccluderVolume() const { return _minimumShadowOccluderVolume; } + + /** Sets the maximum number of occluders to have active for culling + * purposes. */ + void setMaximumNumberOfActiveOccluders(unsigned int num) { _maximumNumberOfActiveOccluders = num; } + unsigned int getMaximumNumberOfActiveOccluders() const { return _maximumNumberOfActiveOccluders; } + + void setCreateDrawablesOnOccludeNodes(bool flag) { _createDrawables=flag; } + bool getCreateDrawablesOnOccludeNodes() const { return _createDrawables; } + + void setCollectedOccluderSet(const ShadowVolumeOccluderSet& svol) { _occluderSet = svol; } + ShadowVolumeOccluderSet& getCollectedOccluderSet() { return _occluderSet; } + const ShadowVolumeOccluderSet& getCollectedOccluderSet() const { return _occluderSet; } + + /** Removes occluded occluders for the collected occluders list, then + * discards all but MaximumNumberOfActiveOccluders of occluders, + * discarding the occluders with the lowest shadow occluder volume. */ + void removeOccludedOccluders(); + + + protected: + + /** Prevents unwanted copy construction. */ + //CollectOccludersVisitor(const CollectOccludersVisitor&):osg::NodeVisitor(),osg::CullStack() {} + + /** Prevents unwanted copy operator. */ + CollectOccludersVisitor& operator = (const CollectOccludersVisitor&) { return *this; } + + inline void handle_cull_callbacks_and_traverse(osg::Node& node) + { + /*osg::NodeCallback* callback = node.getCullCallback(); + if (callback) (*callback)(&node,this); + else*/ if (node.getNumChildrenWithOccluderNodes()>0) traverse(node); + } + + inline void handle_cull_callbacks_and_accept(osg::Node& node,osg::Node* acceptNode) + { + /*osg::NodeCallback* callback = node.getCullCallback(); + if (callback) (*callback)(&node,this); + else*/ if (node.getNumChildrenWithOccluderNodes()>0) acceptNode->accept(*this); + } + + float _minimumShadowOccluderVolume; + unsigned _maximumNumberOfActiveOccluders; + bool _createDrawables; + ShadowVolumeOccluderSet _occluderSet; + +}; + +} + +#endif + diff --git a/libs/include/android/osg/ColorMask b/libs/include/android/osg/ColorMask new file mode 100755 index 0000000..b1cc172 --- /dev/null +++ b/libs/include/android/osg/ColorMask @@ -0,0 +1,100 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_COLORMASK +#define OSG_COLORMASK 1 + +#include +#include + +namespace osg { + +/** Encapsulates OpenGL glColorMaskFunc/Op/Mask functions. +*/ +class OSG_EXPORT ColorMask : public StateAttribute +{ + public : + + + ColorMask(); + + ColorMask(bool red,bool green,bool blue,bool alpha): + _red(red), + _green(green), + _blue(blue), + _alpha(alpha) {} + + + /** Copy constructor using CopyOp to manage deep vs shallow copy. */ + ColorMask(const ColorMask& cm,const CopyOp& copyop=CopyOp::SHALLOW_COPY): + StateAttribute(cm,copyop), + _red(cm._red), + _green(cm._green), + _blue(cm._blue), + _alpha(cm._alpha) {} + + META_StateAttribute(osg, ColorMask, COLORMASK); + + /** Return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs. */ + virtual int compare(const StateAttribute& sa) const + { + // Check for equal types, then create the rhs variable + // used by the COMPARE_StateAttribute_Parameter macros below. + COMPARE_StateAttribute_Types(ColorMask,sa) + + // Compare each parameter in turn against the rhs. + COMPARE_StateAttribute_Parameter(_red) + COMPARE_StateAttribute_Parameter(_green) + COMPARE_StateAttribute_Parameter(_blue) + COMPARE_StateAttribute_Parameter(_alpha) + + return 0; // Passed all the above comparison macros, so must be equal. + } + + inline void setMask(bool red,bool green,bool blue,bool alpha) + { + _red = red; + _green = green; + _blue = blue; + _alpha = alpha; + + } + + inline void setRedMask(bool mask) { _red=mask; } + inline bool getRedMask() const { return _red; } + + inline void setGreenMask(bool mask) { _green=mask; } + inline bool getGreenMask() const { return _green; } + + inline void setBlueMask(bool mask) { _blue=mask; } + inline bool getBlueMask() const { return _blue; } + + inline void setAlphaMask(bool mask) { _alpha=mask; } + inline bool getAlphaMask() const { return _alpha; } + + virtual void apply(State& state) const; + + protected: + + virtual ~ColorMask(); + + bool _red; + bool _green; + bool _blue; + bool _alpha; + +}; + +} + +#endif diff --git a/libs/include/android/osg/ColorMatrix b/libs/include/android/osg/ColorMatrix new file mode 100755 index 0000000..db7afd7 --- /dev/null +++ b/libs/include/android/osg/ColorMatrix @@ -0,0 +1,72 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_COLORMATRIX +#define OSG_COLORMATRIX 1 + +#include +#include + +namespace osg { + +/** Encapsulates OpenGL color matrix functionality. */ +class OSG_EXPORT ColorMatrix : public StateAttribute +{ + public : + + ColorMatrix(); + + /** Copy constructor using CopyOp to manage deep vs shallow copy. */ + ColorMatrix(const ColorMatrix& cm,const CopyOp& copyop=CopyOp::SHALLOW_COPY): + StateAttribute(cm,copyop), + _matrix(cm._matrix) {} + + META_StateAttribute(osg, ColorMatrix, COLORMATRIX); + + /** Return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs. */ + virtual int compare(const StateAttribute& sa) const + { + // Check for equal types, then create the rhs variable + // used by the COMPARE_StateAttribute_Parameter macros below. + COMPARE_StateAttribute_Types(ColorMatrix,sa) + + // Compare each parameter in turn against the rhs. + COMPARE_StateAttribute_Parameter(_matrix) + + return 0; // Passed all the above comparison macros, so must be equal. + } + + /** Sets the color matrix. */ + inline void setMatrix(const Matrix& matrix) { _matrix = matrix; } + + /** Gets the color matrix. */ + inline Matrix& getMatrix() { return _matrix; } + + /** Gets the const color matrix. */ + inline const Matrix& getMatrix() const { return _matrix; } + + /** Applies as OpenGL texture matrix. */ + virtual void apply(State& state) const; + + protected: + + virtual ~ColorMatrix( void ); + + Matrix _matrix; + +}; + +} + + +#endif diff --git a/libs/include/android/osg/ComputeBoundsVisitor b/libs/include/android/osg/ComputeBoundsVisitor new file mode 100755 index 0000000..1efd859 --- /dev/null +++ b/libs/include/android/osg/ComputeBoundsVisitor @@ -0,0 +1,61 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_COMPUTEBOUNDSVISITOR +#define OSG_COMPUTEBOUNDSVISITOR 1 + +#include +#include +#include + +namespace osg { + +class OSG_EXPORT ComputeBoundsVisitor : public osg::NodeVisitor +{ +public: + + ComputeBoundsVisitor(TraversalMode traversalMode = TRAVERSE_ALL_CHILDREN); + + META_NodeVisitor(osg, ComputeBoundsVisitor) + + virtual void reset(); + + osg::BoundingBox& getBoundingBox() { return _bb; } + + void getPolytope(osg::Polytope& polytope, float margin=0.1) const; + + void getBase(osg::Polytope& polytope, float margin=0.1) const; + + void apply(osg::Node& node); + + void apply(osg::Transform& transform); + + void apply(osg::Geode& geode); + + inline void pushMatrix(osg::Matrix& matrix) { _matrixStack.push_back(matrix); } + + inline void popMatrix() { _matrixStack.pop_back(); } + + void applyDrawable(osg::Drawable* drawable); + +protected: + + typedef std::vector MatrixStack; + + MatrixStack _matrixStack; + osg::BoundingBox _bb; +}; + +} + +#endif diff --git a/libs/include/android/osg/Config b/libs/include/android/osg/Config new file mode 100755 index 0000000..43d9b68 --- /dev/null +++ b/libs/include/android/osg/Config @@ -0,0 +1,47 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 2008-2009 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +/**************************************************************************** + * THIS FILE IS AUTOGENERATED BY CMAKE. DO NOT EDIT! + ****************************************************************************/ + +/* Changes to the configuration reflected here can be made with ccmake on + * unix or with cmake-gui on windows. Alternatively you can use cmake's -D + * or -P switches to set some configuration values at cmake configuration time. + */ + +#ifndef OSG_CONFIG +#define OSG_CONFIG 1 + +/* #undef OSG_NOTIFY_DISABLED */ +/* #undef OSG_USE_FLOAT_MATRIX */ +/* #undef OSG_USE_FLOAT_PLANE */ +#define OSG_USE_FLOAT_BOUNDINGSPHERE +#define OSG_USE_FLOAT_BOUNDINGBOX +#define OSG_USE_REF_PTR_IMPLICIT_OUTPUT_CONVERSION +/* #undef OSG_USE_UTF8_FILENAME */ +#define OSG_DISABLE_MSVC_WARNINGS + +/* #undef OSG_GL1_AVAILABLE */ +/* #undef OSG_GL2_AVAILABLE */ +/* #undef OSG_GL3_AVAILABLE */ +#define OSG_GLES1_AVAILABLE +/* #undef OSG_GLES2_AVAILABLE */ +/* #undef OSG_GL_LIBRARY_STATIC */ +/* #undef OSG_GL_DISPLAYLISTS_AVAILABLE */ +#define OSG_GL_MATRICES_AVAILABLE +#define OSG_GL_VERTEX_FUNCS_AVAILABLE +#define OSG_GL_VERTEX_ARRAY_FUNCS_AVAILABLE +#define OSG_GL_FIXED_FUNCTION_AVAILABLE + +#endif diff --git a/libs/include/android/osg/ConvexPlanarOccluder b/libs/include/android/osg/ConvexPlanarOccluder new file mode 100755 index 0000000..ac71539 --- /dev/null +++ b/libs/include/android/osg/ConvexPlanarOccluder @@ -0,0 +1,67 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_CONVEXPLANAROCCLUDER +#define OSG_CONVEXPLANAROCCLUDER 1 + +#include +#include + +namespace osg { + +class OccluderVolume; + +/** A class for representing convex clipping volumes made up of several ConvexPlanarPolygon. */ +class OSG_EXPORT ConvexPlanarOccluder : public Object +{ + + public: + + ConvexPlanarOccluder():Object() {} + ConvexPlanarOccluder(const ConvexPlanarOccluder& cpo,const CopyOp& copyop=CopyOp::SHALLOW_COPY): + Object(cpo,copyop), + _occluder(cpo._occluder), + _holeList(cpo._holeList) {} + + META_Object(osg,ConvexPlanarOccluder); + + void setOccluder(const ConvexPlanarPolygon& cpp) { _occluder = cpp; } + + ConvexPlanarPolygon& getOccluder() { return _occluder; } + + const ConvexPlanarPolygon& getOccluder() const { return _occluder; } + + + + typedef std::vector HoleList; + + void addHole(const ConvexPlanarPolygon& cpp) { _holeList.push_back(cpp); } + + void setHoleList(const HoleList& holeList) { _holeList=holeList; } + + HoleList& getHoleList() { return _holeList; } + + const HoleList& getHoleList() const { return _holeList; } + + protected: + + ~ConvexPlanarOccluder(); // {} + + ConvexPlanarPolygon _occluder; + HoleList _holeList; + +}; + +} // end of namespace + +#endif diff --git a/libs/include/android/osg/ConvexPlanarPolygon b/libs/include/android/osg/ConvexPlanarPolygon new file mode 100755 index 0000000..64efcc8 --- /dev/null +++ b/libs/include/android/osg/ConvexPlanarPolygon @@ -0,0 +1,49 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_CONVEXPLANARPOLYGON +#define OSG_CONVEXPLANARPOLYGON 1 + +#include + +#include + +namespace osg { + +/** A class for representing components of convex clipping volumes. */ +class OSG_EXPORT ConvexPlanarPolygon +{ + + public: + + ConvexPlanarPolygon(); + + typedef std::vector VertexList; + + void add(const Vec3& v) { _vertexList.push_back(v); } + + void setVertexList(const VertexList& vertexList) { _vertexList=vertexList; } + + VertexList& getVertexList() { return _vertexList; } + + const VertexList& getVertexList() const { return _vertexList; } + + protected: + + VertexList _vertexList; + +}; + +} // end of namespace + +#endif diff --git a/libs/include/android/osg/CoordinateSystemNode b/libs/include/android/osg/CoordinateSystemNode new file mode 100755 index 0000000..38d7df9 --- /dev/null +++ b/libs/include/android/osg/CoordinateSystemNode @@ -0,0 +1,248 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_COORDINATESYSTEMNODE +#define OSG_COORDINATESYSTEMNODE 1 + +#include +#include + +namespace osg +{ + +const double WGS_84_RADIUS_EQUATOR = 6378137.0; +const double WGS_84_RADIUS_POLAR = 6356752.3142; + +/** EllipsoidModel encapsulates the ellipsoid used to model astronomical bodies, + * such as sun, planets, moon etc. + * All distance quantities (i.e. heights + radius) are in meters, + * and latitude and longitude are in radians.*/ +class EllipsoidModel : public Object +{ + public: + + /** WGS_84 is a common representation of the earth's spheroid */ + EllipsoidModel(double radiusEquator = WGS_84_RADIUS_EQUATOR, + double radiusPolar = WGS_84_RADIUS_POLAR): + _radiusEquator(radiusEquator), + _radiusPolar(radiusPolar) { computeCoefficients(); } + + EllipsoidModel(const EllipsoidModel& et,const CopyOp& copyop=CopyOp::SHALLOW_COPY): + Object(et,copyop), + _radiusEquator(et._radiusEquator), + _radiusPolar(et._radiusPolar) { computeCoefficients(); } + + META_Object(osg,EllipsoidModel); + + void setRadiusEquator(double radius) { _radiusEquator = radius; computeCoefficients(); } + double getRadiusEquator() const { return _radiusEquator; } + + void setRadiusPolar(double radius) { _radiusPolar = radius; computeCoefficients(); } + double getRadiusPolar() const { return _radiusPolar; } + + inline void convertLatLongHeightToXYZ(double latitude, double longitude, double height, + double& X, double& Y, double& Z) const; + + inline void convertXYZToLatLongHeight(double X, double Y, double Z, + double& latitude, double& longitude, double& height) const; + + inline void computeLocalToWorldTransformFromLatLongHeight(double latitude, double longitude, double height, osg::Matrixd& localToWorld) const; + + inline void computeLocalToWorldTransformFromXYZ(double X, double Y, double Z, osg::Matrixd& localToWorld) const; + + inline void computeCoordinateFrame(double latitude, double longitude, osg::Matrixd& localToWorld) const; + + inline osg::Vec3d computeLocalUpVector(double X, double Y, double Z) const; + + // Convenience method for determining if EllipsoidModel is a stock WGS84 ellipsoid + inline bool isWGS84() const {return(_radiusEquator == WGS_84_RADIUS_EQUATOR && _radiusPolar == WGS_84_RADIUS_POLAR);} + + // Compares two EllipsoidModel by comparing critical internal values. + // Ignores _eccentricitySquared since it's just a cached value derived from + // the _radiusEquator and _radiusPolar members. + friend bool operator == ( const EllipsoidModel & e1, const EllipsoidModel& e2) {return(e1._radiusEquator == e2._radiusEquator && e1._radiusPolar == e2._radiusPolar);} + + + protected: + + void computeCoefficients() + { + double flattening = (_radiusEquator-_radiusPolar)/_radiusEquator; + _eccentricitySquared = 2*flattening - flattening*flattening; + } + + double _radiusEquator; + double _radiusPolar; + double _eccentricitySquared; + +}; + +/** CoordinateFrame encapsulates the orientation of east, north and up.*/ +typedef Matrixd CoordinateFrame; + +/** CoordinateSystem encapsulate the coordinate system that is associated with objects in a scene. + For an overview of common earth bases coordinate systems see http://www.colorado.edu/geography/gcraft/notes/coordsys/coordsys_f.html */ +class OSG_EXPORT CoordinateSystemNode : public Group +{ + public: + + CoordinateSystemNode(); + + CoordinateSystemNode(const std::string& format, const std::string& cs); + + /** Copy constructor using CopyOp to manage deep vs shallow copy.*/ + CoordinateSystemNode(const CoordinateSystemNode&,const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY); + + META_Node(osg,CoordinateSystemNode); + + + /** Set the coordinate system node up by copying the format, coordinate system string, and ellipsoid model of another coordinate system node.*/ + void set(const CoordinateSystemNode& csn); + + /** Set the coordinate system format string. Typical values would be WKT, PROJ4, USGS etc.*/ + void setFormat(const std::string& format) { _format = format; } + + /** Get the coordinate system format string.*/ + const std::string& getFormat() const { return _format; } + + /** Set the CoordinateSystem reference string, should be stored in a form consistent with the Format.*/ + void setCoordinateSystem(const std::string& cs) { _cs = cs; } + + /** Get the CoordinateSystem reference string.*/ + const std::string& getCoordinateSystem() const { return _cs; } + + + /** Set EllipsoidModel to describe the model used to map lat, long and height into geocentric XYZ and back. */ + void setEllipsoidModel(EllipsoidModel* ellipsode) { _ellipsoidModel = ellipsode; } + + /** Get the EllipsoidModel.*/ + EllipsoidModel* getEllipsoidModel() { return _ellipsoidModel.get(); } + + /** Get the const EllipsoidModel.*/ + const EllipsoidModel* getEllipsoidModel() const { return _ellipsoidModel.get(); } + + /** Compute the local coordinate frame for specified point.*/ + CoordinateFrame computeLocalCoordinateFrame(const Vec3d& position) const; + + /** Compute the local up-vector for specified point.*/ + osg::Vec3d computeLocalUpVector(const Vec3d& position) const; + + protected: + + virtual ~CoordinateSystemNode() {} + + std::string _format; + std::string _cs; + ref_ptr _ellipsoidModel; + +}; + + + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// implement inline methods. +// +inline void EllipsoidModel::convertLatLongHeightToXYZ(double latitude, double longitude, double height, + double& X, double& Y, double& Z) const +{ + // for details on maths see http://www.colorado.edu/geography/gcraft/notes/datum/gif/llhxyz.gif + double sin_latitude = sin(latitude); + double cos_latitude = cos(latitude); + double N = _radiusEquator / sqrt( 1.0 - _eccentricitySquared*sin_latitude*sin_latitude); + X = (N+height)*cos_latitude*cos(longitude); + Y = (N+height)*cos_latitude*sin(longitude); + Z = (N*(1-_eccentricitySquared)+height)*sin_latitude; +} + + +inline void EllipsoidModel::convertXYZToLatLongHeight(double X, double Y, double Z, + double& latitude, double& longitude, double& height) const +{ + // http://www.colorado.edu/geography/gcraft/notes/datum/gif/xyzllh.gif + double p = sqrt(X*X + Y*Y); + double theta = atan2(Z*_radiusEquator , (p*_radiusPolar)); + double eDashSquared = (_radiusEquator*_radiusEquator - _radiusPolar*_radiusPolar)/ + (_radiusPolar*_radiusPolar); + + double sin_theta = sin(theta); + double cos_theta = cos(theta); + + latitude = atan( (Z + eDashSquared*_radiusPolar*sin_theta*sin_theta*sin_theta) / + (p - _eccentricitySquared*_radiusEquator*cos_theta*cos_theta*cos_theta) ); + longitude = atan2(Y,X); + + double sin_latitude = sin(latitude); + double N = _radiusEquator / sqrt( 1.0 - _eccentricitySquared*sin_latitude*sin_latitude); + + height = p/cos(latitude) - N; +} + +inline void EllipsoidModel::computeLocalToWorldTransformFromLatLongHeight(double latitude, double longitude, double height, osg::Matrixd& localToWorld) const +{ + double X, Y, Z; + convertLatLongHeightToXYZ(latitude,longitude,height,X,Y,Z); + + localToWorld.makeTranslate(X,Y,Z); + computeCoordinateFrame(latitude, longitude, localToWorld); +} + +inline void EllipsoidModel::computeLocalToWorldTransformFromXYZ(double X, double Y, double Z, osg::Matrixd& localToWorld) const +{ + double latitude, longitude, height; + convertXYZToLatLongHeight(X,Y,Z,latitude,longitude,height); + + localToWorld.makeTranslate(X,Y,Z); + computeCoordinateFrame(latitude, longitude, localToWorld); +} + +inline void EllipsoidModel::computeCoordinateFrame(double latitude, double longitude, osg::Matrixd& localToWorld) const +{ + // Compute up vector + osg::Vec3d up ( cos(longitude)*cos(latitude), sin(longitude)*cos(latitude), sin(latitude)); + + // Compute east vector + osg::Vec3d east (-sin(longitude), cos(longitude), 0); + + // Compute north vector = outer product up x east + osg::Vec3d north = up ^ east; + + // set matrix + localToWorld(0,0) = east[0]; + localToWorld(0,1) = east[1]; + localToWorld(0,2) = east[2]; + + localToWorld(1,0) = north[0]; + localToWorld(1,1) = north[1]; + localToWorld(1,2) = north[2]; + + localToWorld(2,0) = up[0]; + localToWorld(2,1) = up[1]; + localToWorld(2,2) = up[2]; +} + +inline osg::Vec3d EllipsoidModel::computeLocalUpVector(double X, double Y, double Z) const +{ + // Note latitude is angle between normal to ellipsoid surface and XY-plane + double latitude; + double longitude; + double altitude; + convertXYZToLatLongHeight(X,Y,Z,latitude,longitude,altitude); + + // Compute up vector + return osg::Vec3d( cos(longitude) * cos(latitude), + sin(longitude) * cos(latitude), + sin(latitude)); +} + +} +#endif diff --git a/libs/include/android/osg/CopyOp b/libs/include/android/osg/CopyOp new file mode 100755 index 0000000..096e0c5 --- /dev/null +++ b/libs/include/android/osg/CopyOp @@ -0,0 +1,93 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_COPYOP +#define OSG_COPYOP 1 + +#include + +namespace osg { + +class Referenced; +class Object; +class Image; +class Texture; +class StateSet; +class StateAttribute; +class StateAttributeCallback; +class Uniform; +class Node; +class Drawable; +class Array; +class PrimitiveSet; +class Shape; +class NodeCallback; + + +/** Copy Op(erator) used to control whether shallow or deep copy is used + * during copy construction and clone operation.*/ +class OSG_EXPORT CopyOp +{ + + public: + + enum Options + { + SHALLOW_COPY = 0, + DEEP_COPY_OBJECTS = 1<<0, + DEEP_COPY_NODES = 1<<1, + DEEP_COPY_DRAWABLES = 1<<2, + DEEP_COPY_STATESETS = 1<<3, + DEEP_COPY_STATEATTRIBUTES = 1<<4, + DEEP_COPY_TEXTURES = 1<<5, + DEEP_COPY_IMAGES = 1<<6, + DEEP_COPY_ARRAYS = 1<<7, + DEEP_COPY_PRIMITIVES = 1<<8, + DEEP_COPY_SHAPES = 1<<9, + DEEP_COPY_UNIFORMS = 1<<10, + DEEP_COPY_CALLBACKS = 1<<11, + DEEP_COPY_USERDATA = 1<<12, + DEEP_COPY_ALL = 0x7FFFFFFF + }; + + typedef unsigned int CopyFlags; + + inline CopyOp(CopyFlags flags=SHALLOW_COPY):_flags(flags) {} + virtual ~CopyOp() {} + + void setCopyFlags(CopyFlags flags) { _flags = flags; } + CopyFlags getCopyFlags() const { return _flags; } + + virtual Referenced* operator() (const Referenced* ref) const; + virtual Object* operator() (const Object* obj) const; + virtual Node* operator() (const Node* node) const; + virtual Drawable* operator() (const Drawable* drawable) const; + virtual StateSet* operator() (const StateSet* stateset) const; + virtual StateAttribute* operator() (const StateAttribute* attr) const; + virtual Texture* operator() (const Texture* text) const; + virtual Image* operator() (const Image* image) const; + virtual Array* operator() (const Array* array) const; + virtual PrimitiveSet* operator() (const PrimitiveSet* primitives) const; + virtual Shape* operator() (const Shape* shape) const; + virtual Uniform* operator() (const Uniform* shape) const; + virtual NodeCallback* operator() (const NodeCallback* nodecallback) const; + virtual StateAttributeCallback* operator() (const StateAttributeCallback* stateattributecallback) const; + + protected: + + CopyFlags _flags; +}; + +} + +#endif diff --git a/libs/include/android/osg/CullFace b/libs/include/android/osg/CullFace new file mode 100755 index 0000000..6c54474 --- /dev/null +++ b/libs/include/android/osg/CullFace @@ -0,0 +1,79 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_CULLFACE +#define OSG_CULLFACE 1 + +#include +#include + +namespace osg { + +/** Class to globally enable/disable OpenGL's polygon culling mode. + */ +class OSG_EXPORT CullFace : public StateAttribute +{ + public : + + enum Mode { + FRONT = GL_FRONT, + BACK = GL_BACK, + FRONT_AND_BACK = GL_FRONT_AND_BACK + }; + + CullFace(Mode mode=BACK): + _mode(mode) {} + + /** Copy constructor using CopyOp to manage deep vs shallow copy.*/ + CullFace(const CullFace& cf,const CopyOp& copyop=CopyOp::SHALLOW_COPY): + StateAttribute(cf,copyop), + _mode(cf._mode) {} + + META_StateAttribute(osg, CullFace, CULLFACE); + + /** return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs.*/ + virtual int compare(const StateAttribute& sa) const + { + // check the types are equal and then create the rhs variable + // used by the COMPARE_StateAttribute_Parameter macros below. + COMPARE_StateAttribute_Types(CullFace,sa) + + // compare each parameter in turn against the rhs. + COMPARE_StateAttribute_Parameter(_mode) + + return 0; // passed all the above comparison macros, must be equal. + } + + virtual bool getModeUsage(StateAttribute::ModeUsage& usage) const + { + usage.usesMode(GL_CULL_FACE); + return true; + } + + inline void setMode(Mode mode) { _mode = mode; } + + inline Mode getMode() const { return _mode; } + + virtual void apply(State& state) const; + + protected: + + virtual ~CullFace(); + + Mode _mode; + +}; + +} + +#endif diff --git a/libs/include/android/osg/CullSettings b/libs/include/android/osg/CullSettings new file mode 100755 index 0000000..b7a7e16 --- /dev/null +++ b/libs/include/android/osg/CullSettings @@ -0,0 +1,276 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_CULLSETTINGS +#define OSG_CULLSETTINGS 1 + +#include +#include +#include + +namespace osg { + +// forward declare +class ArgumentParser; +class ApplicationUsage; + +class OSG_EXPORT CullSettings +{ + public: + + CullSettings() + { + setDefaults(); + readEnvironmentalVariables(); + } + + CullSettings(ArgumentParser& arguments) + { + setDefaults(); + readEnvironmentalVariables(); + readCommandLine(arguments); + } + + CullSettings(const CullSettings& cs); + + virtual ~CullSettings() {} + + CullSettings& operator = (const CullSettings& settings) + { + if (this==&settings) return *this; + setCullSettings(settings); + return *this; + } + + + virtual void setDefaults(); + + + enum VariablesMask + { + COMPUTE_NEAR_FAR_MODE = (0x1 << 0), + CULLING_MODE = (0x1 << 1), + LOD_SCALE = (0x1 << 2), + SMALL_FEATURE_CULLING_PIXEL_SIZE = (0x1 << 3), + CLAMP_PROJECTION_MATRIX_CALLBACK = (0x1 << 4), + NEAR_FAR_RATIO = (0x1 << 5), + IMPOSTOR_ACTIVE = (0x1 << 6), + DEPTH_SORT_IMPOSTOR_SPRITES = (0x1 << 7), + IMPOSTOR_PIXEL_ERROR_THRESHOLD = (0x1 << 8), + NUM_FRAMES_TO_KEEP_IMPOSTORS_SPRITES = (0x1 << 9), + CULL_MASK = (0x1 << 10), + CULL_MASK_LEFT = (0x1 << 11), + CULL_MASK_RIGHT = (0x1 << 12), + CLEAR_COLOR = (0x1 << 13), + CLEAR_MASK = (0x1 << 14), + LIGHTING_MODE = (0x1 << 15), + LIGHT = (0x1 << 16), + DRAW_BUFFER = (0x1 << 17), + READ_BUFFER = (0x1 << 18), + + NO_VARIABLES = 0x00000000, + ALL_VARIABLES = 0x7FFFFFFF + }; + + typedef int InheritanceMask; + + /** Set the inheritance mask used in inheritCullSettings to control which variables get overwritten by the passed in CullSettings object.*/ + void setInheritanceMask(InheritanceMask mask) { _inheritanceMask = mask; } + + /** Get the inheritance mask used in inheritCullSettings to control which variables get overwritten by the passed in CullSettings object.*/ + InheritanceMask getInheritanceMask() const { return _inheritanceMask; } + + /** Set the local cull settings values from specified CullSettings object.*/ + void setCullSettings(const CullSettings& settings); + + /** Inherit the local cull settings variable from specified CullSettings object, according to the inheritance mask.*/ + virtual void inheritCullSettings(const CullSettings& settings) { inheritCullSettings(settings, _inheritanceMask); } + + /** Inherit the local cull settings variable from specified CullSettings object, according to the inheritance mask.*/ + virtual void inheritCullSettings(const CullSettings& settings, unsigned int inheritanceMask); + + /** read the environmental variables.*/ + void readEnvironmentalVariables(); + + /** read the commandline arguments.*/ + void readCommandLine(ArgumentParser& arguments); + + + enum InheritanceMaskActionOnAttributeSetting + { + DISABLE_ASSOCIATED_INHERITANCE_MASK_BIT, + DO_NOT_MODIFY_INHERITANCE_MASK + }; + + void setInheritanceMaskActionOnAttributeSetting(InheritanceMaskActionOnAttributeSetting action) { _inheritanceMaskActionOnAttributeSetting = action; } + InheritanceMaskActionOnAttributeSetting getInheritanceMaskActionOnAttributeSetting() const { return _inheritanceMaskActionOnAttributeSetting; } + + /** Apply the action, specified by the InheritanceMaskActionOnAttributeSetting, to apply to the inheritance bit mask. + * This method is called by CullSettings::set*() parameter methods to ensure that CullSettings inheritance mechanisms doesn't overwrite the local parameter settings.*/ + inline void applyMaskAction(unsigned int maskBit) + { + if (_inheritanceMaskActionOnAttributeSetting==DISABLE_ASSOCIATED_INHERITANCE_MASK_BIT) + { + _inheritanceMask = _inheritanceMask & (~maskBit); + } + } + + + /** Switch the creation of Impostors on or off. + * Setting active to false forces the CullVisitor to use the Impostor + * LOD children for rendering. Setting active to true forces the + * CullVisitor to create the appropriate pre-rendering stages which + * render to the ImpostorSprite's texture.*/ + void setImpostorsActive(bool active) { _impostorActive = active; applyMaskAction(IMPOSTOR_ACTIVE); } + + /** Get whether impostors are active or not. */ + bool getImpostorsActive() const { return _impostorActive; } + + /** Set the impostor error threshold. + * Used in calculation of whether impostors remain valid.*/ + void setImpostorPixelErrorThreshold(float numPixels) { _impostorPixelErrorThreshold=numPixels; applyMaskAction(IMPOSTOR_PIXEL_ERROR_THRESHOLD); } + + /** Get the impostor error threshold.*/ + float getImpostorPixelErrorThreshold() const { return _impostorPixelErrorThreshold; } + + /** Set whether ImpostorSprite's should be placed in a depth sorted bin for rendering.*/ + void setDepthSortImpostorSprites(bool doDepthSort) { _depthSortImpostorSprites = doDepthSort; applyMaskAction(DEPTH_SORT_IMPOSTOR_SPRITES); } + + /** Get whether ImpostorSprite's are depth sorted bin for rendering.*/ + bool getDepthSortImpostorSprites() const { return _depthSortImpostorSprites; } + + /** Set the number of frames that an ImpostorSprite is kept whilst not being beyond, + * before being recycled.*/ + void setNumberOfFrameToKeepImpostorSprites(int numFrames) { _numFramesToKeepImpostorSprites = numFrames; applyMaskAction(NUM_FRAMES_TO_KEEP_IMPOSTORS_SPRITES); } + + /** Get the number of frames that an ImpostorSprite is kept whilst not being beyond, + * before being recycled.*/ + int getNumberOfFrameToKeepImpostorSprites() const { return _numFramesToKeepImpostorSprites; } + + enum ComputeNearFarMode + { + DO_NOT_COMPUTE_NEAR_FAR = 0, + COMPUTE_NEAR_FAR_USING_BOUNDING_VOLUMES, + COMPUTE_NEAR_FAR_USING_PRIMITIVES, + COMPUTE_NEAR_USING_PRIMITIVES + }; + + void setComputeNearFarMode(ComputeNearFarMode cnfm) { _computeNearFar=cnfm; applyMaskAction(COMPUTE_NEAR_FAR_MODE); } + ComputeNearFarMode getComputeNearFarMode() const { return _computeNearFar;} + + void setNearFarRatio(double ratio) { _nearFarRatio = ratio; applyMaskAction(NEAR_FAR_RATIO); } + double getNearFarRatio() const { return _nearFarRatio; } + + enum CullingModeValues + { + NO_CULLING = 0x0, + VIEW_FRUSTUM_SIDES_CULLING = 0x1, + NEAR_PLANE_CULLING = 0x2, + FAR_PLANE_CULLING = 0x4, + VIEW_FRUSTUM_CULLING = VIEW_FRUSTUM_SIDES_CULLING| + NEAR_PLANE_CULLING| + FAR_PLANE_CULLING, + SMALL_FEATURE_CULLING = 0x8, + SHADOW_OCCLUSION_CULLING = 0x10, + CLUSTER_CULLING = 0x20, + DEFAULT_CULLING = VIEW_FRUSTUM_SIDES_CULLING| + SMALL_FEATURE_CULLING| + SHADOW_OCCLUSION_CULLING| + CLUSTER_CULLING, + ENABLE_ALL_CULLING = VIEW_FRUSTUM_CULLING| + SMALL_FEATURE_CULLING| + SHADOW_OCCLUSION_CULLING| + CLUSTER_CULLING + }; + + typedef int CullingMode; + + /** Set the culling mode for the CullVisitor to use.*/ + void setCullingMode(CullingMode mode) { _cullingMode = mode; applyMaskAction(CULLING_MODE); } + + /** Returns the current CullingMode.*/ + CullingMode getCullingMode() const { return _cullingMode; } + + + void setCullMask(osg::Node::NodeMask nm) { _cullMask = nm; applyMaskAction(CULL_MASK); } + osg::Node::NodeMask getCullMask() const { return _cullMask; } + + void setCullMaskLeft(osg::Node::NodeMask nm) { _cullMaskLeft = nm; applyMaskAction(CULL_MASK_LEFT); } + osg::Node::NodeMask getCullMaskLeft() const { return _cullMaskLeft; } + + void setCullMaskRight(osg::Node::NodeMask nm) { _cullMaskRight = nm; applyMaskAction(CULL_MASK_RIGHT); } + osg::Node::NodeMask getCullMaskRight() const { return _cullMaskRight; } + + /** Set the LOD bias for the CullVisitor to use.*/ + void setLODScale(float scale) { _LODScale = scale; applyMaskAction(LOD_SCALE); } + + /** Get the LOD bias.*/ + float getLODScale() const { return _LODScale; } + + /** Threshold at which small features are culled. + \param value Boulding volume size in screen space. Default is 2.0. */ + void setSmallFeatureCullingPixelSize(float value) { _smallFeatureCullingPixelSize=value; applyMaskAction(SMALL_FEATURE_CULLING_PIXEL_SIZE); } + + /** Get the Small Feature Culling Pixel Size.*/ + float getSmallFeatureCullingPixelSize() const { return _smallFeatureCullingPixelSize; } + + + + /** Callback for overriding the CullVisitor's default clamping of the projection matrix to computed near and far values. + * Note, both Matrixf and Matrixd versions of clampProjectionMatrixImplementation must be implemented as the CullVisitor + * can target either Matrix data type, configured at compile time.*/ + struct ClampProjectionMatrixCallback : public osg::Referenced + { + virtual bool clampProjectionMatrixImplementation(osg::Matrixf& projection, double& znear, double& zfar) const = 0; + virtual bool clampProjectionMatrixImplementation(osg::Matrixd& projection, double& znear, double& zfar) const = 0; + }; + + /** set the ClampProjectionMatrixCallback.*/ + void setClampProjectionMatrixCallback(ClampProjectionMatrixCallback* cpmc) { _clampProjectionMatrixCallback = cpmc; applyMaskAction(CLAMP_PROJECTION_MATRIX_CALLBACK); } + /** get the non const ClampProjectionMatrixCallback.*/ + ClampProjectionMatrixCallback* getClampProjectionMatrixCallback() { return _clampProjectionMatrixCallback.get(); } + /** get the const ClampProjectionMatrixCallback.*/ + const ClampProjectionMatrixCallback* getClampProjectionMatrixCallback() const { return _clampProjectionMatrixCallback.get(); } + + + /** Write out internal settings of CullSettings. */ + void write(std::ostream& out); + + protected: + + InheritanceMask _inheritanceMask; + InheritanceMaskActionOnAttributeSetting _inheritanceMaskActionOnAttributeSetting; + + ComputeNearFarMode _computeNearFar; + CullingMode _cullingMode; + float _LODScale; + float _smallFeatureCullingPixelSize; + + ref_ptr _clampProjectionMatrixCallback; + double _nearFarRatio; + bool _impostorActive; + bool _depthSortImpostorSprites; + float _impostorPixelErrorThreshold; + int _numFramesToKeepImpostorSprites; + + Node::NodeMask _cullMask; + Node::NodeMask _cullMaskLeft; + Node::NodeMask _cullMaskRight; + + +}; + + +} + +#endif diff --git a/libs/include/android/osg/CullStack b/libs/include/android/osg/CullStack new file mode 100755 index 0000000..c59ec97 --- /dev/null +++ b/libs/include/android/osg/CullStack @@ -0,0 +1,310 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_CULLSTACK +#define OSG_CULLSTACK 1 + +#include +#include +#include +#include +#include + +namespace osg { + +/** A CullStack class which accumulates the current project, modelview matrices +and the CullingSet. */ +class OSG_EXPORT CullStack : public osg::CullSettings +{ + + public: + + + CullStack(); + CullStack(const CullStack& cs); + + ~CullStack(); + + typedef std::vector OccluderList; + + void reset(); + + void pushCullingSet(); + void popCullingSet(); + + void setOccluderList(const ShadowVolumeOccluderList& svol) { _occluderList = svol; } + ShadowVolumeOccluderList& getOccluderList() { return _occluderList; } + const ShadowVolumeOccluderList& getOccluderList() const { return _occluderList; } + + void pushViewport(osg::Viewport* viewport); + void popViewport(); + + void pushProjectionMatrix(osg::RefMatrix* matrix); + void popProjectionMatrix(); + + void pushModelViewMatrix(osg::RefMatrix* matrix, Transform::ReferenceFrame referenceFrame); + void popModelViewMatrix(); + + inline float getFrustumVolume() { if (_frustumVolume<0.0f) computeFrustumVolume(); return _frustumVolume; } + + + /** Compute the pixel size of an object at position v, with specified radius.*/ + float pixelSize(const Vec3& v,float radius) const + { + return getCurrentCullingSet().pixelSize(v,radius); + } + + /** Compute the pixel size of the bounding sphere.*/ + float pixelSize(const BoundingSphere& bs) const + { + return pixelSize(bs.center(),bs.radius()); + } + + /** Compute the pixel size of an object at position v, with specified radius. fabs()ed to always be positive. */ + float clampedPixelSize(const Vec3& v,float radius) const + { + return getCurrentCullingSet().clampedPixelSize(v,radius); + } + + /** Compute the pixel size of the bounding sphere. fabs()ed to always be positive. */ + float clampedPixelSize(const BoundingSphere& bs) const + { + return clampedPixelSize(bs.center(),bs.radius()); + } + + inline void disableAndPushOccludersCurrentMask(NodePath& nodePath) + { + getCurrentCullingSet().disableAndPushOccludersCurrentMask(nodePath); + } + + inline void popOccludersCurrentMask(NodePath& nodePath) + { + getCurrentCullingSet().popOccludersCurrentMask(nodePath); + } + + inline bool isCulled(const std::vector& vertices) + { + return getCurrentCullingSet().isCulled(vertices); + } + + inline bool isCulled(const BoundingBox& bb) + { + return bb.valid() && getCurrentCullingSet().isCulled(bb); + } + + inline bool isCulled(const BoundingSphere& bs) + { + return getCurrentCullingSet().isCulled(bs); + } + + inline bool isCulled(const osg::Node& node) + { + if (node.isCullingActive()) + { + return getCurrentCullingSet().isCulled(node.getBound()); + } + else + { + getCurrentCullingSet().resetCullingMask(); + return false; + } + } + + inline void pushCurrentMask() + { + getCurrentCullingSet().pushCurrentMask(); + } + + inline void popCurrentMask() + { + getCurrentCullingSet().popCurrentMask(); + } + + + typedef std::vector< CullingSet > CullingStack; + + inline CullingStack& getClipSpaceCullingStack() { return _clipspaceCullingStack; } + + inline CullingStack& getProjectionCullingStack() { return _projectionCullingStack; } + + inline CullingStack& getModelViewCullingStack() { return _modelviewCullingStack; } + + inline CullingSet& getCurrentCullingSet() { return *_back_modelviewCullingStack; } + inline const CullingSet& getCurrentCullingSet() const { return *_back_modelviewCullingStack; } + + inline osg::Viewport* getViewport(); + inline osg::RefMatrix* getModelViewMatrix(); + inline osg::RefMatrix* getProjectionMatrix(); + inline osg::Matrix getWindowMatrix(); + inline const osg::RefMatrix* getMVPW(); + + inline const osg::Vec3& getReferenceViewPoint() const { return _referenceViewPoints.back(); } + inline void pushReferenceViewPoint(const osg::Vec3& viewPoint) { _referenceViewPoints.push_back(viewPoint); } + inline void popReferenceViewPoint() { _referenceViewPoints.pop_back(); } + + inline const osg::Vec3& getEyeLocal() const { return _eyePointStack.back(); } + + inline const osg::Vec3& getViewPointLocal() const { return _viewPointStack.back(); } + + inline const osg::Vec3 getUpLocal() const + { + const osg::Matrix& matrix = *_modelviewStack.back(); + return osg::Vec3(matrix(0,1),matrix(1,1),matrix(2,1)); + } + + inline const osg::Vec3 getLookVectorLocal() const + { + const osg::Matrix& matrix = *_modelviewStack.back(); + return osg::Vec3(-matrix(0,2),-matrix(1,2),-matrix(2,2)); + } + + + protected: + + // base set of shadow volume occluder to use in culling. + ShadowVolumeOccluderList _occluderList; + + typedef fast_back_stack< ref_ptr > MatrixStack; + + MatrixStack _projectionStack; + + MatrixStack _modelviewStack; + MatrixStack _MVPW_Stack; + + typedef fast_back_stack > ViewportStack; + ViewportStack _viewportStack; + + typedef fast_back_stack EyePointStack; + EyePointStack _referenceViewPoints; + EyePointStack _eyePointStack; + EyePointStack _viewPointStack; + + CullingStack _clipspaceCullingStack; + CullingStack _projectionCullingStack; + + CullingStack _modelviewCullingStack; + unsigned int _index_modelviewCullingStack; + CullingSet* _back_modelviewCullingStack; + + void computeFrustumVolume(); + float _frustumVolume; + + unsigned int _bbCornerNear; + unsigned int _bbCornerFar; + + ref_ptr _identity; + + typedef std::vector< osg::ref_ptr > MatrixList; + MatrixList _reuseMatrixList; + unsigned int _currentReuseMatrixIndex; + + inline osg::RefMatrix* createOrReuseMatrix(const osg::Matrix& value); + + +}; + +inline osg::Viewport* CullStack::getViewport() +{ + if (!_viewportStack.empty()) + { + return _viewportStack.back().get(); + } + else + { + return 0L; + } +} + +inline osg::RefMatrix* CullStack::getModelViewMatrix() +{ + if (!_modelviewStack.empty()) + { + return _modelviewStack.back().get(); + } + else + { + return _identity.get(); + } +} + +inline osg::RefMatrix* CullStack::getProjectionMatrix() +{ + if (!_projectionStack.empty()) + { + return _projectionStack.back().get(); + } + else + { + return _identity.get(); + } +} + +inline osg::Matrix CullStack::getWindowMatrix() +{ + if (!_viewportStack.empty()) + { + osg::Viewport* viewport = _viewportStack.back().get(); + return viewport->computeWindowMatrix(); + } + else + { + return *_identity; + } +} + +inline const osg::RefMatrix* CullStack::getMVPW() +{ + if (!_MVPW_Stack.empty()) + { + if (!_MVPW_Stack.back()) + { + _MVPW_Stack.back() = createOrReuseMatrix(*getModelViewMatrix()); + (*_MVPW_Stack.back()) *= *(getProjectionMatrix()); + (*_MVPW_Stack.back()) *= getWindowMatrix(); + } + return _MVPW_Stack.back().get(); + } + else + { + return _identity.get(); + } +} + +inline RefMatrix* CullStack::createOrReuseMatrix(const osg::Matrix& value) +{ + // skip of any already reused matrix. + while (_currentReuseMatrixIndex<_reuseMatrixList.size() && + _reuseMatrixList[_currentReuseMatrixIndex]->referenceCount()>1) + { + ++_currentReuseMatrixIndex; + } + + // if still within list, element must be singularly referenced + // there return it to be reused. + if (_currentReuseMatrixIndex<_reuseMatrixList.size()) + { + RefMatrix* matrix = _reuseMatrixList[_currentReuseMatrixIndex++].get(); + matrix->set(value); + return matrix; + } + + // otherwise need to create new matrix. + osg::RefMatrix* matrix = new RefMatrix(value); + _reuseMatrixList.push_back(matrix); + ++_currentReuseMatrixIndex; + return matrix; +} + +} // end of namespace + +#endif diff --git a/libs/include/android/osg/CullingSet b/libs/include/android/osg/CullingSet new file mode 100755 index 0000000..a22b99c --- /dev/null +++ b/libs/include/android/osg/CullingSet @@ -0,0 +1,357 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_CullingSet +#define OSG_CullingSet 1 + +#include +#include +#include + +#include + + +namespace osg { + +#define COMPILE_WITH_SHADOW_OCCLUSION_CULLING + +/** A CullingSet class which contains a frustum and a list of occluders. */ +class OSG_EXPORT CullingSet : public Referenced +{ + + public: + + typedef std::pair< osg::ref_ptr, osg::Polytope > StateFrustumPair; + typedef std::vector< StateFrustumPair > StateFrustumList; + + CullingSet(); + + CullingSet(const CullingSet& cs): + Referenced(), + _mask(cs._mask), + _frustum(cs._frustum), + _stateFrustumList(cs._stateFrustumList), + _occluderList(cs._occluderList), + _pixelSizeVector(cs._pixelSizeVector), + _smallFeatureCullingPixelSize(cs._smallFeatureCullingPixelSize) + { + } + + CullingSet(const CullingSet& cs,const Matrix& matrix, const Vec4& pixelSizeVector): + _mask(cs._mask), + _frustum(cs._frustum), + _stateFrustumList(cs._stateFrustumList), + _occluderList(cs._occluderList), + _pixelSizeVector(pixelSizeVector), + _smallFeatureCullingPixelSize(cs._smallFeatureCullingPixelSize) + { + _frustum.transformProvidingInverse(matrix); + for(OccluderList::iterator itr=_occluderList.begin(); + itr!=_occluderList.end(); + ++itr) + { + itr->transformProvidingInverse(matrix); + } + } + + CullingSet& operator = (const CullingSet& cs) + { + if (this==&cs) return *this; + + _mask = cs._mask; + _frustum = cs._frustum; + _stateFrustumList = cs._stateFrustumList; + _occluderList = cs._occluderList; + _pixelSizeVector = cs._pixelSizeVector; + _smallFeatureCullingPixelSize = cs._smallFeatureCullingPixelSize; + + return *this; + } + + + inline void set(const CullingSet& cs) + { + _mask = cs._mask; + _frustum = cs._frustum; + _stateFrustumList = cs._stateFrustumList; + _occluderList = cs._occluderList; + _pixelSizeVector = cs._pixelSizeVector; + _smallFeatureCullingPixelSize = cs._smallFeatureCullingPixelSize; + } + + inline void set(const CullingSet& cs,const Matrix& matrix, const Vec4& pixelSizeVector) + { + _mask = cs._mask; + _stateFrustumList = cs._stateFrustumList; + _occluderList = cs._occluderList; + _pixelSizeVector = pixelSizeVector; + _smallFeatureCullingPixelSize = cs._smallFeatureCullingPixelSize; + + //_frustum = cs._frustum; + //_frustum.transformProvidingInverse(matrix); + + _frustum.setAndTransformProvidingInverse(cs._frustum,matrix); + + for(StateFrustumList::iterator sitr=_stateFrustumList.begin(); + sitr!=_stateFrustumList.end(); + ++sitr) + { + sitr->second.transformProvidingInverse(matrix); + } + + for(OccluderList::iterator oitr=_occluderList.begin(); + oitr!=_occluderList.end(); + ++oitr) + { + oitr->transformProvidingInverse(matrix); + } + + } + + typedef std::vector OccluderList; + + typedef int Mask; + + enum MaskValues + { + NO_CULLING = 0x0, + VIEW_FRUSTUM_SIDES_CULLING = 0x1, + NEAR_PLANE_CULLING = 0x2, + FAR_PLANE_CULLING = 0x4, + VIEW_FRUSTUM_CULLING = VIEW_FRUSTUM_SIDES_CULLING| + NEAR_PLANE_CULLING| + FAR_PLANE_CULLING, + SMALL_FEATURE_CULLING = 0x8, + SHADOW_OCCLUSION_CULLING = 0x10, + DEFAULT_CULLING = VIEW_FRUSTUM_SIDES_CULLING| + SMALL_FEATURE_CULLING| + SHADOW_OCCLUSION_CULLING, + ENABLE_ALL_CULLING = VIEW_FRUSTUM_CULLING| + SMALL_FEATURE_CULLING| + SHADOW_OCCLUSION_CULLING + }; + + void setCullingMask(Mask mask) { _mask = mask; } + Mask getCullingMask() const { return _mask; } + + void setFrustum(Polytope& cv) { _frustum = cv; } + + Polytope& getFrustum() { return _frustum; } + const Polytope& getFrustum() const { return _frustum; } + + void addStateFrustum(StateSet* stateset, Polytope& polytope) { _stateFrustumList.push_back(StateFrustumPair(stateset,polytope)); } + + void getStateFrustumList(StateFrustumList& sfl) { _stateFrustumList = sfl; } + StateFrustumList& getStateFrustumList() { return _stateFrustumList; } + + void addOccluder(ShadowVolumeOccluder& cv) { _occluderList.push_back(cv); } + + void setPixelSizeVector(const Vec4& v) { _pixelSizeVector = v; } + + Vec4& getPixelSizeVector() { return _pixelSizeVector; } + const Vec4& getPixelSizeVector() const { return _pixelSizeVector; } + + /** Threshold at which small features are culled. + \param value Boulding volume size in screen space. Default is 2.0. */ + void setSmallFeatureCullingPixelSize(float value) { _smallFeatureCullingPixelSize=value; } + + float& getSmallFeatureCullingPixelSize() { return _smallFeatureCullingPixelSize; } + + float getSmallFeatureCullingPixelSize() const { return _smallFeatureCullingPixelSize; } + + + /** Compute the pixel of an object at position v, with specified radius.*/ + float pixelSize(const Vec3& v,float radius) const { return radius/(v*_pixelSizeVector); } + + /** Compute the pixel of a bounding sphere.*/ + float pixelSize(const BoundingSphere& bs) const { return bs.radius()/(bs.center()*_pixelSizeVector); } + + /** Compute the pixel of an object at position v, with specified radius. fabs()ed to always be positive. */ + float clampedPixelSize(const Vec3& v,float radius) const { return fabs(pixelSize(v, radius)); } + + /** Compute the pixel of a bounding sphere. fabs()ed to always be positive. */ + float clampedPixelSize(const BoundingSphere& bs) const { return fabs(pixelSize(bs)); } + + + inline bool isCulled(const std::vector& vertices) + { + if (_mask&VIEW_FRUSTUM_CULLING) + { + // is it outside the view frustum... + if (!_frustum.contains(vertices)) return true; + } + + if (_mask&SMALL_FEATURE_CULLING) + { + } + + if (_mask&SHADOW_OCCLUSION_CULLING) + { + // is it in one of the shadow occluder volumes. + if (!_occluderList.empty()) + { + for(OccluderList::iterator itr=_occluderList.begin(); + itr!=_occluderList.end(); + ++itr) + { + if (itr->contains(vertices)) return true; + } + } + } + + return false; + } + + inline bool isCulled(const BoundingBox& bb) + { + if (_mask&VIEW_FRUSTUM_CULLING) + { + // is it outside the view frustum... + if (!_frustum.contains(bb)) return true; + } + + if (_mask&SMALL_FEATURE_CULLING) + { + } + + if (_mask&SHADOW_OCCLUSION_CULLING) + { + // is it in one of the shadow occluder volumes. + if (!_occluderList.empty()) + { + for(OccluderList::iterator itr=_occluderList.begin(); + itr!=_occluderList.end(); + ++itr) + { + if (itr->contains(bb)) return true; + } + } + } + + return false; + } + + inline bool isCulled(const BoundingSphere& bs) + { + if (_mask&VIEW_FRUSTUM_CULLING) + { + // is it outside the view frustum... + if (!_frustum.contains(bs)) return true; + } + + if (_mask&SMALL_FEATURE_CULLING) + { + if (((bs.center()*_pixelSizeVector)*_smallFeatureCullingPixelSize)>bs.radius()) return true; + } +#ifdef COMPILE_WITH_SHADOW_OCCLUSION_CULLING + if (_mask&SHADOW_OCCLUSION_CULLING) + { + // is it in one of the shadow occluder volumes. + if (!_occluderList.empty()) + { + for(OccluderList::iterator itr=_occluderList.begin(); + itr!=_occluderList.end(); + ++itr) + { + if (itr->contains(bs)) return true; + } + } + } +#endif + return false; + } + + inline void pushCurrentMask() + { + _frustum.pushCurrentMask(); + + if (!_stateFrustumList.empty()) + { + for(StateFrustumList::iterator itr=_stateFrustumList.begin(); + itr!=_stateFrustumList.end(); + ++itr) + { + itr->second.pushCurrentMask(); + } + } + + +#ifdef COMPILE_WITH_SHADOW_OCCLUSION_CULLING + if (!_occluderList.empty()) + { + for(OccluderList::iterator itr=_occluderList.begin(); + itr!=_occluderList.end(); + ++itr) + { + itr->pushCurrentMask(); + } + } +#endif + } + + inline void popCurrentMask() + { + _frustum.popCurrentMask(); + + if (!_stateFrustumList.empty()) + { + for(StateFrustumList::iterator itr=_stateFrustumList.begin(); + itr!=_stateFrustumList.end(); + ++itr) + { + itr->second.popCurrentMask(); + } + } + +#ifdef COMPILE_WITH_SHADOW_OCCLUSION_CULLING + if (!_occluderList.empty()) + { + for(OccluderList::iterator itr=_occluderList.begin(); + itr!=_occluderList.end(); + ++itr) + { + itr->popCurrentMask(); + } + } +#endif + } + + inline void resetCullingMask() + { + _frustum.setResultMask(_frustum.getCurrentMask()); + } + + void disableAndPushOccludersCurrentMask(NodePath& nodePath); + + void popOccludersCurrentMask(NodePath& nodePath); + + static osg::Vec4 computePixelSizeVector(const Viewport& W, const Matrix& P, const Matrix& M); + + virtual ~CullingSet(); + + + protected: + + + Mask _mask; + Polytope _frustum; + StateFrustumList _stateFrustumList; + OccluderList _occluderList; + Vec4 _pixelSizeVector; + float _smallFeatureCullingPixelSize; + +}; + +} // end of namespace + +#endif diff --git a/libs/include/android/osg/DeleteHandler b/libs/include/android/osg/DeleteHandler new file mode 100755 index 0000000..7e2411c --- /dev/null +++ b/libs/include/android/osg/DeleteHandler @@ -0,0 +1,89 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_DELETEHANDLER +#define OSG_DELETEHANDLER 1 + +#include + +#include + +namespace osg { + + +/** Class for overriding the default delete behaviour so that users can implement their own object + * deletion schemes. + * This might be used to implement a protection scheme that avoids + * multiple threads deleting objects unintentionally. + * Note, the DeleteHandler cannot itself be reference counted, otherwise it + * would be responsible for deleting itself! + * A static auto_ptr<> is used internally in Referenced.cpp to manage the + * DeleteHandler's memory.*/ +class OSG_EXPORT DeleteHandler +{ + public: + + typedef std::pair FrameNumberObjectPair; + typedef std::list ObjectsToDeleteList; + + DeleteHandler(int numberOfFramesToRetainObjects=0); + + virtual ~DeleteHandler(); + + /** Set the number of frames to retain objects that have been requested for deletion. + * When set to zero objects are deleted immediately, by setting to 1 they are kept around for an extra frame etc. + * The ability to retain objects for several frames is useful to prevent premature deletion when objects + * are still being used by graphics threads that use double buffering of rendering data structures with + * non ref_ptr<> pointers to scene graph elements.*/ + void setNumFramesToRetainObjects(unsigned int numberOfFramesToRetainObjects) { _numFramesToRetainObjects = numberOfFramesToRetainObjects; } + + unsigned int getNumFramesToRetainObjects() const { return _numFramesToRetainObjects; } + + /** Set the current frame number so that subsequent deletes get tagged as associated with this frame.*/ + void setFrameNumber(unsigned int frameNumber) { _currentFrameNumber = frameNumber; } + + /** Get the current frame number.*/ + unsigned int getFrameNumber() const { return _currentFrameNumber; } + + inline void doDelete(const Referenced* object) { delete object; } + + /** Flush objects that are ready to be fully deleted.*/ + virtual void flush(); + + /** Flush all objects that the DeleteHandler holds. + * Note, this should only be called if there are no threads running with non ref_ptr<> pointers, such as graphics threads.*/ + virtual void flushAll(); + + /** Request the deletion of an object. + * Depending on users implementation of DeleteHandler, the delete of the object may occur + * straight away or be delayed until doDelete is called. + * The default implementation does a delete straight away.*/ + virtual void requestDelete(const osg::Referenced* object); + + protected: + + DeleteHandler(const DeleteHandler&): + _numFramesToRetainObjects(0), + _currentFrameNumber(0) {} + DeleteHandler operator = (const DeleteHandler&) { return *this; } + + unsigned int _numFramesToRetainObjects; + unsigned int _currentFrameNumber; + OpenThreads::Mutex _mutex; + ObjectsToDeleteList _objectsToDelete; + +}; + +} + +#endif diff --git a/libs/include/android/osg/Depth b/libs/include/android/osg/Depth new file mode 100755 index 0000000..aecbc6e --- /dev/null +++ b/libs/include/android/osg/Depth @@ -0,0 +1,112 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_DEPTH +#define OSG_DEPTH 1 + +#include + +namespace osg { + +/** Encapsulate OpenGL glDepthFunc/Mask/Range functions. +*/ +class OSG_EXPORT Depth : public StateAttribute +{ + public : + + + enum Function + { + NEVER = GL_NEVER, + LESS = GL_LESS, + EQUAL = GL_EQUAL, + LEQUAL = GL_LEQUAL, + GREATER = GL_GREATER, + NOTEQUAL = GL_NOTEQUAL, + GEQUAL = GL_GEQUAL, + ALWAYS = GL_ALWAYS + }; + + + Depth(Function func=LESS,double zNear=0.0, double zFar=1.0,bool writeMask=true); + + /** Copy constructor using CopyOp to manage deep vs shallow copy.*/ + Depth(const Depth& dp,const CopyOp& copyop=CopyOp::SHALLOW_COPY): + StateAttribute(dp,copyop), + _func(dp._func), + _zNear(dp._zNear), + _zFar(dp._zFar), + _depthWriteMask(dp._depthWriteMask) {} + + + META_StateAttribute(osg, Depth, DEPTH); + + /** return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs.*/ + virtual int compare(const StateAttribute& sa) const + { + // check the types are equal and then create the rhs variable + // used by the COMPARE_StateAttribute_Parameter macros below. + COMPARE_StateAttribute_Types(Depth,sa) + + // compare each parameter in turn against the rhs. + COMPARE_StateAttribute_Parameter(_func) + COMPARE_StateAttribute_Parameter(_depthWriteMask) + COMPARE_StateAttribute_Parameter(_zNear) + COMPARE_StateAttribute_Parameter(_zFar) + + return 0; // passed all the above comparison macros, must be equal. + } + + virtual bool getModeUsage(StateAttribute::ModeUsage& usage) const + { + usage.usesMode(GL_DEPTH_TEST); + return true; + } + + inline void setFunction(Function func) { _func = func; } + inline Function getFunction() const { return _func; } + + + inline void setRange(double zNear, double zFar) + { + _zNear = zNear; + _zFar = zFar; + } + + inline void setZNear(double zNear) { _zNear=zNear; } + inline double getZNear() const { return _zNear; } + + inline void setZFar(double zFar) { _zFar=zFar; } + inline double getZFar() const { return _zFar; } + + inline void setWriteMask(bool mask) { _depthWriteMask = mask; } + inline bool getWriteMask() const { return _depthWriteMask; } + + + virtual void apply(State& state) const; + + protected: + + virtual ~Depth(); + + Function _func; + + double _zNear; + double _zFar; + + bool _depthWriteMask; +}; + +} + +#endif diff --git a/libs/include/android/osg/DisplaySettings b/libs/include/android/osg/DisplaySettings new file mode 100755 index 0000000..d7688d2 --- /dev/null +++ b/libs/include/android/osg/DisplaySettings @@ -0,0 +1,377 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_DisplaySettings +#define OSG_DisplaySettings 1 + +#include +#include +#include + +#include +#include + +namespace osg { + +// forward declare +class ArgumentParser; +class ApplicationUsage; + +/** DisplaySettings class for encapsulating what visuals are required and + * have been set up, and the status of stereo viewing.*/ +class OSG_EXPORT DisplaySettings : public osg::Referenced +{ + + public: + + /** Maintain a DisplaySettings singleton for objects to query at runtime.*/ + static ref_ptr& instance(); + + DisplaySettings(): + Referenced(true) + { + setDefaults(); + readEnvironmentalVariables(); + } + + DisplaySettings(ArgumentParser& arguments): + Referenced(true) + { + setDefaults(); + readEnvironmentalVariables(); + readCommandLine(arguments); + } + + DisplaySettings(const DisplaySettings& vs); + + + DisplaySettings& operator = (const DisplaySettings& vs); + + void setDisplaySettings(const DisplaySettings& vs); + + void merge(const DisplaySettings& vs); + + void setDefaults(); + + /** read the environmental variables.*/ + void readEnvironmentalVariables(); + + /** read the commandline arguments.*/ + void readCommandLine(ArgumentParser& arguments); + + + enum DisplayType + { + MONITOR, + POWERWALL, + REALITY_CENTER, + HEAD_MOUNTED_DISPLAY + }; + + void setDisplayType(DisplayType type) { _displayType = type; } + + DisplayType getDisplayType() const { return _displayType; } + + + void setStereo(bool on) { _stereo = on; } + bool getStereo() const { return _stereo; } + + enum StereoMode + { + QUAD_BUFFER, + ANAGLYPHIC, + HORIZONTAL_SPLIT, + VERTICAL_SPLIT, + LEFT_EYE, + RIGHT_EYE, + HORIZONTAL_INTERLACE, + VERTICAL_INTERLACE, + CHECKERBOARD + }; + + void setStereoMode(StereoMode mode) { _stereoMode = mode; } + StereoMode getStereoMode() const { return _stereoMode; } + + void setEyeSeparation(float eyeSeparation) { _eyeSeparation = eyeSeparation; } + float getEyeSeparation() const { return _eyeSeparation; } + + enum SplitStereoHorizontalEyeMapping + { + LEFT_EYE_LEFT_VIEWPORT, + LEFT_EYE_RIGHT_VIEWPORT + }; + + void setSplitStereoHorizontalEyeMapping(SplitStereoHorizontalEyeMapping m) { _splitStereoHorizontalEyeMapping = m; } + SplitStereoHorizontalEyeMapping getSplitStereoHorizontalEyeMapping() const { return _splitStereoHorizontalEyeMapping; } + + void setSplitStereoHorizontalSeparation(int s) { _splitStereoHorizontalSeparation = s; } + int getSplitStereoHorizontalSeparation() const { return _splitStereoHorizontalSeparation; } + + enum SplitStereoVerticalEyeMapping + { + LEFT_EYE_TOP_VIEWPORT, + LEFT_EYE_BOTTOM_VIEWPORT + }; + + void setSplitStereoVerticalEyeMapping(SplitStereoVerticalEyeMapping m) { _splitStereoVerticalEyeMapping = m; } + SplitStereoVerticalEyeMapping getSplitStereoVerticalEyeMapping() const { return _splitStereoVerticalEyeMapping; } + + void setSplitStereoVerticalSeparation(int s) { _splitStereoVerticalSeparation = s; } + int getSplitStereoVerticalSeparation() const { return _splitStereoVerticalSeparation; } + + void setSplitStereoAutoAdjustAspectRatio(bool flag) { _splitStereoAutoAdjustAspectRatio=flag; } + bool getSplitStereoAutoAdjustAspectRatio() const { return _splitStereoAutoAdjustAspectRatio; } + + + void setScreenWidth(float width) { _screenWidth = width; } + float getScreenWidth() const { return _screenWidth; } + + void setScreenHeight(float height) { _screenHeight = height; } + float getScreenHeight() const { return _screenHeight; } + + void setScreenDistance(float distance) { _screenDistance = distance; } + float getScreenDistance() const { return _screenDistance; } + + + + void setDoubleBuffer(bool flag) { _doubleBuffer = flag; } + bool getDoubleBuffer() const { return _doubleBuffer; } + + + void setRGB(bool flag) { _RGB = flag; } + bool getRGB() const { return _RGB; } + + + void setDepthBuffer(bool flag) { _depthBuffer = flag; } + bool getDepthBuffer() const { return _depthBuffer; } + + + void setMinimumNumAlphaBits(unsigned int bits) { _minimumNumberAlphaBits = bits; } + unsigned int getMinimumNumAlphaBits() const { return _minimumNumberAlphaBits; } + bool getAlphaBuffer() const { return _minimumNumberAlphaBits!=0; } + + void setMinimumNumStencilBits(unsigned int bits) { _minimumNumberStencilBits = bits; } + unsigned int getMinimumNumStencilBits() const { return _minimumNumberStencilBits; } + bool getStencilBuffer() const { return _minimumNumberStencilBits!=0; } + + void setMinimumNumAccumBits(unsigned int red, unsigned int green, unsigned int blue, unsigned int alpha); + unsigned int getMinimumNumAccumRedBits() const { return _minimumNumberAccumRedBits; } + unsigned int getMinimumNumAccumGreenBits() const { return _minimumNumberAccumGreenBits; } + unsigned int getMinimumNumAccumBlueBits() const { return _minimumNumberAccumBlueBits; } + unsigned int getMinimumNumAccumAlphaBits() const { return _minimumNumberAccumAlphaBits; } + bool getAccumBuffer() const { return (_minimumNumberAccumRedBits+_minimumNumberAccumGreenBits+_minimumNumberAccumBlueBits+_minimumNumberAccumAlphaBits)!=0; } + + + void setMaxNumberOfGraphicsContexts(unsigned int num); + unsigned int getMaxNumberOfGraphicsContexts() const; + + void setNumMultiSamples(unsigned int samples) { _numMultiSamples = samples; } + unsigned int getNumMultiSamples() const { return _numMultiSamples; } + bool getMultiSamples() const { return _numMultiSamples!=0; } + + void setCompileContextsHint(bool useCompileContexts) { _compileContextsHint = useCompileContexts; } + bool getCompileContextsHint() const { return _compileContextsHint; } + + void setSerializeDrawDispatch(bool serializeDrawDispatch) { _serializeDrawDispatch = serializeDrawDispatch; } + bool getSerializeDrawDispatch() const { return _serializeDrawDispatch; } + + + void setUseSceneViewForStereoHint(bool hint) { _useSceneViewForStereoHint = hint; } + bool getUseSceneViewForStereoHint() const { return _useSceneViewForStereoHint; } + + + /** Set the hint for the total number of threads in the DatbasePager set up, inclusive of the number of http dedicated threads.*/ + void setNumOfDatabaseThreadsHint(unsigned int numThreads) { _numDatabaseThreadsHint = numThreads; } + + /** Get the hint for total number of threads in the DatbasePager set up, inclusive of the number of http dedicated threads.*/ + unsigned int getNumOfDatabaseThreadsHint() const { return _numDatabaseThreadsHint; } + + /** Set the hint for number of threads in the DatbasePager to dedicate to reading http requests.*/ + void setNumOfHttpDatabaseThreadsHint(unsigned int numThreads) { _numHttpDatabaseThreadsHint = numThreads; } + + /** Get the hint for number of threads in the DatbasePager dedicated to reading http requests.*/ + unsigned int getNumOfHttpDatabaseThreadsHint() const { return _numHttpDatabaseThreadsHint; } + + void setApplication(const std::string& application) { _application = application; } + const std::string& getApplication() { return _application; } + + + void setMaxTexturePoolSize(unsigned int size) { _maxTexturePoolSize = size; } + unsigned int getMaxTexturePoolSize() const { return _maxTexturePoolSize; } + + void setMaxBufferObjectPoolSize(unsigned int size) { _maxBufferObjectPoolSize = size; } + unsigned int getMaxBufferObjectPoolSize() const { return _maxBufferObjectPoolSize; } + + /** + Methods used to set and get defaults for Cameras implicit buffer attachments. + For more info: See description of Camera::setImplicitBufferAttachment method + + DisplaySettings implicit buffer attachment selection defaults to: DEPTH and COLOR + for both primary (Render) FBO and seconday Multisample (Resolve) FBO + ie: IMPLICT_DEPTH_BUFFER_ATTACHMENT | IMPLICIT_COLOR_BUFFER_ATTACHMENT + **/ + enum ImplicitBufferAttachment + { + IMPLICIT_DEPTH_BUFFER_ATTACHMENT = (1 << 0), + IMPLICIT_STENCIL_BUFFER_ATTACHMENT = (1 << 1), + IMPLICIT_COLOR_BUFFER_ATTACHMENT = (1 << 2), + DEFAULT_IMPLICIT_BUFFER_ATTACHMENT = IMPLICIT_COLOR_BUFFER_ATTACHMENT | IMPLICIT_DEPTH_BUFFER_ATTACHMENT + }; + + typedef int ImplicitBufferAttachmentMask; + + void setImplicitBufferAttachmentMask(ImplicitBufferAttachmentMask renderMask = DisplaySettings::DEFAULT_IMPLICIT_BUFFER_ATTACHMENT, ImplicitBufferAttachmentMask resolveMask = DisplaySettings::DEFAULT_IMPLICIT_BUFFER_ATTACHMENT ) + { + _implicitBufferAttachmentRenderMask = renderMask; + _implicitBufferAttachmentResolveMask = resolveMask; + } + + void setImplicitBufferAttachmentRenderMask(ImplicitBufferAttachmentMask implicitBufferAttachmentRenderMask) + { + _implicitBufferAttachmentRenderMask = implicitBufferAttachmentRenderMask; + } + + void setImplicitBufferAttachmentResolveMask(ImplicitBufferAttachmentMask implicitBufferAttachmentResolveMask) + { + _implicitBufferAttachmentResolveMask = implicitBufferAttachmentResolveMask; + } + + /** Get mask selecting default implict buffer attachments for Cameras primary FBOs. */ + ImplicitBufferAttachmentMask getImplicitBufferAttachmentRenderMask() const { return _implicitBufferAttachmentRenderMask; } + + /** Get mask selecting default implict buffer attachments for Cameras secondary MULTISAMPLE FBOs. */ + ImplicitBufferAttachmentMask getImplicitBufferAttachmentResolveMask() const { return _implicitBufferAttachmentResolveMask;} + + enum SwapMethod + { + SWAP_DEFAULT, // Leave swap method at default returned by choose Pixel Format. + SWAP_EXCHANGE, // Flip front / back buffer. + SWAP_COPY, // Copy back to front buffer. + SWAP_UNDEFINED // Move back to front buffer leaving contents of back buffer undefined. + }; + + /** Select preferred swap method */ + void setSwapMethod( SwapMethod swapMethod ) { _swapMethod = swapMethod; } + + /** Get preferred swap method */ + SwapMethod getSwapMethod( void ) { return _swapMethod; } + + /** Set the hint of which OpenGL version to attempt to create a graphics context for.*/ + void setGLContextVersion(const std::string& version) { _glContextVersion = version; } + + /** Get the hint of which OpenGL version to attempt to create a graphics context for.*/ + const std::string getGLContextVersion() const { return _glContextVersion; } + + /** Set the hint of the flags to use in when creating graphic contexts.*/ + void setGLContextFlags(unsigned int flags) { _glContextFlags = flags; } + + /** Get the hint of the flags to use in when creating graphic contexts.*/ + unsigned int getGLContextFlags() const { return _glContextFlags; } + + /** Set the hint of the profile mask to use in when creating graphic contexts.*/ + void setGLContextProfileMask(unsigned int mask) { _glContextProfileMask = mask; } + + /** Get the hint of the profile mask to use in when creating graphic contexts.*/ + unsigned int getGLContextProfileMask() const { return _glContextProfileMask; } + + + void setKeystoneHint(bool enabled) { _keystoneHint = enabled; } + bool getKeystoneHint() const { return _keystoneHint; } + + typedef std::vector FileNames; + void setKeystoneFileNames(const FileNames& filenames) { _keystoneFileNames = filenames; } + FileNames& getKeystoneFileNames() { return _keystoneFileNames; } + const FileNames& getKeystoneFileNames() const { return _keystoneFileNames; } + + typedef std::vector< osg::ref_ptr > Objects; + void setKeystones(const Objects& objects) { _keystones = objects; } + Objects& getKeystones() { return _keystones; } + const Objects& getKeystones() const { return _keystones; } + + + /** helper function for computing the left eye projection matrix.*/ + virtual osg::Matrixd computeLeftEyeProjectionImplementation(const osg::Matrixd& projection) const; + + /** helper function for computing the left eye view matrix.*/ + virtual osg::Matrixd computeLeftEyeViewImplementation(const osg::Matrixd& view, double eyeSeperationScale=1.0) const; + + /** helper function for computing the right eye view matrix.*/ + virtual osg::Matrixd computeRightEyeProjectionImplementation(const osg::Matrixd& projection) const; + + /** helper function for computing the right eye view matrix.*/ + virtual osg::Matrixd computeRightEyeViewImplementation(const osg::Matrixd& view, double eyeSeperationScale=1.0) const; + + protected: + + virtual ~DisplaySettings(); + + + DisplayType _displayType; + bool _stereo; + StereoMode _stereoMode; + float _eyeSeparation; + float _screenWidth; + float _screenHeight; + float _screenDistance; + + SplitStereoHorizontalEyeMapping _splitStereoHorizontalEyeMapping; + int _splitStereoHorizontalSeparation; + SplitStereoVerticalEyeMapping _splitStereoVerticalEyeMapping; + int _splitStereoVerticalSeparation; + bool _splitStereoAutoAdjustAspectRatio; + + bool _doubleBuffer; + bool _RGB; + bool _depthBuffer; + unsigned int _minimumNumberAlphaBits; + unsigned int _minimumNumberStencilBits; + unsigned int _minimumNumberAccumRedBits; + unsigned int _minimumNumberAccumGreenBits; + unsigned int _minimumNumberAccumBlueBits; + unsigned int _minimumNumberAccumAlphaBits; + + unsigned int _maxNumOfGraphicsContexts; + + unsigned int _numMultiSamples; + + bool _compileContextsHint; + bool _serializeDrawDispatch; + bool _useSceneViewForStereoHint; + + unsigned int _numDatabaseThreadsHint; + unsigned int _numHttpDatabaseThreadsHint; + + std::string _application; + + unsigned int _maxTexturePoolSize; + unsigned int _maxBufferObjectPoolSize; + + ImplicitBufferAttachmentMask _implicitBufferAttachmentRenderMask; + ImplicitBufferAttachmentMask _implicitBufferAttachmentResolveMask; + + std::string _glContextVersion; + unsigned int _glContextFlags; + unsigned int _glContextProfileMask; + + SwapMethod _swapMethod; + + + bool _keystoneHint; + FileNames _keystoneFileNames; + Objects _keystones; + +}; + +} + +# endif diff --git a/libs/include/android/osg/DrawPixels b/libs/include/android/osg/DrawPixels new file mode 100755 index 0000000..14c66b4 --- /dev/null +++ b/libs/include/android/osg/DrawPixels @@ -0,0 +1,80 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_DRAWPIXELS +#define OSG_DRAWPIXELS 1 + +#include +#include +#include + +namespace osg { + +/** DrawPixels is an osg::Drawable subclass which encapsulates the drawing of + * images using glDrawPixels.*/ +class OSG_EXPORT DrawPixels : public Drawable +{ + public: + + DrawPixels(); + + /** Copy constructor using CopyOp to manage deep vs shallow copy.*/ + DrawPixels(const DrawPixels& drawimage,const CopyOp& copyop=CopyOp::SHALLOW_COPY); + + virtual Object* cloneType() const { return new DrawPixels(); } + + virtual Object* clone(const CopyOp& copyop) const { return new DrawPixels(*this,copyop); } + + virtual bool isSameKindAs(const Object* obj) const { return dynamic_cast(obj)!=NULL; } + + virtual const char* libraryName() const { return "osg"; } + virtual const char* className() const { return "DrawPixels"; } + + + void setPosition(const osg::Vec3& position); + + osg::Vec3& getPosition() { return _position; } + const osg::Vec3& getPosition() const { return _position; } + + void setImage(osg::Image* image) { _image = image; } + + osg::Image* getImage() { return _image.get(); } + const osg::Image* getImage() const { return _image.get(); } + + void setUseSubImage(bool useSubImage) { _useSubImage=useSubImage; } + bool getUseSubImage() const { return _useSubImage; } + + void setSubImageDimensions(unsigned int offsetX,unsigned int offsetY,unsigned int width,unsigned int height); + void getSubImageDimensions(unsigned int& offsetX,unsigned int& offsetY,unsigned int& width,unsigned int& height) const; + + virtual void drawImplementation(RenderInfo& renderInfo) const; + + virtual BoundingBox computeBound() const; + + protected: + + DrawPixels& operator = (const DrawPixels&) { return *this;} + + virtual ~DrawPixels(); + + Vec3 _position; + ref_ptr _image; + + bool _useSubImage; + unsigned int _offsetX, _offsetY, _width, _height; + +}; + +} + +#endif diff --git a/libs/include/android/osg/Drawable b/libs/include/android/osg/Drawable new file mode 100755 index 0000000..13cee3d --- /dev/null +++ b/libs/include/android/osg/Drawable @@ -0,0 +1,920 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_DRAWABLE +#define OSG_DRAWABLE 1 + +#include +#include +#include +#include +#include + + +#ifndef GL_NV_occlusion_query + + #define GL_OCCLUSION_TEST_HP 0x8165 + #define GL_OCCLUSION_TEST_RESULT_HP 0x8166 + #define GL_PIXEL_COUNTER_BITS_NV 0x8864 + #define GL_CURRENT_OCCLUSION_QUERY_ID_NV 0x8865 + #define GL_PIXEL_COUNT_NV 0x8866 + #define GL_PIXEL_COUNT_AVAILABLE_NV 0x8867 + +#endif + +#ifndef GL_ARB_occlusion_query + + #define GL_SAMPLES_PASSED_ARB 0x8914 + #define GL_QUERY_COUNTER_BITS_ARB 0x8864 + #define GL_CURRENT_QUERY_ARB 0x8865 + #define GL_QUERY_RESULT_ARB 0x8866 + #define GL_QUERY_RESULT_AVAILABLE_ARB 0x8867 + +#endif + + +#ifndef GL_TIME_ELAPSED + #define GL_TIME_ELAPSED 0x88BF + #define GL_TIMESTAMP 0x8E28 +#endif + +#ifndef GL_QUERY_RESULT + #define GL_QUERY_RESULT 0x8866 + #define GL_QUERY_RESULT_AVAILABLE 0x8867 +#endif + + +#if !defined(GL_EXT_timer_query) && !defined(OSG_GL3_AVAILABLE) + #ifdef _WIN32 + typedef __int64 GLint64EXT; + typedef unsigned __int64 GLuint64EXT; + #else + typedef long long int GLint64EXT; + typedef unsigned long long int GLuint64EXT; + #endif +#endif + + +namespace osg { + + +class Vec2f; +class Vec3f; +class Vec4f; +class Vec4ub; +class Geometry; +class NodeVisitor; +class ArrayDispatchers; + +// this is defined to alter the way display lists are compiled inside the +// the draw method, it has been found that the NVidia drivers fail completely +// to optimize COMPILE_AND_EXECUTE in fact make it go slower than for no display +// lists, but optimize a separate COMPILE very well?! Define it as default +// the use of a separate COMPILE, then glCallList rather than use COMPILE_AND_EXECUTE. + +#define USE_SEPARATE_COMPILE_AND_EXECUTE + +/** Pure virtual base class for drawable geometry. In OSG, everything that can + * be rendered is implemented as a class derived from \c Drawable. The + * \c Drawable class contains no drawing primitives, since these are provided + * by subclasses such as \c osg::Geometry. + *

Notice that a \c Drawable is not a \c Node, and therefore it cannot be + * directly added to a scene graph. Instead, Drawables are attached to + * Geodes, which are scene graph nodes. + *

The OpenGL state that must be used when rendering a \c Drawable is + * represented by a \c StateSet. Since a \c Drawable has a reference + * (\c osg::ref_ptr) to a \c StateSet, StateSets can be shared between + * different Drawables. In fact, sharing StateSets is a good + * way to improve performance, since this allows OSG to reduce the number of + * expensive changes in the OpenGL state. + *

Finally, Drawables can also be shared between different + * Geodes, so that the same geometry (loaded to memory just once) can + * be used in different parts of the scene graph. +*/ +class OSG_EXPORT Drawable : public Object +{ + public: + + static unsigned int s_numberDrawablesReusedLastInLastFrame; + static unsigned int s_numberNewDrawablesInLastFrame; + static unsigned int s_numberDeletedDrawablesInLastFrame; + + Drawable(); + + /** Copy constructor using CopyOp to manage deep vs shallow copy.*/ + Drawable(const Drawable& drawable,const CopyOp& copyop=CopyOp::SHALLOW_COPY); + + virtual bool isSameKindAs(const Object* obj) const { return dynamic_cast(obj)!=NULL; } + virtual const char* libraryName() const { return "osg"; } + virtual const char* className() const { return "Drawable"; } + + /** Convert 'this' into a Geometry pointer if Drawable is a Geometry, otherwise return 0. + * Equivalent to dynamic_cast(this).*/ + virtual Geometry* asGeometry() { return 0; } + + /** Convert 'const this' into a const Geometry pointer if Drawable is a Geometry, otherwise return 0. + * Equivalent to dynamic_cast(this).*/ + virtual const Geometry* asGeometry() const { return 0; } + + + /** Compute the DataVariance based on an assessment of callback etc.*/ + virtual void computeDataVariance(); + + + /** A vector of osg::Node pointers which is used to store the parent(s) of drawable.*/ + typedef std::vector ParentList; + + /** Get the parent list of drawable. */ + inline const ParentList& getParents() const { return _parents; } + + /** Get the a copy of parent list of node. A copy is returned to + * prevent modification of the parent list.*/ + inline ParentList getParents() { return _parents; } + + /** Get a single parent of Drawable. + * @param i index of the parent to get. + * @return the parent i. + */ + inline Node* getParent(unsigned int i) { return _parents[i]; } + /** Get a single const parent of Drawable. + * @param i index of the parent to get. + * @return the parent i. + */ + inline const Node* getParent(unsigned int i) const { return _parents[i]; } + + /** + * Get the number of parents of node. + * @return the number of parents of this node. + */ + inline unsigned int getNumParents() const { return static_cast(_parents.size()); } + + /** Get the list of matrices that transform this node from local coordinates to world coordinates. + * The optional Node* haltTraversalAtNode allows the user to prevent traversal beyond a specifed node. */ + MatrixList getWorldMatrices(const osg::Node* haltTraversalAtNode=0) const; + + + /** Set the StateSet attached to the Drawable. + Previously attached StateSet are automatically unreferenced on + assignment of a new drawstate.*/ + void setStateSet(StateSet* stateset); + + /** Get the attached StateSet.*/ + inline StateSet* getStateSet() { return _stateset.get();} + + /** Get the attached const StateSet.*/ + inline const StateSet* getStateSet() const { return _stateset.get();} + + /** Get the attached const StateSet, + * if one is not already attached create one, + * attach it to the drawable and return a pointer to it.*/ + StateSet* getOrCreateStateSet(); + + + /** Set the initial bounding volume to use when computing the overall bounding volume.*/ + void setInitialBound(const osg::BoundingBox& bbox) { _initialBound = bbox; dirtyBound(); } + + /** Set the initial bounding volume to use when computing the overall bounding volume.*/ + const BoundingBox& getInitialBound() const { return _initialBound; } + + /** Dirty the bounding box, forcing a computeBound() on the next call + * to getBound(). Should be called in the internal geometry of the Drawable + * is modified.*/ + void dirtyBound(); + + /** Get BoundingBox of Drawable. + * If the BoundingBox is not up to date then its updated via an internal call to computeBond(). + */ + inline const BoundingBox& getBound() const + { + if(!_boundingBoxComputed) + { + _boundingBox = _initialBound; + if (_computeBoundCallback.valid()) + _boundingBox.expandBy(_computeBoundCallback->computeBound(*this)); + else + _boundingBox.expandBy(computeBound()); + + _boundingBoxComputed = true; + } + return _boundingBox; + } + + + /** Compute the bounding box around Drawables's geometry.*/ + virtual BoundingBox computeBound() const; + + /** Callback to allow users to override the default computation of bounding volume. */ + struct ComputeBoundingBoxCallback : public osg::Object + { + ComputeBoundingBoxCallback() {} + + ComputeBoundingBoxCallback(const ComputeBoundingBoxCallback&,const CopyOp&) {} + + META_Object(osg,ComputeBoundingBoxCallback); + + virtual BoundingBox computeBound(const osg::Drawable&) const { return BoundingBox(); } + }; + + /** Set the compute bound callback to override the default computeBound.*/ + void setComputeBoundingBoxCallback(ComputeBoundingBoxCallback* callback) { _computeBoundCallback = callback; } + + /** Get the compute bound callback.*/ + ComputeBoundingBoxCallback* getComputeBoundingBoxCallback() { return _computeBoundCallback.get(); } + + /** Get the const compute bound callback.*/ + const ComputeBoundingBoxCallback* getComputeBoundingBoxCallback() const { return _computeBoundCallback.get(); } + + + /** Set the Shape of the \c Drawable. The shape can be used to + * speed up collision detection or as a guide for procedural + * geometry generation. + * @see osg::Shape. + */ + inline void setShape(Shape* shape) { _shape = shape; } + + /** Get the Shape of the Drawable.*/ + inline Shape* getShape() { return _shape.get(); } + + /** Get the const Shape of the const Drawable.*/ + inline const Shape* getShape() const { return _shape.get(); } + + + + /** Set the drawable so that it can or cannot be used in conjunction with OpenGL + * display lists. When set to true, calls to Drawable::setUseDisplayList, + * whereas when set to false, no display lists can be created and calls + * to setUseDisplayList are ignored, and a warning is produced. The latter + * is typically used to guard against the switching on of display lists + * on objects with dynamic internal data such as continuous Level of Detail + * algorithms.*/ + void setSupportsDisplayList(bool flag); + + /** Get whether display lists are supported for this drawable instance.*/ + inline bool getSupportsDisplayList() const { return _supportsDisplayList; } + + + /** When set to true, force the draw method to use OpenGL Display List for rendering. + If false, rendering directly. If the display list has not been compiled + already, the next call to draw will automatically create the display list.*/ + void setUseDisplayList(bool flag); + + /** Return whether OpenGL display lists are being used for rendering.*/ + inline bool getUseDisplayList() const { return _useDisplayList; } + + /** Return OpenGL display list for specified contextID. */ + inline GLuint& getDisplayList(unsigned int contextID) const { return _globjList[contextID]; } + + /** When set to true, ignore the setUseDisplayList() settings, and hints to the drawImplementation + method to use OpenGL vertex buffer objects for rendering.*/ + virtual void setUseVertexBufferObjects(bool flag); + + /** Return whether OpenGL vertex buffer objects should be used when supported by OpenGL driver.*/ + inline bool getUseVertexBufferObjects() const { return _useVertexBufferObjects; } + + + /** Force a recompile on next draw() of any OpenGL display list associated with this geoset.*/ + virtual void dirtyDisplayList(); + + + /** Return the estimated size of GLObjects (display lists/vertex buffer objects) that are associated with this drawable. + * This size is used a hint for reuse of deleted display lists/vertex buffer objects. */ + virtual unsigned int getGLObjectSizeHint() const { return 0; } + + + + /** Draw OpenGL primitives. + * If the \c Drawable has \c _useDisplayList set to \c true, then use + * an OpenGL display list, automatically compiling one if required. + * Otherwise, call \c drawImplementation(). + * @note This method should \e not be overridden in subclasses, as it + * manages the optional display list (notice this is not even + * \c virtual). Subclasses should override + * \c drawImplementation() instead. + */ + inline void draw(RenderInfo& renderInfo) const; + + /** Immediately compile this \c Drawable into an OpenGL Display List/VertexBufferObjects. + * @note Operation is ignored if \c _useDisplayList is \c false or VertexBufferObjects are not used. + */ + virtual void compileGLObjects(RenderInfo& renderInfo) const; + + /** Set whether to use a mutex to ensure ref() and unref() are thread safe.*/ + virtual void setThreadSafeRefUnref(bool threadSafe); + + /** Resize any per context GLObject buffers to specified size. */ + virtual void resizeGLObjectBuffers(unsigned int maxSize); + + /** If State is non-zero, this function releases OpenGL objects for + * the specified graphics context. Otherwise, releases OpenGL objects + * for all graphics contexts. */ + virtual void releaseGLObjects(State* state=0) const; + + struct UpdateCallback : public virtual osg::Object + { + UpdateCallback() {} + + UpdateCallback(const UpdateCallback&,const CopyOp&) {} + + META_Object(osg,UpdateCallback); + + /** do customized update code.*/ + virtual void update(osg::NodeVisitor*, osg::Drawable*) {} + }; + + /** Set the UpdateCallback which allows users to attach customize the updating of an object during the update traversal. */ + virtual void setUpdateCallback(UpdateCallback* ac); + + /** Get the non const UpdateCallback.*/ + UpdateCallback* getUpdateCallback() { return _updateCallback.get(); } + + /** Get the const UpdateCallback.*/ + const UpdateCallback* getUpdateCallback() const { return _updateCallback.get(); } + + /** Return whether this Drawable has update callbacks associated with it, and therefore must be traversed.*/ + bool requiresUpdateTraversal() const { return _updateCallback.valid() || (_stateset.valid() && _stateset->requiresUpdateTraversal()); } + + + struct EventCallback : public virtual osg::Object + { + EventCallback() {} + + EventCallback(const EventCallback&,const CopyOp&) {} + + META_Object(osg,EventCallback); + + /** do customized Event code. */ + virtual void event(osg::NodeVisitor*, osg::Drawable*) {} + }; + + /** Set the EventCallback which allows users to attach customize the updating of an object during the Event traversal.*/ + virtual void setEventCallback(EventCallback* ac); + + /** Get the non const EventCallback.*/ + EventCallback* getEventCallback() { return _eventCallback.get(); } + + /** Get the const EventCallback.*/ + const EventCallback* getEventCallback() const { return _eventCallback.get(); } + + /** Return whether this Drawable has event callbacks associated with it, and therefore must be traversed.*/ + bool requiresEventTraversal() const { return _eventCallback.valid() || (_stateset.valid() && _stateset->requiresEventTraversal()); } + + + struct CullCallback : public virtual osg::Object + { + CullCallback() {} + + CullCallback(const CullCallback&,const CopyOp&) {} + + META_Object(osg,CullCallback); + + /** deprecated.*/ + virtual bool cull(osg::NodeVisitor*, osg::Drawable*, osg::State*) const { return false; } + + /** do customized cull code, return true if drawable should be culled.*/ + virtual bool cull(osg::NodeVisitor* nv, osg::Drawable* drawable, osg::RenderInfo* renderInfo) const { return cull(nv, drawable, renderInfo? renderInfo->getState():0); } + }; + + /** Set the CullCallback which allows users to customize the culling of Drawable during the cull traversal.*/ + virtual void setCullCallback(CullCallback* cc) { _cullCallback=cc; } + + /** Get the non const CullCallback.*/ + CullCallback* getCullCallback() { return _cullCallback.get(); } + + /** Get the const CullCallback.*/ + const CullCallback* getCullCallback() const { return _cullCallback.get(); } + + + + + /** Callback attached to an Drawable which allows the users to customize the drawing of an exist Drawable object. + * The draw callback is implement as a replacement to the Drawable's own drawImplementation() method, if the + * the user intends to decorate the existing draw code then simple call the drawable->drawImplementation() from + * with the callbacks drawImplementation() method. This allows the users to do both pre and post callbacks + * without fuss and can even disable the inner draw if required.*/ + struct DrawCallback : public virtual osg::Object + { + DrawCallback() {} + + DrawCallback(const DrawCallback&,const CopyOp&) {} + + META_Object(osg,DrawCallback); + + /** do customized draw code.*/ + virtual void drawImplementation(osg::RenderInfo& /*renderInfo*/,const osg::Drawable* /*drawable*/) const {} + }; + + /** Set the DrawCallback which allows users to attach customize the drawing of existing Drawable object.*/ + virtual void setDrawCallback(DrawCallback* dc) { _drawCallback=dc; dirtyDisplayList(); } + + /** Get the non const DrawCallback.*/ + DrawCallback* getDrawCallback() { return _drawCallback.get(); } + + /** Get the const DrawCallback.*/ + const DrawCallback* getDrawCallback() const { return _drawCallback.get(); } + + /** drawImplementation(RenderInfo&) is a pure virtual method for the actual implementation of OpenGL drawing calls, such as vertex arrays and primitives, that + * must be implemented in concrete subclasses of the Drawable base class, examples include osg::Geometry and osg::ShapeDrawable. + * drawImplementation(RenderInfo&) is called from the draw(RenderInfo&) method, with the draw method handling management of OpenGL display lists, + * and drawImplementation(RenderInfo&) handling the actual drawing itself. + * @param renderInfo The osg::RenderInfo object that encapsulates the current rendering information including the osg::State OpenGL state for the current graphics context. */ + virtual void drawImplementation(RenderInfo& renderInfo) const = 0; + + + /** Return a OpenGL display list handle a newly generated or reused from display list cache. */ + static GLuint generateDisplayList(unsigned int contextID, unsigned int sizeHint = 0); + + /** Set the minimum number of display lists to retain in the deleted display list cache. */ + static void setMinimumNumberOfDisplayListsToRetainInCache(unsigned int minimum); + + /** Get the minimum number of display lists to retain in the deleted display list cache. */ + static unsigned int getMinimumNumberOfDisplayListsToRetainInCache(); + + /** Use deleteDisplayList instead of glDeleteList to allow + * OpenGL display list to be cached until they can be deleted + * by the OpenGL context in which they were created, specified + * by contextID.*/ + static void deleteDisplayList(unsigned int contextID,GLuint globj, unsigned int sizeHint = 0); + + /** Flush all the cached display list which need to be deleted + * in the OpenGL context related to contextID.*/ + static void flushAllDeletedDisplayLists(unsigned int contextID); + + /** Flush all the cached display list which need to be deleted + * in the OpenGL context related to contextID. + * Note, unlike flush no OpenGL calls are made, instead the handles are all removed. + * this call is useful for when an OpenGL context has been destroyed. */ + static void discardAllDeletedDisplayLists(unsigned int contextID); + + /** Flush the cached display list which need to be deleted + * in the OpenGL context related to contextID.*/ + static void flushDeletedDisplayLists(unsigned int contextID,double& availableTime); + + typedef unsigned int AttributeType; + + enum AttributeTypes + { + VERTICES = 0, + WEIGHTS = 1, + NORMALS = 2, + COLORS = 3, + SECONDARY_COLORS = 4, + FOG_COORDS = 5, + ATTRIBUTE_6 = 6, + ATTRIBUTE_7 = 7, + TEXTURE_COORDS = 8, + TEXTURE_COORDS_0 = TEXTURE_COORDS, + TEXTURE_COORDS_1 = TEXTURE_COORDS_0+1, + TEXTURE_COORDS_2 = TEXTURE_COORDS_0+2, + TEXTURE_COORDS_3 = TEXTURE_COORDS_0+3, + TEXTURE_COORDS_4 = TEXTURE_COORDS_0+4, + TEXTURE_COORDS_5 = TEXTURE_COORDS_0+5, + TEXTURE_COORDS_6 = TEXTURE_COORDS_0+6, + TEXTURE_COORDS_7 = TEXTURE_COORDS_0+7 + // only eight texture coord examples provided here, but underlying code can handle any no of texture units, + // simply co them as (TEXTURE_COORDS_0+unit). + }; + + class AttributeFunctor + { + public: + virtual ~AttributeFunctor() {} + + virtual void apply(AttributeType,unsigned int,GLbyte*) {} + virtual void apply(AttributeType,unsigned int,GLshort*) {} + virtual void apply(AttributeType,unsigned int,GLint*) {} + + virtual void apply(AttributeType,unsigned int,GLubyte*) {} + virtual void apply(AttributeType,unsigned int,GLushort*) {} + virtual void apply(AttributeType,unsigned int,GLuint*) {} + + virtual void apply(AttributeType,unsigned int,float*) {} + virtual void apply(AttributeType,unsigned int,Vec2*) {} + virtual void apply(AttributeType,unsigned int,Vec3*) {} + virtual void apply(AttributeType,unsigned int,Vec4*) {} + virtual void apply(AttributeType,unsigned int,Vec4ub*) {} + + virtual void apply(AttributeType,unsigned int,double*) {} + virtual void apply(AttributeType,unsigned int,Vec2d*) {} + virtual void apply(AttributeType,unsigned int,Vec3d*) {} + virtual void apply(AttributeType,unsigned int,Vec4d*) {} + }; + + + /** Return true if the Drawable subclass supports accept(AttributeFunctor&).*/ + virtual bool supports(const AttributeFunctor&) const { return false; } + + /** accept an AttributeFunctor and call its methods to tell it about the internal attributes that this Drawable has. + * return true if functor handled by drawable, + * return false on failure of drawable to generate functor calls.*/ + virtual void accept(AttributeFunctor&) {} + + + class ConstAttributeFunctor + { + public: + + virtual ~ConstAttributeFunctor() {} + + virtual void apply(AttributeType,unsigned int,const GLbyte*) {} + virtual void apply(AttributeType,unsigned int,const GLshort*) {} + virtual void apply(AttributeType,unsigned int,const GLint*) {} + + virtual void apply(AttributeType,unsigned int,const GLubyte*) {} + virtual void apply(AttributeType,unsigned int,const GLushort*) {} + virtual void apply(AttributeType,unsigned int,const GLuint*) {} + + virtual void apply(AttributeType,unsigned int,const float*) {} + virtual void apply(AttributeType,unsigned int,const Vec2*) {} + virtual void apply(AttributeType,unsigned int,const Vec3*) {} + virtual void apply(AttributeType,unsigned int,const Vec4*) {} + virtual void apply(AttributeType,unsigned int,const Vec4ub*) {} + + virtual void apply(AttributeType,unsigned int,const double*) {} + virtual void apply(AttributeType,unsigned int,const Vec2d*) {} + virtual void apply(AttributeType,unsigned int,const Vec3d*) {} + virtual void apply(AttributeType,unsigned int,const Vec4d*) {} + }; + + /** Return true if the Drawable subclass supports accept(ConstAttributeFunctor&).*/ + virtual bool supports(const ConstAttributeFunctor&) const { return false; } + + /** Accept an AttributeFunctor and call its methods to tell it about the internal attributes that this Drawable has. + * return true if functor handled by drawable, + * return false on failure of drawable to generate functor calls.*/ + virtual void accept(ConstAttributeFunctor&) const {} + + + + /** Return true if the Drawable subclass supports accept(PrimitiveFunctor&).*/ + virtual bool supports(const PrimitiveFunctor&) const { return false; } + + /** Accept a PrimitiveFunctor and call its methods to tell it about the internal primitives that this Drawable has. + * return true if functor handled by drawable, return false on failure of drawable to generate functor calls. + * Note, PrimtiveFunctor only provides const access of the primitives, as primitives may be procedurally generated + * so one cannot modify it.*/ + virtual void accept(PrimitiveFunctor&) const {} + + /** Return true if the Drawable subclass supports accept(PrimitiveIndexFunctor&).*/ + virtual bool supports(const PrimitiveIndexFunctor&) const { return false; } + + /** Accept a PrimitiveIndexFunctor and call its methods to tell it about the internal primitives that this Drawable has. + * return true if functor handled by drawable, return false on failure of drawable to generate functor calls. + * Note, PrimtiveIndexFunctor only provide const access of the primitives, as primitives may be procedurally generated + * so one cannot modify it.*/ + virtual void accept(PrimitiveIndexFunctor&) const {} + + + /** Extensions class which encapsulates the querying of extensions and + * associated function pointers, and provide convenience wrappers to + * check for the extensions or use the associated functions.*/ + class OSG_EXPORT Extensions : public osg::Referenced + { + public: + Extensions(unsigned int contextID); + + Extensions(const Extensions& rhs); + + void lowestCommonDenominator(const Extensions& rhs); + + void setupGLExtensions(unsigned int contextID); + + void setVertexProgramSupported(bool flag) { _isVertexProgramSupported=flag; } + bool isVertexProgramSupported() const { return _isVertexProgramSupported; } + + void setSecondaryColorSupported(bool flag) { _isSecondaryColorSupported=flag; } + bool isSecondaryColorSupported() const { return _isSecondaryColorSupported; } + + void setFogCoordSupported(bool flag) { _isFogCoordSupported=flag; } + bool isFogCoordSupported() const { return _isFogCoordSupported; } + + void setMultiTexSupported(bool flag) { _isMultiTexSupported=flag; } + bool isMultiTexSupported() const { return _isMultiTexSupported; } + + void setOcclusionQuerySupported(bool flag) { _isOcclusionQuerySupported=flag; } + bool isOcclusionQuerySupported() const { return _isOcclusionQuerySupported; } + + void setARBOcclusionQuerySupported(bool flag) { _isARBOcclusionQuerySupported=flag; } + bool isARBOcclusionQuerySupported() const { return _isARBOcclusionQuerySupported; } + + void setTimerQuerySupported(bool flag) { _isTimerQuerySupported = flag; } + bool isTimerQuerySupported() const { return _isTimerQuerySupported; } + void setARBTimerQuerySupported(bool flag) { _isARBTimerQuerySupported = flag; } + bool isARBTimerQuerySupported() const { return _isARBTimerQuerySupported; } + void glSecondaryColor3ubv(const GLubyte* coord) const; + void glSecondaryColor3fv(const GLfloat* coord) const; + + void glFogCoordfv(const GLfloat* coord) const; + + void glMultiTexCoord1f(GLenum target,GLfloat coord) const; + void glMultiTexCoord2fv(GLenum target,const GLfloat* coord) const; + void glMultiTexCoord3fv(GLenum target,const GLfloat* coord) const; + void glMultiTexCoord4fv(GLenum target,const GLfloat* coord) const; + + void glMultiTexCoord1d(GLenum target,GLdouble coord) const; + void glMultiTexCoord2dv(GLenum target,const GLdouble* coord) const; + void glMultiTexCoord3dv(GLenum target,const GLdouble* coord) const; + void glMultiTexCoord4dv(GLenum target,const GLdouble* coord) const; + + void glVertexAttrib1s(unsigned int index, GLshort s) const; + void glVertexAttrib1f(unsigned int index, GLfloat f) const; + void glVertexAttrib1d(unsigned int index, GLdouble f) const; + void glVertexAttrib2fv(unsigned int index, const GLfloat * v) const; + void glVertexAttrib3fv(unsigned int index, const GLfloat * v) const; + void glVertexAttrib4fv(unsigned int index, const GLfloat * v) const; + void glVertexAttrib2dv(unsigned int index, const GLdouble * v) const; + void glVertexAttrib3dv(unsigned int index, const GLdouble * v) const; + void glVertexAttrib4dv(unsigned int index, const GLdouble * v) const; + void glVertexAttrib4ubv(unsigned int index, const GLubyte * v) const; + void glVertexAttrib4Nubv(unsigned int index, const GLubyte * v) const; + + + void glGenBuffers (GLsizei n, GLuint *buffers) const; + void glBindBuffer (GLenum target, GLuint buffer) const; + void glBufferData (GLenum target, GLsizeiptrARB size, const GLvoid *data, GLenum usage) const; + void glBufferSubData (GLenum target, GLintptrARB offset, GLsizeiptrARB size, const GLvoid *data) const; + void glDeleteBuffers (GLsizei n, const GLuint *buffers) const; + GLboolean glIsBuffer (GLuint buffer) const; + void glGetBufferSubData (GLenum target, GLintptrARB offset, GLsizeiptrARB size, GLvoid *data) const; + GLvoid* glMapBuffer (GLenum target, GLenum access) const; + GLboolean glUnmapBuffer (GLenum target) const; + void glGetBufferParameteriv (GLenum target, GLenum pname, GLint *params) const; + void glGetBufferPointerv (GLenum target, GLenum pname, GLvoid* *params) const; + + + void glGenOcclusionQueries( GLsizei n, GLuint *ids ) const; + void glDeleteOcclusionQueries( GLsizei n, const GLuint *ids ) const; + GLboolean glIsOcclusionQuery( GLuint id ) const; + void glBeginOcclusionQuery( GLuint id ) const; + void glEndOcclusionQuery() const; + void glGetOcclusionQueryiv( GLuint id, GLenum pname, GLint *params ) const; + void glGetOcclusionQueryuiv( GLuint id, GLenum pname, GLuint *params ) const; + + void glGetQueryiv(GLenum target, GLenum pname, GLint *params) const; + void glGenQueries(GLsizei n, GLuint *ids) const; + void glBeginQuery(GLenum target, GLuint id) const; + void glEndQuery(GLenum target) const; + void glQueryCounter(GLuint id, GLenum target) const; + GLboolean glIsQuery(GLuint id) const; + void glDeleteQueries(GLsizei n, const GLuint *ids) const; + void glGetQueryObjectiv(GLuint id, GLenum pname, GLint *params) const; + void glGetQueryObjectuiv(GLuint id, GLenum pname, GLuint *params) const; + void glGetQueryObjectui64v(GLuint id, GLenum pname, GLuint64EXT *params) const; + void glGetInteger64v(GLenum pname, GLint64EXT *params) const; + + protected: + + friend class ArrayDispatchers; + + typedef void (GL_APIENTRY * FogCoordProc) (const GLfloat* coord); + + typedef void (GL_APIENTRY * VertexAttrib1sProc) (GLuint index, GLshort s); + typedef void (GL_APIENTRY * VertexAttrib1fProc) (GLuint index, GLfloat f); + typedef void (GL_APIENTRY * VertexAttrib1dProc) (GLuint index, GLdouble f); + typedef void (GL_APIENTRY * VertexAttribfvProc) (GLuint index, const GLfloat * v); + typedef void (GL_APIENTRY * VertexAttribdvProc) (GLuint index, const GLdouble * v); + typedef void (GL_APIENTRY * VertexAttribubvProc) (GLuint index, const GLubyte * v); + + typedef void (GL_APIENTRY * SecondaryColor3ubvProc) (const GLubyte* coord); + typedef void (GL_APIENTRY * SecondaryColor3fvProc) (const GLfloat* coord); + + typedef void (GL_APIENTRY * MultiTexCoord1fProc) (GLenum target,GLfloat coord); + typedef void (GL_APIENTRY * MultiTexCoordfvProc) (GLenum target,const GLfloat* coord); + typedef void (GL_APIENTRY * MultiTexCoord1dProc) (GLenum target,GLdouble coord); + typedef void (GL_APIENTRY * MultiTexCoorddvProc) (GLenum target,const GLdouble* coord); + + + typedef void (GL_APIENTRY * GenBuffersProc) (GLsizei n, GLuint *buffers); + typedef void (GL_APIENTRY * BindBufferProc) (GLenum target, GLuint buffer); + typedef void (GL_APIENTRY * BufferDataProc) (GLenum target, GLsizeiptrARB size, const GLvoid *data, GLenum usage); + typedef void (GL_APIENTRY * BufferSubDataProc) (GLenum target, GLintptrARB offset, GLsizeiptrARB size, const GLvoid *data); + typedef void (GL_APIENTRY * DeleteBuffersProc) (GLsizei n, const GLuint *buffers); + typedef GLboolean (GL_APIENTRY * IsBufferProc) (GLuint buffer); + typedef void (GL_APIENTRY * GetBufferSubDataProc) (GLenum target, GLintptrARB offset, GLsizeiptrARB size, GLvoid *data); + typedef GLvoid* (GL_APIENTRY * MapBufferProc) (GLenum target, GLenum access); + typedef GLboolean (GL_APIENTRY * UnmapBufferProc) (GLenum target); + typedef void (GL_APIENTRY * GetBufferParameterivProc) (GLenum target, GLenum pname, GLint *params); + typedef void (GL_APIENTRY * GetBufferPointervProc) (GLenum target, GLenum pname, GLvoid* *params); + + typedef void (GL_APIENTRY * GenOcclusionQueriesProc) ( GLsizei n, GLuint *ids ); + typedef void (GL_APIENTRY * DeleteOcclusionQueriesProc) ( GLsizei n, const GLuint *ids ); + typedef GLboolean (GL_APIENTRY * IsOcclusionQueryProc) ( GLuint id ); + typedef void (GL_APIENTRY * BeginOcclusionQueryProc) ( GLuint id ); + typedef void (GL_APIENTRY * EndOcclusionQueryProc) (); + typedef void (GL_APIENTRY * GetOcclusionQueryivProc) ( GLuint id, GLenum pname, GLint *params ); + typedef void (GL_APIENTRY * GetOcclusionQueryuivProc) ( GLuint id, GLenum pname, GLuint *params ); + typedef void (GL_APIENTRY * GetOcclusionQueryui64vProc) ( GLuint id, GLenum pname, GLuint64EXT *params ); + + typedef void (GL_APIENTRY *GenQueriesProc) (GLsizei n, GLuint *ids); + typedef void (GL_APIENTRY *DeleteQueriesProc) (GLsizei n, const GLuint *ids); + typedef GLboolean (GL_APIENTRY *IsQueryProc) (GLuint id); + typedef void (GL_APIENTRY *BeginQueryProc) (GLenum target, GLuint id); + typedef void (GL_APIENTRY *EndQueryProc) (GLenum target); + typedef void (GL_APIENTRY *QueryCounterProc)(GLuint id, GLenum target); + typedef void (GL_APIENTRY *GetQueryivProc) (GLenum target, GLenum pname, GLint *params); + typedef void (GL_APIENTRY *GetQueryObjectivProc) (GLuint id, GLenum pname, GLint *params); + typedef void (GL_APIENTRY *GetQueryObjectuivProc) (GLuint id, GLenum pname, GLuint *params); + typedef void (GL_APIENTRY *GetQueryObjectui64vProc) (GLuint id, GLenum pname, GLuint64EXT *params); + typedef void (GL_APIENTRY *GetInteger64vProc) (GLenum pname, GLint64EXT *params); + + ~Extensions() {} + + bool _isVertexProgramSupported; + bool _isSecondaryColorSupported; + bool _isFogCoordSupported; + bool _isMultiTexSupported; + bool _isOcclusionQuerySupported; + bool _isARBOcclusionQuerySupported; + bool _isTimerQuerySupported; + bool _isARBTimerQuerySupported; + + FogCoordProc _glFogCoordfv; + + SecondaryColor3ubvProc _glSecondaryColor3ubv; + SecondaryColor3fvProc _glSecondaryColor3fv; + + VertexAttrib1sProc _glVertexAttrib1s; + VertexAttrib1fProc _glVertexAttrib1f; + VertexAttrib1dProc _glVertexAttrib1d; + VertexAttribfvProc _glVertexAttrib1fv; + VertexAttribfvProc _glVertexAttrib2fv; + VertexAttribfvProc _glVertexAttrib3fv; + VertexAttribfvProc _glVertexAttrib4fv; + VertexAttribdvProc _glVertexAttrib2dv; + VertexAttribdvProc _glVertexAttrib3dv; + VertexAttribdvProc _glVertexAttrib4dv; + VertexAttribubvProc _glVertexAttrib4ubv; + VertexAttribubvProc _glVertexAttrib4Nubv; + + MultiTexCoord1fProc _glMultiTexCoord1f; + MultiTexCoordfvProc _glMultiTexCoord1fv; + MultiTexCoordfvProc _glMultiTexCoord2fv; + MultiTexCoordfvProc _glMultiTexCoord3fv; + MultiTexCoordfvProc _glMultiTexCoord4fv; + MultiTexCoord1dProc _glMultiTexCoord1d; + MultiTexCoorddvProc _glMultiTexCoord2dv; + MultiTexCoorddvProc _glMultiTexCoord3dv; + MultiTexCoorddvProc _glMultiTexCoord4dv; + + GenBuffersProc _glGenBuffers; + BindBufferProc _glBindBuffer; + BufferDataProc _glBufferData; + BufferSubDataProc _glBufferSubData; + DeleteBuffersProc _glDeleteBuffers; + IsBufferProc _glIsBuffer; + GetBufferSubDataProc _glGetBufferSubData; + MapBufferProc _glMapBuffer; + UnmapBufferProc _glUnmapBuffer; + GetBufferParameterivProc _glGetBufferParameteriv; + GetBufferPointervProc _glGetBufferPointerv; + + GenOcclusionQueriesProc _glGenOcclusionQueries; + DeleteOcclusionQueriesProc _glDeleteOcclusionQueries; + IsOcclusionQueryProc _glIsOcclusionQuery; + BeginOcclusionQueryProc _glBeginOcclusionQuery; + EndOcclusionQueryProc _glEndOcclusionQuery; + GetOcclusionQueryivProc _glGetOcclusionQueryiv; + GetOcclusionQueryuivProc _glGetOcclusionQueryuiv; + + GenQueriesProc _gl_gen_queries_arb; + DeleteQueriesProc _gl_delete_queries_arb; + IsQueryProc _gl_is_query_arb; + BeginQueryProc _gl_begin_query_arb; + EndQueryProc _gl_end_query_arb; + QueryCounterProc _glQueryCounter; + GetQueryivProc _gl_get_queryiv_arb; + GetQueryObjectivProc _gl_get_query_objectiv_arb; + GetQueryObjectuivProc _gl_get_query_objectuiv_arb; + GetQueryObjectui64vProc _gl_get_query_objectui64v; + GetInteger64vProc _glGetInteger64v; + + }; + + /** Function to call to get the extension of a specified context. + * If the Extension object for that context has not yet been created + * and the 'createIfNotInitalized' flag been set to false then returns NULL. + * If 'createIfNotInitalized' is true then the Extensions object is + * automatically created. However, in this case the extension object is + * only created with the graphics context associated with ContextID..*/ + static Extensions* getExtensions(unsigned int contextID,bool createIfNotInitalized); + + /** setExtensions allows users to override the extensions across graphics contexts. + * typically used when you have different extensions supported across graphics pipes + * but need to ensure that they all use the same low common denominator extensions.*/ + static void setExtensions(unsigned int contextID,Extensions* extensions); + + + protected: + + Drawable& operator = (const Drawable&) { return *this;} + + virtual ~Drawable(); + + + /** set the bounding box .*/ + void setBound(const BoundingBox& bb) const; + + void addParent(osg::Node* node); + void removeParent(osg::Node* node); + + ParentList _parents; + friend class Node; + friend class Geode; + friend class StateSet; + + ref_ptr _stateset; + + BoundingBox _initialBound; + ref_ptr _computeBoundCallback; + mutable BoundingBox _boundingBox; + mutable bool _boundingBoxComputed; + + ref_ptr _shape; + + bool _supportsDisplayList; + bool _useDisplayList; + bool _supportsVertexBufferObjects; + bool _useVertexBufferObjects; + + typedef osg::buffered_value GLObjectList; + mutable GLObjectList _globjList; + + ref_ptr _updateCallback; + unsigned int _numChildrenRequiringUpdateTraversal; + void setNumChildrenRequiringUpdateTraversal(unsigned int num); + unsigned int getNumChildrenRequiringUpdateTraversal() const { return _numChildrenRequiringUpdateTraversal; } + + ref_ptr _eventCallback; + unsigned int _numChildrenRequiringEventTraversal; + void setNumChildrenRequiringEventTraversal(unsigned int num); + unsigned int getNumChildrenRequiringEventTraversal() const { return _numChildrenRequiringEventTraversal; } + + ref_ptr _cullCallback; + ref_ptr _drawCallback; +}; + +inline void Drawable::draw(RenderInfo& renderInfo) const +{ +#ifdef OSG_GL_DISPLAYLISTS_AVAILABLE + if (_useDisplayList && !(_supportsVertexBufferObjects && _useVertexBufferObjects && renderInfo.getState()->isVertexBufferObjectSupported())) + { + // get the contextID (user defined ID of 0 upwards) for the + // current OpenGL context. + unsigned int contextID = renderInfo.getContextID(); + + // get the globj for the current contextID. + GLuint& globj = _globjList[contextID]; + + // call the globj if already set otherwise compile and execute. + if( globj != 0 ) + { + glCallList( globj ); + } + else if (_useDisplayList) + { +#ifdef USE_SEPARATE_COMPILE_AND_EXECUTE + globj = generateDisplayList(contextID, getGLObjectSizeHint()); + glNewList( globj, GL_COMPILE ); + if (_drawCallback.valid()) + _drawCallback->drawImplementation(renderInfo,this); + else + drawImplementation(renderInfo); + glEndList(); + + glCallList( globj); +#else + globj = generateDisplayList(contextID, getGLObjectSizeHint()); + glNewList( globj, GL_COMPILE_AND_EXECUTE ); + if (_drawCallback.valid()) + _drawCallback->drawImplementation(renderInfo,this); + else + drawImplementation(renderInfo); + glEndList(); +#endif + } + + return; + + } +#endif + + // draw object as nature intended.. + if (_drawCallback.valid()) + _drawCallback->drawImplementation(renderInfo,this); + else + drawImplementation(renderInfo); +} + + +} + +#endif diff --git a/libs/include/android/osg/Endian b/libs/include/android/osg/Endian new file mode 100755 index 0000000..b351558 --- /dev/null +++ b/libs/include/android/osg/Endian @@ -0,0 +1,88 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_ENDIAN +#define OSG_ENDIAN 1 + +#include + +namespace osg { + +enum Endian +{ + BigEndian, + LittleEndian +}; + +inline Endian getCpuByteOrder() +{ + union { + char big_endian_1[2]; + short is_it_really_1; + } u; + u.big_endian_1[0] = 0; + u.big_endian_1[1] = 1; + + if (u.is_it_really_1 == 1) + return BigEndian; + else + return LittleEndian; +} + +inline void swapBytes( char* in, unsigned int size ) +{ + char* start = in; + char* end = start+size-1; + while (start +void swapBytes(T& t) { swapBytes(reinterpret_cast(&t), sizeof(T)); } + +} + +#endif diff --git a/libs/include/android/osg/Export b/libs/include/android/osg/Export new file mode 100755 index 0000000..7fd42bf --- /dev/null +++ b/libs/include/android/osg/Export @@ -0,0 +1,72 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_EXPORT_ +#define OSG_EXPORT_ 1 + +#include +// define USE_DEPRECATED_API is used to include in API which is being fazed out +// if you can compile your apps with this turned off you are +// well placed for compatibility with future versions. +#define USE_DEPRECATED_API + +// disable VisualStudio warnings +#if defined(_MSC_VER) && defined(OSG_DISABLE_MSVC_WARNINGS) + #pragma warning( disable : 4244 ) + #pragma warning( disable : 4251 ) + #pragma warning( disable : 4275 ) + #pragma warning( disable : 4512 ) + #pragma warning( disable : 4267 ) + #pragma warning( disable : 4702 ) + #pragma warning( disable : 4511 ) +#endif + +#if defined(_MSC_VER) || defined(__CYGWIN__) || defined(__MINGW32__) || defined( __BCPLUSPLUS__) || defined( __MWERKS__) + # if defined( OSG_LIBRARY_STATIC ) + # define OSG_EXPORT + # elif defined( OSG_LIBRARY ) + # define OSG_EXPORT __declspec(dllexport) + # else + # define OSG_EXPORT __declspec(dllimport) + # endif +#else + # define OSG_EXPORT +#endif + +// set up define for whether member templates are supported by VisualStudio compilers. +#ifdef _MSC_VER +# if (_MSC_VER >= 1300) +# define __STL_MEMBER_TEMPLATES +# endif +#endif + +/* Define NULL pointer value */ + +#ifndef NULL + #ifdef __cplusplus + #define NULL 0 + #else + #define NULL ((void *)0) + #endif +#endif + +/** + +\namespace osg + +The core osg library provides the basic scene graph classes such as Nodes, +State and Drawables, and maths and general helper classes. +*/ + +#endif + diff --git a/libs/include/android/osg/Fog b/libs/include/android/osg/Fog new file mode 100755 index 0000000..abed4b1 --- /dev/null +++ b/libs/include/android/osg/Fog @@ -0,0 +1,146 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_FOG +#define OSG_FOG 1 + +#include +#include + +#ifndef GL_FOG_DISTANCE_MODE_NV + #define GL_FOG_DISTANCE_MODE_NV 0x855A +#endif +#ifndef GL_EYE_PLANE_ABSOLUTE_NV + #define GL_EYE_PLANE_ABSOLUTE_NV 0x855C +#endif +#ifndef GL_EYE_RADIAL_NV + #define GL_EYE_RADIAL_NV 0x855B +#endif + + +#ifndef GL_FOG_COORDINATE + #define GL_FOG_COORDINATE 0x8451 +#endif +#ifndef GL_FRAGMENT_DEPTH + #define GL_FRAGMENT_DEPTH 0x8452 +#endif + +#ifndef GL_FOG + #define GL_FOG 0x0B60 + #define GL_EXP 0x0800 + #define GL_EXP2 0x0801 +#endif + +#ifndef GL_FOG_HINT + #define GL_FOG_HINT 0x0C54 +#endif + +namespace osg { + + +/** Fog - encapsulates OpenGL fog state. */ +class OSG_EXPORT Fog : public StateAttribute +{ + public : + + Fog(); + + /** Copy constructor using CopyOp to manage deep vs shallow copy.*/ + Fog(const Fog& fog,const CopyOp& copyop=CopyOp::SHALLOW_COPY): + StateAttribute(fog,copyop), + _mode(fog._mode), + _density(fog._density), + _start(fog._start), + _end(fog._end), + _color(fog._color), + _fogCoordinateSource(fog._fogCoordinateSource), + _useRadialFog(fog._useRadialFog) {} + + META_StateAttribute(osg, Fog,FOG); + + /** return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs.*/ + virtual int compare(const StateAttribute& sa) const + { + // check the types are equal and then create the rhs variable + // used by the COMPARE_StateAttribute_Parameter macros below. + COMPARE_StateAttribute_Types(Fog,sa) + + // compare each parameter in turn against the rhs. + COMPARE_StateAttribute_Parameter(_mode) + COMPARE_StateAttribute_Parameter(_density) + COMPARE_StateAttribute_Parameter(_start) + COMPARE_StateAttribute_Parameter(_end) + COMPARE_StateAttribute_Parameter(_color) + COMPARE_StateAttribute_Parameter(_fogCoordinateSource) + COMPARE_StateAttribute_Parameter(_useRadialFog) + + return 0; // passed all the above comparison macros, must be equal. + } + + virtual bool getModeUsage(StateAttribute::ModeUsage& usage) const + { + usage.usesMode(GL_FOG); + return true; + } + + enum Mode { + LINEAR = GL_LINEAR, + EXP = GL_EXP, + EXP2 = GL_EXP2 + }; + + inline void setMode( Mode mode ) { _mode = mode; } + inline Mode getMode() const { return _mode; } + + inline void setDensity( float density ) { _density = density; } + inline float getDensity() const { return _density; } + + inline void setStart( float start ) { _start = start; } + inline float getStart() const { return _start; } + + inline void setEnd( float end ) { _end = end; } + inline float getEnd() const { return _end; } + + inline void setColor( const Vec4 &color ) { _color = color; } + inline const Vec4& getColor() const { return _color; } + + inline void setUseRadialFog( bool useRadialFog ) { _useRadialFog = useRadialFog; } + inline bool getUseRadialFog() const { return _useRadialFog; } + + enum FogCoordinateSource + { + FOG_COORDINATE = GL_FOG_COORDINATE, + FRAGMENT_DEPTH = GL_FRAGMENT_DEPTH + }; + + inline void setFogCoordinateSource(GLint source) { _fogCoordinateSource = source; } + inline GLint getFogCoordinateSource() const { return _fogCoordinateSource; } + + virtual void apply(State& state) const; + + protected : + + virtual ~Fog(); + + Mode _mode; + float _density; + float _start; + float _end; + Vec4 _color; + GLint _fogCoordinateSource; + bool _useRadialFog; +}; + +} + +#endif diff --git a/libs/include/android/osg/FragmentProgram b/libs/include/android/osg/FragmentProgram new file mode 100755 index 0000000..b4781c0 --- /dev/null +++ b/libs/include/android/osg/FragmentProgram @@ -0,0 +1,312 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_FRAGMENTPROGRAM +#define OSG_FRAGMENTPROGRAM 1 + +#include +#include +#include +#include + +#include +#include + +// if not defined by gl.h use the definition found in: +// http://oss.sgi.com/projects/ogl-sample/registry/ARB/fragment_program.txt +#ifndef GL_ARB_fragment_program +#define GL_FRAGMENT_PROGRAM_ARB 0x8804 +#define GL_PROGRAM_FORMAT_ASCII_ARB 0x8875 +#define GL_PROGRAM_LENGTH_ARB 0x8627 +#define GL_PROGRAM_FORMAT_ARB 0x8876 +#define GL_PROGRAM_BINDING_ARB 0x8677 +#define GL_PROGRAM_INSTRUCTIONS_ARB 0x88A0 +#define GL_MAX_PROGRAM_INSTRUCTIONS_ARB 0x88A1 +#define GL_PROGRAM_NATIVE_INSTRUCTIONS_ARB 0x88A2 +#define GL_MAX_PROGRAM_NATIVE_INSTRUCTIONS_ARB 0x88A3 +#define GL_PROGRAM_TEMPORARIES_ARB 0x88A4 +#define GL_MAX_PROGRAM_TEMPORARIES_ARB 0x88A5 +#define GL_PROGRAM_NATIVE_TEMPORARIES_ARB 0x88A6 +#define GL_MAX_PROGRAM_NATIVE_TEMPORARIES_ARB 0x88A7 +#define GL_PROGRAM_PARAMETERS_ARB 0x88A8 +#define GL_MAX_PROGRAM_PARAMETERS_ARB 0x88A9 +#define GL_PROGRAM_NATIVE_PARAMETERS_ARB 0x88AA +#define GL_MAX_PROGRAM_NATIVE_PARAMETERS_ARB 0x88AB +#define GL_PROGRAM_ATTRIBS_ARB 0x88AC +#define GL_MAX_PROGRAM_ATTRIBS_ARB 0x88AD +#define GL_PROGRAM_NATIVE_ATTRIBS_ARB 0x88AE +#define GL_MAX_PROGRAM_NATIVE_ATTRIBS_ARB 0x88AF +#define GL_MAX_PROGRAM_LOCAL_PARAMETERS_ARB 0x88B4 +#define GL_MAX_PROGRAM_ENV_PARAMETERS_ARB 0x88B5 +#define GL_PROGRAM_UNDER_NATIVE_LIMITS_ARB 0x88B6 +#define GL_PROGRAM_ALU_INSTRUCTIONS_ARB 0x8805 +#define GL_PROGRAM_TEX_INSTRUCTIONS_ARB 0x8806 +#define GL_PROGRAM_TEX_INDIRECTIONS_ARB 0x8807 +#define GL_PROGRAM_NATIVE_ALU_INSTRUCTIONS_ARB 0x8808 +#define GL_PROGRAM_NATIVE_TEX_INSTRUCTIONS_ARB 0x8809 +#define GL_PROGRAM_NATIVE_TEX_INDIRECTIONS_ARB 0x880A +#define GL_MAX_PROGRAM_ALU_INSTRUCTIONS_ARB 0x880B +#define GL_MAX_PROGRAM_TEX_INSTRUCTIONS_ARB 0x880C +#define GL_MAX_PROGRAM_TEX_INDIRECTIONS_ARB 0x880D +#define GL_MAX_PROGRAM_NATIVE_ALU_INSTRUCTIONS_ARB 0x880E +#define GL_MAX_PROGRAM_NATIVE_TEX_INSTRUCTIONS_ARB 0x880F +#define GL_MAX_PROGRAM_NATIVE_TEX_INDIRECTIONS_ARB 0x8810 +#define GL_PROGRAM_STRING_ARB 0x8628 +#define GL_PROGRAM_ERROR_POSITION_ARB 0x864B +#define GL_CURRENT_MATRIX_ARB 0x8641 +#define GL_TRANSPOSE_CURRENT_MATRIX_ARB 0x88B7 +#define GL_CURRENT_MATRIX_STACK_DEPTH_ARB 0x8640 +#define GL_MAX_PROGRAM_MATRICES_ARB 0x862F +#define GL_MAX_PROGRAM_MATRIX_STACK_DEPTH_ARB 0x862E +#define GL_MAX_TEXTURE_COORDS_ARB 0x8871 +#define GL_MAX_TEXTURE_IMAGE_UNITS_ARB 0x8872 +#define GL_PROGRAM_ERROR_STRING_ARB 0x8874 +#define GL_MATRIX0_ARB 0x88C0 +#define GL_MATRIX1_ARB 0x88C1 +#define GL_MATRIX2_ARB 0x88C2 +#define GL_MATRIX3_ARB 0x88C3 +#define GL_MATRIX4_ARB 0x88C4 +#define GL_MATRIX5_ARB 0x88C5 +#define GL_MATRIX6_ARB 0x88C6 +#define GL_MATRIX7_ARB 0x88C7 +#define GL_MATRIX8_ARB 0x88C8 +#define GL_MATRIX9_ARB 0x88C9 +#define GL_MATRIX10_ARB 0x88CA +#define GL_MATRIX11_ARB 0x88CB +#define GL_MATRIX12_ARB 0x88CC +#define GL_MATRIX13_ARB 0x88CD +#define GL_MATRIX14_ARB 0x88CE +#define GL_MATRIX15_ARB 0x88CF +#define GL_MATRIX16_ARB 0x88D0 +#define GL_MATRIX17_ARB 0x88D1 +#define GL_MATRIX18_ARB 0x88D2 +#define GL_MATRIX19_ARB 0x88D3 +#define GL_MATRIX20_ARB 0x88D4 +#define GL_MATRIX21_ARB 0x88D5 +#define GL_MATRIX22_ARB 0x88D6 +#define GL_MATRIX23_ARB 0x88D7 +#define GL_MATRIX24_ARB 0x88D8 +#define GL_MATRIX25_ARB 0x88D9 +#define GL_MATRIX26_ARB 0x88DA +#define GL_MATRIX27_ARB 0x88DB +#define GL_MATRIX28_ARB 0x88DC +#define GL_MATRIX29_ARB 0x88DD +#define GL_MATRIX30_ARB 0x88DE +#define GL_MATRIX31_ARB 0x88DF + +#endif + + +namespace osg { + + + +/** FragmentProgram - encapsulates the OpenGL ARB fragment program state.*/ +class OSG_EXPORT FragmentProgram : public StateAttribute +{ + public: + + FragmentProgram(); + + /** Copy constructor using CopyOp to manage deep vs shallow copy.*/ + FragmentProgram(const FragmentProgram& vp,const CopyOp& copyop=CopyOp::SHALLOW_COPY); + + META_StateAttribute(osg, FragmentProgram, FRAGMENTPROGRAM); + + /** return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs.*/ + virtual int compare(const osg::StateAttribute& sa) const + { + // check the types are equal and then create the rhs variable + // used by the COMPARE_StateAttribute_Parameter macros below. + COMPARE_StateAttribute_Types(FragmentProgram,sa) + + // compare each parameter in turn against the rhs. + COMPARE_StateAttribute_Parameter(_fragmentProgram) + + return 0; // passed all the above comparison macros, must be equal. + } + + virtual bool getModeUsage(StateAttribute::ModeUsage& usage) const + { + usage.usesMode(GL_FRAGMENT_PROGRAM_ARB); + return true; + } + + // data access methods. + + /** Get the handle to the fragment program id for the current context.*/ + inline GLuint& getFragmentProgramID(unsigned int contextID) const + { + return _fragmentProgramIDList[contextID]; + } + + + /** Set the fragment program using a C style string.*/ + inline void setFragmentProgram( const char* program ) + { + _fragmentProgram = program; + dirtyFragmentProgramObject(); + } + + /** Set the fragment program using C++ style string.*/ + inline void setFragmentProgram( const std::string& program ) + { + _fragmentProgram = program; + dirtyFragmentProgramObject(); + } + + /** Get the fragment program.*/ + inline const std::string& getFragmentProgram() const { return _fragmentProgram; } + + /** Set Program Parameters */ + inline void setProgramLocalParameter(const GLuint index, const Vec4& p) + { + _programLocalParameters[index] = p; + } + + typedef std::map LocalParamList; + + /** Set list of Program Parameters */ + inline void setLocalParameters(const LocalParamList& lpl) { _programLocalParameters = lpl; } + + /** Get list of Program Parameters */ + inline LocalParamList& getLocalParameters() { return _programLocalParameters; } + + /** Get const list of Program Parameters */ + inline const LocalParamList& getLocalParameters() const { return _programLocalParameters; } + + /** Matrix */ + inline void setMatrix(const GLenum mode, const Matrix& matrix) + { + _matrixList[mode] = matrix; + } + + typedef std::map MatrixList; + + /** Set list of Matrices */ + inline void setMatrices(const MatrixList& matrices) { _matrixList = matrices; } + + /** Get list of Matrices */ + inline MatrixList& getMatrices() { return _matrixList; } + + /** Get list of Matrices */ + inline const MatrixList& getMatrices() const { return _matrixList; } + + + /** Force a recompile on next apply() of associated OpenGL vertex program objects.*/ + void dirtyFragmentProgramObject(); + + /** use deleteFragmentProgramObject instead of glDeletePrograms to allow + * OpenGL Fragment Program objects to be cached until they can be deleted + * by the OpenGL context in which they were created, specified + * by contextID.*/ + static void deleteFragmentProgramObject(unsigned int contextID,GLuint handle); + + /** flush all the cached fragment programs which need to be deleted + * in the OpenGL context related to contextID.*/ + static void flushDeletedFragmentProgramObjects(unsigned int contextID,double currentTime, double& availableTime); + + /** discard all the cached fragment programs which need to be deleted + * in the OpenGL context related to contextID. + * Note, unlike flush no OpenGL calls are made, instead the handles are all removed. + * this call is useful for when an OpenGL context has been destroyed. */ + static void discardDeletedFragmentProgramObjects(unsigned int contextID); + + virtual void apply(State& state) const; + + virtual void compileGLObjects(State& state) const { apply(state); } + + /** Resize any per context GLObject buffers to specified size. */ + virtual void resizeGLObjectBuffers(unsigned int maxSize); + + /** release an OpenGL objects in specified graphics context if State + object is passed, otherwise release OpenGL objects for all graphics context if + State object pointer == NULL.*/ + virtual void releaseGLObjects(State* state=0) const; + + /** Extensions class which encapsulates the querying of extensions and + * associated function pointers, and provide convenience wrappers to + * check for the extensions or use the associated functions.*/ + class OSG_EXPORT Extensions : public osg::Referenced + { + public: + Extensions(unsigned int contextID); + + Extensions(const Extensions& rhs); + + void lowestCommonDenominator(const Extensions& rhs); + + void setupGLExtensions(unsigned int contextID); + + void setFragmentProgramSupported(bool flag) { _isFragmentProgramSupported=flag; } + bool isFragmentProgramSupported() const { return _isFragmentProgramSupported; } + + void glBindProgram(GLenum target, GLuint id) const; + void glGenPrograms(GLsizei n, GLuint *programs) const; + void glDeletePrograms(GLsizei n, GLuint *programs) const; + void glProgramString(GLenum target, GLenum format, GLsizei len, const void *string) const; + void glProgramLocalParameter4fv(GLenum target, GLuint index, const GLfloat *params) const; + + protected: + + ~Extensions() {} + + bool _isFragmentProgramSupported; + + typedef void (GL_APIENTRY * BindProgramProc) (GLenum target, GLuint id); + typedef void (GL_APIENTRY * GenProgramsProc) (GLsizei n, GLuint *programs); + typedef void (GL_APIENTRY * DeleteProgramsProc) (GLsizei n, GLuint *programs); + typedef void (GL_APIENTRY * ProgramStringProc) (GLenum target, GLenum format, GLsizei len, const void *string); + typedef void (GL_APIENTRY * ProgramLocalParameter4fvProc) (GLenum target, GLuint index, const GLfloat *params); + + BindProgramProc _glBindProgram; + GenProgramsProc _glGenPrograms; + DeleteProgramsProc _glDeletePrograms; + ProgramStringProc _glProgramString; + ProgramLocalParameter4fvProc _glProgramLocalParameter4fv; + }; + + /** Function to call to get the extension of a specified context. + * If the Extension object for that context has not yet been created and the + * 'createIfNotInitalized' flag has been set to false then returns NULL. + * If 'createIfNotInitalized' is true then the Extensions object is + * automatically created. However, in this case the extension object will + * only be created with the graphics context associated with ContextID..*/ + static Extensions* getExtensions(unsigned int contextID,bool createIfNotInitalized); + + /** setExtensions allows users to override the extensions across graphics contexts. + * typically used when you have different extensions supported across graphics pipes + * but need to ensure that they all use the same low common denominator extensions.*/ + static void setExtensions(unsigned int contextID,Extensions* extensions); + + + protected: + + + virtual ~FragmentProgram(); + + typedef buffered_value FragmentProgramIDList; + mutable FragmentProgramIDList _fragmentProgramIDList; + + std::string _fragmentProgram; + + LocalParamList _programLocalParameters; + MatrixList _matrixList; +}; + + + +} + +#endif + diff --git a/libs/include/android/osg/FrameBufferObject b/libs/include/android/osg/FrameBufferObject new file mode 100755 index 0000000..344e7ad --- /dev/null +++ b/libs/include/android/osg/FrameBufferObject @@ -0,0 +1,505 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +// initial FBO support written by Marco Jez, June 2005. + +#ifndef OSG_FRAMEBUFFEROBJECT +#define OSG_FRAMEBUFFEROBJECT 1 + +#include +#include +#include +#include + +#ifndef GL_EXT_framebuffer_object +#define GL_EXT_framebuffer_object 1 +#define GL_FRAMEBUFFER_EXT 0x8D40 +#define GL_RENDERBUFFER_EXT 0x8D41 +// #define GL_STENCIL_INDEX_EXT 0x8D45 // removed in rev. #114 of the spec +#define GL_STENCIL_INDEX1_EXT 0x8D46 +#define GL_STENCIL_INDEX4_EXT 0x8D47 +#define GL_STENCIL_INDEX8_EXT 0x8D48 +#define GL_STENCIL_INDEX16_EXT 0x8D49 +#define GL_RENDERBUFFER_WIDTH_EXT 0x8D42 +#define GL_RENDERBUFFER_HEIGHT_EXT 0x8D43 +#define GL_RENDERBUFFER_INTERNAL_FORMAT_EXT 0x8D44 +#define GL_RENDERBUFFER_RED_SIZE_EXT 0x8D50 +#define GL_RENDERBUFFER_GREEN_SIZE_EXT 0x8D51 +#define GL_RENDERBUFFER_BLUE_SIZE_EXT 0x8D52 +#define GL_RENDERBUFFER_ALPHA_SIZE_EXT 0x8D53 +#define GL_RENDERBUFFER_DEPTH_SIZE_EXT 0x8D54 +#define GL_RENDERBUFFER_STENCIL_SIZE_EXT 0x8D55 +#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE_EXT 0x8CD0 +#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME_EXT 0x8CD1 +#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL_EXT 0x8CD2 +#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE_EXT 0x8CD3 +#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_3D_ZOFFSET_EXT 0x8CD4 +#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER_EXT 0x8CD4 +#define GL_COLOR_ATTACHMENT0_EXT 0x8CE0 +#define GL_COLOR_ATTACHMENT1_EXT 0x8CE1 +#define GL_COLOR_ATTACHMENT2_EXT 0x8CE2 +#define GL_COLOR_ATTACHMENT3_EXT 0x8CE3 +#define GL_COLOR_ATTACHMENT4_EXT 0x8CE4 +#define GL_COLOR_ATTACHMENT5_EXT 0x8CE5 +#define GL_COLOR_ATTACHMENT6_EXT 0x8CE6 +#define GL_COLOR_ATTACHMENT7_EXT 0x8CE7 +#define GL_COLOR_ATTACHMENT8_EXT 0x8CE8 +#define GL_COLOR_ATTACHMENT9_EXT 0x8CE9 +#define GL_COLOR_ATTACHMENT10_EXT 0x8CEA +#define GL_COLOR_ATTACHMENT11_EXT 0x8CEB +#define GL_COLOR_ATTACHMENT12_EXT 0x8CEC +#define GL_COLOR_ATTACHMENT13_EXT 0x8CED +#define GL_COLOR_ATTACHMENT14_EXT 0x8CEE +#define GL_COLOR_ATTACHMENT15_EXT 0x8CEF +#define GL_DEPTH_ATTACHMENT_EXT 0x8D00 +#define GL_STENCIL_ATTACHMENT_EXT 0x8D20 +#define GL_FRAMEBUFFER_COMPLETE_EXT 0x8CD5 +#define GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_EXT 0x8CD6 +#define GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_EXT 0x8CD7 +#define GL_FRAMEBUFFER_INCOMPLETE_DUPLICATE_ATTACHMENT_EXT 0x8CD8 +#define GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT 0x8CD9 +#define GL_FRAMEBUFFER_INCOMPLETE_FORMATS_EXT 0x8CDA +#define GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER_EXT 0x8CDB +#define GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER_EXT 0x8CDC +#define GL_FRAMEBUFFER_UNSUPPORTED_EXT 0x8CDD +#define GL_FRAMEBUFFER_BINDING_EXT 0x8CA6 +#define GL_RENDERBUFFER_BINDING_EXT 0x8CA7 +#define GL_MAX_COLOR_ATTACHMENTS_EXT 0x8CDF +#define GL_MAX_RENDERBUFFER_SIZE_EXT 0x84E8 +#define GL_INVALID_FRAMEBUFFER_OPERATION_EXT 0x0506 +#endif + +#ifndef GL_EXT_framebuffer_blit +#define GL_EXT_framebuffer_blit 1 +#define GL_DRAW_FRAMEBUFFER_BINDING_EXT 0x8CA6 +#define GL_READ_FRAMEBUFFER_EXT 0x8CA8 +#define GL_DRAW_FRAMEBUFFER_EXT 0x8CA9 +#define GL_READ_FRAMEBUFFER_BINDING_EXT 0x8CAA +#endif + +#ifndef GL_EXT_framebuffer_multisample +#define GL_EXT_framebuffer_multisample 1 +#define GL_RENDERBUFFER_SAMPLES_EXT 0x8CAB +#define GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_EXT 0x8D56 +#define GL_MAX_SAMPLES_EXT 0x8D57 +#endif + +#ifndef GL_MAX_SAMPLES_EXT +// Workaround for Centos 5 and other distros that define +// GL_EXT_framebuffer_multisample but not GL_MAX_SAMPLES_EXT +#define GL_MAX_SAMPLES_EXT 0x8D57 +#endif + +#ifndef GL_NV_framebuffer_multisample_coverage +#define GL_NV_framebuffer_multisample_coverage 1 +#define GL_RENDERBUFFER_COVERAGE_SAMPLES_NV 0x8CAB +#define GL_RENDERBUFFER_COLOR_SAMPLES_NV 0x8E10 +#define GL_MAX_MULTISAMPLE_COVERAGE_MODES_NV 0x8E11 +#define GL_MULTISAMPLE_COVERAGE_MODES_NV 0x8E12 +#endif + +#ifndef GL_EXT_packed_depth_stencil +#define GL_EXT_packed_depth_stencil 1 +#define GL_DEPTH_STENCIL_EXT 0x84F9 +#define GL_UNSIGNED_INT_24_8_EXT 0x84FA +#define GL_DEPTH24_STENCIL8_EXT 0x88F0 +#define GL_TEXTURE_STENCIL_SIZE_EXT 0x88F1 +#endif + +namespace osg +{ + +/************************************************************************** + * FBOExtensions + **************************************************************************/ + + class OSG_EXPORT FBOExtensions : public osg::Referenced + { + public: + typedef void GL_APIENTRY TglBindRenderbuffer(GLenum, GLuint); + typedef void GL_APIENTRY TglDeleteRenderbuffers(GLsizei n, const GLuint *renderbuffers); + typedef void GL_APIENTRY TglGenRenderbuffers(GLsizei, GLuint *); + typedef void GL_APIENTRY TglRenderbufferStorage(GLenum, GLenum, GLsizei, GLsizei); + typedef void GL_APIENTRY TglRenderbufferStorageMultisample(GLenum, GLsizei, GLenum, GLsizei, GLsizei); + typedef void GL_APIENTRY TglRenderbufferStorageMultisampleCoverageNV(GLenum, GLsizei, GLsizei, GLenum, GLsizei, GLsizei); + typedef void GL_APIENTRY TglBindFramebuffer(GLenum, GLuint); + typedef void GL_APIENTRY TglDeleteFramebuffers(GLsizei n, const GLuint *framebuffers); + typedef void GL_APIENTRY TglGenFramebuffers(GLsizei, GLuint *); + typedef GLenum GL_APIENTRY TglCheckFramebufferStatus(GLenum); + typedef void GL_APIENTRY TglFramebufferTexture1D(GLenum, GLenum, GLenum, GLuint, GLint); + typedef void GL_APIENTRY TglFramebufferTexture2D(GLenum, GLenum, GLenum, GLuint, GLint); + typedef void GL_APIENTRY TglFramebufferTexture3D(GLenum, GLenum, GLenum, GLuint, GLint, GLint); + typedef void GL_APIENTRY TglFramebufferTexture(GLenum, GLenum, GLint, GLint); + typedef void GL_APIENTRY TglFramebufferTextureLayer(GLenum, GLenum, GLuint, GLint, GLint); + typedef void GL_APIENTRY TglFramebufferRenderbuffer(GLenum, GLenum, GLenum, GLuint); + typedef void GL_APIENTRY TglGenerateMipmap(GLenum); + typedef void GL_APIENTRY TglBlitFramebuffer(GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLbitfield, GLenum); + typedef void GL_APIENTRY TglGetRenderbufferParameteriv(GLenum, GLenum, GLint*); + + TglBindRenderbuffer* glBindRenderbuffer; + TglGenRenderbuffers* glGenRenderbuffers; + TglDeleteRenderbuffers* glDeleteRenderbuffers; + TglRenderbufferStorage* glRenderbufferStorage; + TglRenderbufferStorageMultisample* glRenderbufferStorageMultisample; + TglRenderbufferStorageMultisampleCoverageNV* glRenderbufferStorageMultisampleCoverageNV; + TglBindFramebuffer* glBindFramebuffer; + TglDeleteFramebuffers* glDeleteFramebuffers; + TglGenFramebuffers* glGenFramebuffers; + TglCheckFramebufferStatus* glCheckFramebufferStatus; + TglFramebufferTexture1D* glFramebufferTexture1D; + TglFramebufferTexture2D* glFramebufferTexture2D; + TglFramebufferTexture3D* glFramebufferTexture3D; + TglFramebufferTexture* glFramebufferTexture; + TglFramebufferTextureLayer* glFramebufferTextureLayer; + TglFramebufferRenderbuffer* glFramebufferRenderbuffer; + TglGenerateMipmap* glGenerateMipmap; + TglBlitFramebuffer* glBlitFramebuffer; + TglGetRenderbufferParameteriv* glGetRenderbufferParameteriv; + + static FBOExtensions* instance(unsigned contextID, bool createIfNotInitalized); + + bool isSupported() const { return _supported; } + bool isMultisampleSupported() const { return glRenderbufferStorageMultisample != 0; } + bool isMultisampleCoverageSupported() const { return glRenderbufferStorageMultisampleCoverageNV != 0; } + bool isPackedDepthStencilSupported() const { return _packed_depth_stencil_supported; } + + protected: + FBOExtensions(unsigned int contextID); + + bool _supported; + bool _packed_depth_stencil_supported; + }; + +/************************************************************************** + * RenderBuffer + **************************************************************************/ + + class OSG_EXPORT RenderBuffer: public Object + { + public: + RenderBuffer(); + RenderBuffer(int width, int height, GLenum internalFormat, int samples=0, int colorSamples=0); + RenderBuffer(const RenderBuffer& copy, const CopyOp& copyop = CopyOp::SHALLOW_COPY); + + META_Object(osg, RenderBuffer); + + inline int getWidth() const; + inline int getHeight() const; + inline void setWidth(int w); + inline void setHeight(int h); + inline void setSize(int w, int h); + inline GLenum getInternalFormat() const; + inline void setInternalFormat(GLenum format); + inline int getSamples() const; + inline int getColorSamples() const; + inline void setSamples(int samples); + inline void setColorSamples(int colorSamples); + + GLuint getObjectID(unsigned int contextID, const FBOExtensions *ext) const; + inline int compare(const RenderBuffer &rb) const; + + /** Mark internal RenderBuffer for deletion. + * Deletion requests are queued until they can be executed + * in the proper GL context. */ + static void deleteRenderBuffer(unsigned int contextID, GLuint rb); + + /** flush all the cached RenderBuffers which need to be deleted + * in the OpenGL context related to contextID.*/ + static void flushDeletedRenderBuffers(unsigned int contextID,double currentTime, double& availableTime); + + /** discard all the cached RenderBuffers which need to be deleted in the OpenGL context related to contextID. + * Note, unlike flush no OpenGL calls are made, instead the handles are all removed. + * this call is useful for when an OpenGL context has been destroyed. */ + static void discardDeletedRenderBuffers(unsigned int contextID); + + static int getMaxSamples(unsigned int contextID, const FBOExtensions *ext); + + /** Resize any per context GLObject buffers to specified size. */ + virtual void resizeGLObjectBuffers(unsigned int maxSize); + + /** If State is non-zero, this function releases any associated OpenGL objects for + * the specified graphics context. Otherwise, releases OpenGL objexts + * for all graphics contexts. */ + virtual void releaseGLObjects(osg::State* = 0) const; + + protected: + virtual ~RenderBuffer(); + RenderBuffer &operator=(const RenderBuffer &) { return *this; } + + inline void dirtyAll() const; + + private: + mutable buffered_value _objectID; + mutable buffered_value _dirty; + + GLenum _internalFormat; + int _width; + int _height; + // "samples" in the framebuffer_multisample extension is equivalent to + // "coverageSamples" in the framebuffer_multisample_coverage extension. + int _samples; + int _colorSamples; + }; + + // INLINE METHODS + + inline int RenderBuffer::getWidth() const + { + return _width; + } + + inline int RenderBuffer::getHeight() const + { + return _height; + } + + inline void RenderBuffer::setWidth(int w) + { + _width = w; + dirtyAll(); + } + + inline void RenderBuffer::setHeight(int h) + { + _height = h; + dirtyAll(); + } + + inline void RenderBuffer::setSize(int w, int h) + { + _width = w; + _height = h; + dirtyAll(); + } + + inline GLenum RenderBuffer::getInternalFormat() const + { + return _internalFormat; + } + + inline void RenderBuffer::setInternalFormat(GLenum format) + { + _internalFormat = format; + dirtyAll(); + } + + inline int RenderBuffer::getSamples() const + { + return _samples; + } + + inline int RenderBuffer::getColorSamples() const + { + return _colorSamples; + } + + inline void RenderBuffer::setSamples(int samples) + { + _samples = samples; + dirtyAll(); + } + + inline void RenderBuffer::setColorSamples(int colorSamples) + { + _colorSamples = colorSamples; + dirtyAll(); + } + + inline void RenderBuffer::dirtyAll() const + { + _dirty.setAllElementsTo(1); + } + + inline int RenderBuffer::compare(const RenderBuffer &rb) const + { + if (&rb == this) return 0; + if (_internalFormat < rb._internalFormat) return -1; + if (_internalFormat > rb._internalFormat) return 1; + if (_width < rb._width) return -1; + if (_width > rb._width) return 1; + if (_height < rb._height) return -1; + if (_height > rb._height) return 1; + return 0; + } + +/************************************************************************** + * FrameBufferAttachement + **************************************************************************/ + class Texture1D; + class Texture2D; + class Texture2DMultisample; + class Texture3D; + class Texture2DArray; + class TextureCubeMap; + class TextureRectangle; + + class OSG_EXPORT FrameBufferAttachment + { + public: + FrameBufferAttachment(); + FrameBufferAttachment(const FrameBufferAttachment& copy); + + explicit FrameBufferAttachment(RenderBuffer* target); + explicit FrameBufferAttachment(Texture1D* target, unsigned int level = 0); + explicit FrameBufferAttachment(Texture2D* target, unsigned int level = 0); + explicit FrameBufferAttachment(Texture2DMultisample* target, unsigned int level = 0); + explicit FrameBufferAttachment(Texture3D* target, unsigned int zoffset, unsigned int level = 0); + explicit FrameBufferAttachment(Texture2DArray* target, unsigned int layer, unsigned int level = 0); + explicit FrameBufferAttachment(TextureCubeMap* target, unsigned int face, unsigned int level = 0); + explicit FrameBufferAttachment(TextureRectangle* target); + explicit FrameBufferAttachment(Camera::Attachment& attachment); + + ~FrameBufferAttachment(); + + FrameBufferAttachment&operator = (const FrameBufferAttachment& copy); + + bool isMultisample() const; + void createRequiredTexturesAndApplyGenerateMipMap(State& state, const FBOExtensions* ext) const; + void attach(State &state, GLenum target, GLenum attachment_point, const FBOExtensions* ext) const; + int compare(const FrameBufferAttachment &fa) const; + + RenderBuffer* getRenderBuffer(); + const RenderBuffer* getRenderBuffer() const; + + Texture* getTexture(); + const Texture* getTexture() const; + + unsigned int getCubeMapFace() const; + unsigned int getTextureLevel() const; + unsigned int getTexture3DZOffset() const; + unsigned int getTextureArrayLayer() const; + + private: + // use the Pimpl idiom to avoid dependency from + // all Texture* headers + struct Pimpl; + Pimpl* _ximpl; + }; + +/************************************************************************** + * FrameBufferObject + **************************************************************************/ + class OSG_EXPORT FrameBufferObject: public StateAttribute + { + public: + typedef std::map AttachmentMap; + typedef std::vector MultipleRenderingTargets; + + typedef Camera::BufferComponent BufferComponent; + + FrameBufferObject(); + FrameBufferObject(const FrameBufferObject& copy, const CopyOp& copyop = CopyOp::SHALLOW_COPY); + + META_StateAttribute(osg, FrameBufferObject, FRAME_BUFFER_OBJECT); + + inline const AttachmentMap& getAttachmentMap() const; + + + void setAttachment(BufferComponent attachment_point, const FrameBufferAttachment &attachment); + inline const FrameBufferAttachment& getAttachment(BufferComponent attachment_point) const; + inline bool hasAttachment(BufferComponent attachment_point) const; + + inline bool hasMultipleRenderingTargets() const { return !_drawBuffers.empty(); } + inline const MultipleRenderingTargets& getMultipleRenderingTargets() const { return _drawBuffers; } + + bool isMultisample() const; + + int compare(const StateAttribute &sa) const; + + void apply(State &state) const; + + inline GLuint getHandle(unsigned int contextID) const + { + return _fboID[contextID]; + } + + enum BindTarget + { + READ_FRAMEBUFFER = GL_READ_FRAMEBUFFER_EXT, + DRAW_FRAMEBUFFER = GL_DRAW_FRAMEBUFFER_EXT, + READ_DRAW_FRAMEBUFFER = GL_FRAMEBUFFER_EXT + }; + + /** Bind the FBO as either the read or draw target, or both. */ + void apply(State &state, BindTarget target) const; + + /** Mark internal FBO for deletion. + * Deletion requests are queued until they can be executed + * in the proper GL context. */ + static void deleteFrameBufferObject(unsigned int contextID, GLuint program); + + /** flush all the cached FBOs which need to be deleted + * in the OpenGL context related to contextID.*/ + static void flushDeletedFrameBufferObjects(unsigned int contextID,double currentTime, double& availableTime); + + /** discard all the cached FBOs which need to be deleted + * in the OpenGL context related to contextID.*/ + static void discardDeletedFrameBufferObjects(unsigned int contextID); + + /** Resize any per context GLObject buffers to specified size. */ + virtual void resizeGLObjectBuffers(unsigned int maxSize); + + /** If State is non-zero, this function releases any associated OpenGL objects for + * the specified graphics context. Otherwise, releases OpenGL objexts + * for all graphics contexts. */ + virtual void releaseGLObjects(osg::State* = 0) const; + + protected: + virtual ~FrameBufferObject(); + FrameBufferObject& operator = (const FrameBufferObject&) { return *this; } + + void updateDrawBuffers(); + + inline void dirtyAll(); + + GLenum convertBufferComponentToGLenum(BufferComponent attachment_point) const; + + private: + AttachmentMap _attachments; + + // Buffers passed to glDrawBuffers when using multiple render targets. + MultipleRenderingTargets _drawBuffers; + + mutable buffered_value _dirtyAttachmentList; + mutable buffered_value _unsupported; + mutable buffered_value _fboID; + + }; + + // INLINE METHODS + + inline const FrameBufferObject::AttachmentMap &FrameBufferObject::getAttachmentMap() const + { + return _attachments; + } + + inline bool FrameBufferObject::hasAttachment(FrameBufferObject::BufferComponent attachment_point) const + { + return _attachments.find(attachment_point) != _attachments.end(); + } + + inline const FrameBufferAttachment &FrameBufferObject::getAttachment(FrameBufferObject::BufferComponent attachment_point) const + { + return _attachments.find(attachment_point)->second; + } + + inline void FrameBufferObject::dirtyAll() + { + _dirtyAttachmentList.setAllElementsTo(1); + } + + +} + +#endif + diff --git a/libs/include/android/osg/FrameStamp b/libs/include/android/osg/FrameStamp new file mode 100755 index 0000000..ce48e1e --- /dev/null +++ b/libs/include/android/osg/FrameStamp @@ -0,0 +1,91 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_FRAMESTAMP +#define OSG_FRAMESTAMP 1 + +#include + +#if defined(__sgi) || (defined(WIN32) && !defined(__MWERKS__)) +#include +#else +#include +using std::tm; +#endif + +namespace osg +{ + +/** Class which encapsulates the frame number, reference time and calendar + * time of specific frame, used to synchronize operations on the scene graph + * and other machines when using a graphics cluster. Note the calendar + * time can be an artificial simulation time or capture the real time + * of day etc.*/ +class OSG_EXPORT FrameStamp : public Referenced +{ + public: + + FrameStamp(); + FrameStamp(const FrameStamp& fs); + + FrameStamp& operator = (const FrameStamp& fs); + + void setFrameNumber(unsigned int fnum) { _frameNumber = fnum; } + unsigned int getFrameNumber() const { return _frameNumber; } + + void setReferenceTime(double refTime) { _referenceTime = refTime; } + double getReferenceTime() const { return _referenceTime; } + + void setSimulationTime(double refTime) { _simulationTime = refTime; } + double getSimulationTime() const { return _simulationTime; } + + void setCalendarTime(const tm& calendarTime); + void getCalendarTime(tm& calendarTime) const; + + // keep public to allow it to be permit allocation which is + // not on the heap used osgcluster + virtual ~FrameStamp(); + + protected: + + + // note no dynamic memory is used so that data can be passed + // via a simple memory copy or within a data packet across + // the network. + + unsigned int _frameNumber; + double _referenceTime; + double _simulationTime; + + // member variables of time.h's tm structure, copied here to + // ensure that all data is not dynamic. The tm structure itself + // is not completely consistent between implementations, which + // could be a problem when sending the FrameStamp across a network + // with different versions of tm (i.e mixing Unix and Windows.) + int tm_sec; /* Seconds. [0-60] (1 leap second) */ + int tm_min; /* Minutes. [0-59] */ + int tm_hour; /* Hours. [0-23] */ + int tm_mday; /* Day. [1-31] */ + int tm_mon; /* Month. [0-11] */ + int tm_year; /* Year - 1900. */ + int tm_wday; /* Day of week. [0-6] */ + int tm_yday; /* Days in year. [0-365] */ + int tm_isdst; /* DST. [-1/0/1]*/ + + +}; + +} + + +#endif diff --git a/libs/include/android/osg/FrontFace b/libs/include/android/osg/FrontFace new file mode 100755 index 0000000..2f7f9fb --- /dev/null +++ b/libs/include/android/osg/FrontFace @@ -0,0 +1,70 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_FRONTFACE +#define OSG_FRONTFACE 1 + +#include +#include + +namespace osg { + +/** Class to specify the orientation of front-facing polygons. +*/ +class OSG_EXPORT FrontFace : public StateAttribute +{ + public : + + enum Mode { + CLOCKWISE = GL_CW, + COUNTER_CLOCKWISE = GL_CCW + }; + + FrontFace(Mode face=COUNTER_CLOCKWISE); + + /** Copy constructor using CopyOp to manage deep vs shallow copy.*/ + FrontFace(const FrontFace& ff,const CopyOp& copyop=CopyOp::SHALLOW_COPY): + StateAttribute(ff,copyop), + _mode(ff._mode) {} + + META_StateAttribute(osg, FrontFace, FRONTFACE); + + /** return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs.*/ + virtual int compare(const StateAttribute& sa) const + { + // check the types are equal and then create the rhs variable + // used by the COMPARE_StateAttribute_Parameter macros below. + COMPARE_StateAttribute_Types(FrontFace,sa) + + // compare each parameter in turn against the rhs. + COMPARE_StateAttribute_Parameter(_mode) + + return 0; // passed all the above comparison macros, must be equal. + } + + inline void setMode(Mode mode) { _mode = mode; } + inline Mode getMode() const { return _mode; } + + virtual void apply(State& state) const; + + protected: + + virtual ~FrontFace(); + + Mode _mode; + +}; + +} + +#endif diff --git a/libs/include/android/osg/GL b/libs/include/android/osg/GL new file mode 100755 index 0000000..1f387c6 --- /dev/null +++ b/libs/include/android/osg/GL @@ -0,0 +1,235 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_GL +#define OSG_GL 1 + +#include +#include + +#if defined(OSG_GLES1_AVAILABLE) + + #ifdef __APPLE__ + //if its apple include the target defines so we can check for IOS + #include "TargetConditionals.h" + #include + #else + #include + #endif + +#elif defined(OSG_GLES2_AVAILABLE) + + #ifdef __APPLE__ + //if its apple include the target defines so we can check for IOS + #include "TargetConditionals.h" + #include + #else + #include + #endif + + +#else + + #ifndef WIN32 + + // Required for compatibility with glext.h sytle function definitions of + // OpenGL extensions, such as in src/osg/Point.cpp. + #ifndef APIENTRY + #define APIENTRY + #endif + + #else // WIN32 + + #if defined(__CYGWIN__) || defined(__MINGW32__) + + #ifndef APIENTRY + #define GLUT_APIENTRY_DEFINED + #define APIENTRY __stdcall + #endif + // XXX This is from Win32's + #ifndef CALLBACK + #define CALLBACK __stdcall + #endif + + #else // ! __CYGWIN__ + + // Under Windows avoid including + // to avoid name space pollution, but Win32's + // needs APIENTRY and WINGDIAPI defined properly. + // XXX This is from Win32's + #ifndef APIENTRY + #define GLUT_APIENTRY_DEFINED + #if (_MSC_VER >= 800) || defined(_STDCALL_SUPPORTED) + #define WINAPI __stdcall + #define APIENTRY WINAPI + #else + #define APIENTRY + #endif + #endif + + // XXX This is from Win32's + #ifndef CALLBACK + #if (_MSC_VER >= 800) || defined(_STDCALL_SUPPORTED) + #define CALLBACK __stdcall + #else + #define CALLBACK + #endif + #endif + + #endif // __CYGWIN__ + + // XXX This is from Win32's and + #ifndef WINGDIAPI + #define GLUT_WINGDIAPI_DEFINED + #define DECLSPEC_IMPORT __declspec(dllimport) + #define WINGDIAPI DECLSPEC_IMPORT + #endif + + // XXX This is from Win32's + #if !defined(_WCHAR_T_DEFINED) && !(defined(__GNUC__)&&((__GNUC__ == 3)||(__GNUC__ == 4))) + typedef unsigned short wchar_t; + #define _WCHAR_T_DEFINED + #endif + + #endif // WIN32 + + #if defined(OSG_GL3_AVAILABLE) + + #define GL3_PROTOTYPES 1 + #ifdef __APPLE__ + #include + #include + #define GLint64EXT GLint64 + #define GLuint64EXT GLuint64 + #define GL_BGRA_EXT GL_BGRA + #else + #include + #endif + + #else + #ifndef __gl_h_ + #ifdef __APPLE__ + #include + #else + #include + + // hack required to avoid conflicts with Qt + // Qt expects GLdouble to be a macro ?! + #ifndef GLdouble + #define GLdouble double + #endif + #endif + #endif + #endif + + #ifndef GL_APIENTRY + #define GL_APIENTRY APIENTRY + #endif // GL_APIENTRY + +#endif + + +#ifdef OSG_GL_MATRICES_AVAILABLE + + inline void glLoadMatrix(const float* mat) { glLoadMatrixf(static_cast(mat)); } + inline void glMultMatrix(const float* mat) { glMultMatrixf(static_cast(mat)); } + + #ifdef OSG_GLES1_AVAILABLE + inline void glLoadMatrix(const double* mat) + { + GLfloat flt_mat[16]; + for(unsigned int i=0;i<16;++i) flt_mat[i] = mat[i]; + glLoadMatrixf(flt_mat); + } + + inline void glMultMatrix(const double* mat) + { + GLfloat flt_mat[16]; + for(unsigned int i=0;i<16;++i) flt_mat[i] = mat[i]; + glMultMatrixf(flt_mat); + } + + #else + inline void glLoadMatrix(const double* mat) { glLoadMatrixd(static_cast(mat)); } + inline void glMultMatrix(const double* mat) { glMultMatrixd(static_cast(mat)); } + #endif +#endif + +// add defines for OpenGL targets that don't define them, just to ease compatibility across targets +#ifndef GL_DOUBLE + #define GL_DOUBLE 0x140A + typedef double GLdouble; +#endif + +#ifndef GL_INT + #define GL_INT 0x1404 +#endif + +#ifndef GL_UNSIGNED_INT + #define GL_UNSIGNED_INT 0x1405 +#endif + +#ifndef GL_NONE + // OpenGL ES1 doesn't provide GL_NONE + #define GL_NONE 0x0 +#endif + +#if defined(OSG_GLES1_AVAILABLE) || defined(OSG_GLES2_AVAILABLE) + //GLES defines (OES) + #define GL_RGB8_OES 0x8051 + #define GL_RGBA8_OES 0x8058 +#endif + +#if defined(OSG_GLES1_AVAILABLE) || defined(OSG_GLES2_AVAILABLE) || defined(OSG_GL3_AVAILABLE) + #define GL_POLYGON 0x0009 + #define GL_QUADS 0x0007 + #define GL_QUAD_STRIP 0x0008 +#endif + +#if defined(OSG_GL3_AVAILABLE) + #define GL_LUMINANCE 0x1909 + #define GL_LUMINANCE_ALPHA 0x190A +#endif + +#ifdef OSG_GL1_AVAILABLE + #define OSG_GL1_FEATURES true +#else + #define OSG_GL1_FEATURES false +#endif + +#ifdef OSG_GL2_AVAILABLE + #define OSG_GL2_FEATURES true +#else + #define OSG_GL2_FEATURES false +#endif + +#ifdef OSG_GL3_AVAILABLE + #define OSG_GL3_FEATURES true +#else + #define OSG_GL3_FEATURES false +#endif + +#ifdef OSG_GLES1_AVAILABLE + #define OSG_GLES1_FEATURES true +#else + #define OSG_GLES1_FEATURES false +#endif + +#ifdef OSG_GLES2_AVAILABLE + #define OSG_GLES2_FEATURES true +#else + #define OSG_GLES2_FEATURES false +#endif + + +#endif // __osgGL_h diff --git a/libs/include/android/osg/GL2Extensions b/libs/include/android/osg/GL2Extensions new file mode 100755 index 0000000..5ed890f --- /dev/null +++ b/libs/include/android/osg/GL2Extensions @@ -0,0 +1,1066 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * Copyright (C) 2003-2005 3Dlabs Inc. Ltd. + * Copyright (C) 2004-2005 Nathan Cournia + * Copyright (C) 2007 Art Tevs + * Copyright (C) 2008 Zebra Imaging + * Copyright (C) 2010 VIRES Simulationstechnologie GmbH + * Copyright (C) 2012 David Callu + * + * This application is open source and may be redistributed and/or modified + * freely and without restriction, both in commercial and non commercial + * applications, as long as this copyright notice is maintained. + * + * This application is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. +*/ + +/* file: include/osg/GL2Extensions + * author: Mike Weiblen 2008-01-02 + * Holger Helmich 2010-10-21 +*/ + +#ifndef OSG_GL2EXTENSIONS +#define OSG_GL2EXTENSIONS 1 + +#include +#include + +#include + +#ifndef GL_SAMPLER_2D_ARRAY_EXT + #define GL_SAMPLER_1D_ARRAY_EXT 0x8DC0 + #define GL_SAMPLER_2D_ARRAY_EXT 0x8DC1 + #define GL_SAMPLER_1D_ARRAY_SHADOW_EXT 0x8DC3 + #define GL_SAMPLER_2D_ARRAY_SHADOW_EXT 0x8DC4 +#endif + +#if !defined(GL_VERSION_2_0) +typedef char GLchar; +#endif + +#if !defined(GL_VERSION_2_0) + #define GL_VERTEX_PROGRAM_POINT_SIZE 0x8642 + #define GL_VERTEX_PROGRAM_TWO_SIDE 0x8643 +#endif + +#if !defined(GL_VERSION_2_0) && !defined(GL_ES_VERSION_2_0) +#define GL_VERSION_2_0 1 +#define GL_BLEND_EQUATION_RGB GL_BLEND_EQUATION +#define GL_VERTEX_ATTRIB_ARRAY_ENABLED 0x8622 +#define GL_VERTEX_ATTRIB_ARRAY_SIZE 0x8623 +#define GL_VERTEX_ATTRIB_ARRAY_STRIDE 0x8624 +#define GL_VERTEX_ATTRIB_ARRAY_TYPE 0x8625 +#define GL_CURRENT_VERTEX_ATTRIB 0x8626 +#define GL_VERTEX_ATTRIB_ARRAY_POINTER 0x8645 +#define GL_STENCIL_BACK_FUNC 0x8800 +#define GL_STENCIL_BACK_FAIL 0x8801 +#define GL_STENCIL_BACK_PASS_DEPTH_FAIL 0x8802 +#define GL_STENCIL_BACK_PASS_DEPTH_PASS 0x8803 +#define GL_MAX_DRAW_BUFFERS 0x8824 +#define GL_DRAW_BUFFER0 0x8825 +#define GL_DRAW_BUFFER1 0x8826 +#define GL_DRAW_BUFFER2 0x8827 +#define GL_DRAW_BUFFER3 0x8828 +#define GL_DRAW_BUFFER4 0x8829 +#define GL_DRAW_BUFFER5 0x882A +#define GL_DRAW_BUFFER6 0x882B +#define GL_DRAW_BUFFER7 0x882C +#define GL_DRAW_BUFFER8 0x882D +#define GL_DRAW_BUFFER9 0x882E +#define GL_DRAW_BUFFER10 0x882F +#define GL_DRAW_BUFFER11 0x8830 +#define GL_DRAW_BUFFER12 0x8831 +#define GL_DRAW_BUFFER13 0x8832 +#define GL_DRAW_BUFFER14 0x8833 +#define GL_DRAW_BUFFER15 0x8834 +#define GL_BLEND_EQUATION_ALPHA 0x883D +#define GL_POINT_SPRITE 0x8861 +#define GL_COORD_REPLACE 0x8862 +#define GL_MAX_VERTEX_ATTRIBS 0x8869 +#define GL_VERTEX_ATTRIB_ARRAY_NORMALIZED 0x886A +#define GL_MAX_TEXTURE_COORDS 0x8871 +#define GL_MAX_TEXTURE_IMAGE_UNITS 0x8872 +#define GL_FRAGMENT_SHADER 0x8B30 +#define GL_VERTEX_SHADER 0x8B31 +#define GL_MAX_FRAGMENT_UNIFORM_COMPONENTS 0x8B49 +#define GL_MAX_VERTEX_UNIFORM_COMPONENTS 0x8B4A +#define GL_MAX_VARYING_FLOATS 0x8B4B +#define GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS 0x8B4C +#define GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS 0x8B4D +#define GL_SHADER_TYPE 0x8B4F +#define GL_FLOAT_VEC2 0x8B50 +#define GL_FLOAT_VEC3 0x8B51 +#define GL_FLOAT_VEC4 0x8B52 +#define GL_INT_VEC2 0x8B53 +#define GL_INT_VEC3 0x8B54 +#define GL_INT_VEC4 0x8B55 +#define GL_BOOL 0x8B56 +#define GL_BOOL_VEC2 0x8B57 +#define GL_BOOL_VEC3 0x8B58 +#define GL_BOOL_VEC4 0x8B59 +#define GL_FLOAT_MAT2 0x8B5A +#define GL_FLOAT_MAT3 0x8B5B +#define GL_FLOAT_MAT4 0x8B5C +#define GL_DELETE_STATUS 0x8B80 +#define GL_COMPILE_STATUS 0x8B81 +#define GL_LINK_STATUS 0x8B82 +#define GL_VALIDATE_STATUS 0x8B83 +#define GL_INFO_LOG_LENGTH 0x8B84 +#define GL_ATTACHED_SHADERS 0x8B85 +#define GL_ACTIVE_UNIFORMS 0x8B86 +#define GL_ACTIVE_UNIFORM_MAX_LENGTH 0x8B87 +#define GL_SHADER_SOURCE_LENGTH 0x8B88 +#define GL_ACTIVE_ATTRIBUTES 0x8B89 +#define GL_ACTIVE_ATTRIBUTE_MAX_LENGTH 0x8B8A +#define GL_FRAGMENT_SHADER_DERIVATIVE_HINT 0x8B8B +#define GL_SHADING_LANGUAGE_VERSION 0x8B8C +#define GL_CURRENT_PROGRAM 0x8B8D +#define GL_POINT_SPRITE_COORD_ORIGIN 0x8CA0 +#define GL_LOWER_LEFT 0x8CA1 +#define GL_UPPER_LEFT 0x8CA2 +#define GL_STENCIL_BACK_REF 0x8CA3 +#define GL_STENCIL_BACK_VALUE_MASK 0x8CA4 +#define GL_STENCIL_BACK_WRITEMASK 0x8CA5 + +#define GL_SAMPLER_2D 0x8B5E +#define GL_SAMPLER_CUBE 0x8B60 +#endif + +#if !defined(GL_SAMPLER_1D) +#define GL_SAMPLER_1D 0x8B5D +#endif +#if !defined(GL_SAMPLER_3D) +#define GL_SAMPLER_3D 0x8B5F +#endif + +#if !defined(GL_SAMPLER_1D_SHADOW) +#define GL_SAMPLER_1D_SHADOW 0x8B61 +#define GL_SAMPLER_2D_SHADOW 0x8B62 +#endif + +#ifndef GL_VERSION_2_1 +#define GL_VERSION_2_1 1 +#define GL_CURRENT_RASTER_SECONDARY_COLOR 0x845F +#define GL_PIXEL_PACK_BUFFER 0x88EB +#define GL_PIXEL_UNPACK_BUFFER 0x88EC +#define GL_PIXEL_PACK_BUFFER_BINDING 0x88ED +#define GL_PIXEL_UNPACK_BUFFER_BINDING 0x88EF +#define GL_FLOAT_MAT2x3 0x8B65 +#define GL_FLOAT_MAT2x4 0x8B66 +#define GL_FLOAT_MAT3x2 0x8B67 +#define GL_FLOAT_MAT3x4 0x8B68 +#define GL_FLOAT_MAT4x2 0x8B69 +#define GL_FLOAT_MAT4x3 0x8B6A +#define GL_SRGB 0x8C40 +#define GL_SRGB8 0x8C41 +#define GL_SRGB_ALPHA 0x8C42 +#define GL_SRGB8_ALPHA8 0x8C43 +#define GL_SLUMINANCE_ALPHA 0x8C44 +#define GL_SLUMINANCE8_ALPHA8 0x8C45 +#define GL_SLUMINANCE 0x8C46 +#define GL_SLUMINANCE8 0x8C47 +#define GL_COMPRESSED_SRGB 0x8C48 +#define GL_COMPRESSED_SRGB_ALPHA 0x8C49 +#define GL_COMPRESSED_SLUMINANCE 0x8C4A +#define GL_COMPRESSED_SLUMINANCE_ALPHA 0x8C4B +#endif + +#ifndef GL_ARB_framebuffer_sRGB +#define GL_FRAMEBUFFER_SRGB 0x8DB9 +#endif + +// EXT_geometry_shader4 +#ifndef GL_EXT_geometry_shader4 +#define GL_GEOMETRY_SHADER_EXT 0x8DD9 +#define GL_GEOMETRY_VERTICES_OUT_EXT 0x8DDA +#define GL_GEOMETRY_INPUT_TYPE_EXT 0x8DDB +#define GL_GEOMETRY_OUTPUT_TYPE_EXT 0x8DDC +#define GL_MAX_GEOMETRY_TEXTURE_IMAGE_UNITS_EXT 0x8C29 +#define GL_MAX_GEOMETRY_VARYING_COMPONENTS_EXT 0x8DDD +#define GL_MAX_VERTEX_VARYING_COMPONENTS_EXT 0x8DDE +#define GL_MAX_VARYING_COMPONENTS_EXT 0x8B4B +#define GL_MAX_GEOMETRY_UNIFORM_COMPONENTS_EXT 0x8DDF +#define GL_MAX_GEOMETRY_OUTPUT_VERTICES_EXT 0x8DE0 +#define GL_MAX_GEOMETRY_TOTAL_OUTPUT_COMPONENTS_EXT 0x8DE1 +#define GL_LINES_ADJACENCY_EXT 0x000A +#define GL_LINE_STRIP_ADJACENCY_EXT 0x000B +#define GL_TRIANGLES_ADJACENCY_EXT 0x000C +#define GL_TRIANGLE_STRIP_ADJACENCY_EXT 0x000D +#define GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS_EXT 0x8DA8 +#define GL_FRAMEBUFFER_INCOMPLETE_LAYER_COUNT_EXT 0x8DA9 +#define GL_FRAMEBUFFER_ATTACHMENT_LAYERED_EXT 0x8DA7 +#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER_EXT 0x8CD4 +#define GL_PROGRAM_POINT_SIZE_EXT 0x8642 +#endif + +// ARB_tessellation_shader +#ifndef GL_ARB_tessellation_shader +#define GL_PATCHES 0x000E +#define GL_PATCH_VERTICES 0x8E72 +#define GL_PATCH_DEFAULT_INNER_LEVEL 0x8E73 +#define GL_PATCH_DEFAULT_OUTER_LEVEL 0x8E74 +#define GL_MAX_PATCH_VERTICES 0x8E7D +#define GL_MAX_TESS_GEN_LEVEL 0x8E7E +#define GL_MAX_TESS_CONTROL_UNIFORM_COMPONENTS 0x8E7F +#define GL_MAX_TESS_EVALUATION_UNIFORM_COMPONENTS 0x8E80 +#define GL_MAX_TESS_CONTROL_TEXTURE_IMAGE_UNITS 0x8E81 +#define GL_MAX_MAX_TESS_EVALUATION_TEXTURE_IMAGE_UNITS 0x8E82 +#define GL_MAX_MAX_TESS_CONTROL_OUTPUT_COMPONENTS 0x8E83 +#define GL_MAX_MAX_TESS_PATCH_COMPONENTS 0x8E84 +#define GL_MAX_MAX_TESS_CONTROL_TOTAL_OUTPUT_COMPONENTS 0x8E85 +#define GL_MAX_MAX_TESS_EVALUATION_OUTPUT_COMPONENTS 0x8E86 +#define GL_MAX_MAX_TESS_CONTROL_UNIFORM_BLOCKS 0x8E89 +#define GL_MAX_MAX_TESS_EVALUATION_UNIFORM_BLOCKS 0x8E8A +#define GL_MAX_MAX_TESS_CONTROL_INPUT_COMPONENTS 0x886C +#define GL_MAX_MAX_TESS_EVALUATION_INPUT_COMPONENTS 0x886D +#define GL_MAX_MAX_COMBINED_TESS_CONTROL_UNIFORM_COMPONENTS 0x8E1E +#define GL_MAX_MAX_COMBINED_TESS_EVALUATION_UNIFORM_COMPONENTS 0x8E1F +#define GL_TESS_EVALUATION_SHADER 0x8E87 +#define GL_TESS_CONTROL_SHADER 0x8E88 +#define GL_TESS_CONTROL_OUTPUT_VERTICES 0x8E75 +#define GL_TESS_GEN_MODE 0x8E76 +#define GL_TESS_GEN_SPACING 0x8E77 +#define GL_TESS_GEN_VERTEX_ORDER 0x8E78 +#define GL_TESS_GEN_POINT_MODE 0x8E79 +#define GL_ISOLINES 0x8E7A +#define GL_FRACTIONAL_ODD 0x8E7B +#define GL_FRACTIONAL_EVEN 0x8E7C +#define GL_UNIFORM_BLOCK_REFERENCED_BY_TESS_CONTROL_SHADER 0x84F0 +#define GL_UNIFORM_BLOCK_REFERENCED_BY_TESS_EVALUATION_SHADER 0x84F1 +#endif + +// EXT_gpu_shader4 +#ifndef GL_EXT_gpu_shader4 +#define GL_SAMPLER_1D_ARRAY_EXT 0x8DC0 +#define GL_SAMPLER_2D_ARRAY_EXT 0x8DC1 +#define GL_SAMPLER_BUFFER_EXT 0x8DC2 +#define GL_SAMPLER_1D_ARRAY_SHADOW_EXT 0x8DC3 +#define GL_SAMPLER_2D_ARRAY_SHADOW_EXT 0x8DC4 +#define GL_SAMPLER_CUBE_SHADOW_EXT 0x8DC5 +#define GL_UNSIGNED_INT_VEC2_EXT 0x8DC6 +#define GL_UNSIGNED_INT_VEC3_EXT 0x8DC7 +#define GL_UNSIGNED_INT_VEC4_EXT 0x8DC8 +#define GL_INT_SAMPLER_1D_EXT 0x8DC9 +#define GL_INT_SAMPLER_2D_EXT 0x8DCA +#define GL_INT_SAMPLER_3D_EXT 0x8DCB +#define GL_INT_SAMPLER_CUBE_EXT 0x8DCC +#define GL_INT_SAMPLER_2D_RECT_EXT 0x8DCD +#define GL_INT_SAMPLER_1D_ARRAY_EXT 0x8DCE +#define GL_INT_SAMPLER_2D_ARRAY_EXT 0x8DCF +#define GL_INT_SAMPLER_BUFFER_EXT 0x8DD0 +#define GL_UNSIGNED_INT_SAMPLER_1D_EXT 0x8DD1 +#define GL_UNSIGNED_INT_SAMPLER_2D_EXT 0x8DD2 +#define GL_UNSIGNED_INT_SAMPLER_3D_EXT 0x8DD3 +#define GL_UNSIGNED_INT_SAMPLER_CUBE_EXT 0x8DD4 +#define GL_UNSIGNED_INT_SAMPLER_2D_RECT_EXT 0x8DD5 +#define GL_UNSIGNED_INT_SAMPLER_1D_ARRAY_EXT 0x8DD6 +#define GL_UNSIGNED_INT_SAMPLER_2D_ARRAY_EXT 0x8DD7 +#define GL_UNSIGNED_INT_SAMPLER_BUFFER_EXT 0x8DD8 +#define GL_MIN_PROGRAM_TEXEL_OFFSET_EXT 0x8904 +#define GL_MAX_PROGRAM_TEXEL_OFFSET_EXT 0x8905 +#endif + +// ARB_uniform_buffer_object +#ifndef GL_ARB_uniform_buffer_object +#define GL_UNIFORM_BUFFER 0x8A11 +#define GL_UNIFORM_BUFFER_BINDING 0x8A28 +#define GL_UNIFORM_BUFFER_START 0x8A29 +#define GL_UNIFORM_BUFFER_SIZE 0x8A2A +#define GL_MAX_VERTEX_UNIFORM_BLOCKS 0x8A2B +#define GL_MAX_GEOMETRY_UNIFORM_BLOCKS 0x8A2C +#define GL_MAX_FRAGMENT_UNIFORM_BLOCKS 0x8A2D +#define GL_MAX_COMBINED_UNIFORM_BLOCKS 0x8A2E +#define GL_MAX_UNIFORM_BUFFER_BINDINGS 0x8A2F +#define GL_MAX_UNIFORM_BLOCK_SIZE 0x8A30 +#define GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS 0x8A31 +#define GL_MAX_COMBINED_GEOMETRY_UNIFORM_COMPONENTS 0x8A32 +#define GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS 0x8A33 +#define GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT 0x8A34 +#define GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH 0x8A35 +#define GL_ACTIVE_UNIFORM_BLOCKS 0x8A36 +#define GL_UNIFORM_TYPE 0x8A37 +#define GL_UNIFORM_SIZE 0x8A38 +#define GL_UNIFORM_NAME_LENGTH 0x8A39 +#define GL_UNIFORM_BLOCK_INDEX 0x8A3A +#define GL_UNIFORM_OFFSET 0x8A3B +#define GL_UNIFORM_ARRAY_STRIDE 0x8A3C +#define GL_UNIFORM_MATRIX_STRIDE 0x8A3D +#define GL_UNIFORM_IS_ROW_MAJOR 0x8A3E +#define GL_UNIFORM_BLOCK_BINDING 0x8A3F +#define GL_UNIFORM_BLOCK_DATA_SIZE 0x8A40 +#define GL_UNIFORM_BLOCK_NAME_LENGTH 0x8A41 +#define GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS 0x8A42 +#define GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES 0x8A43 +#define GL_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER 0x8A44 +#define GL_UNIFORM_BLOCK_REFERENCED_BY_GEOMETRY_SHADER 0x8A45 +#define GL_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER 0x8A46 +#define GL_INVALID_INDEX 0xFFFFFFFFu +#endif + +// ARB_get_program_binary +#ifndef GL_ARB_get_program_binary +#define GL_PROGRAM_BINARY_RETRIEVABLE_HINT 0x8257 +#define GL_PROGRAM_BINARY_LENGTH 0x8741 +#define GL_NUM_PROGRAM_BINARY_FORMATS 0x87FE +#define GL_PROGRAM_BINARY_FORMATS 0x87FF +#endif + +// ARB_gpu_shader_fp64 +#ifndef GL_ARB_gpu_shader_fp64 +#define GL_DOUBLE_VEC2 0x8FFC +#define GL_DOUBLE_VEC3 0x8FFD +#define GL_DOUBLE_VEC4 0x8FFE +#define GL_DOUBLE_MAT2 0x8F46 +#define GL_DOUBLE_MAT3 0x8F47 +#define GL_DOUBLE_MAT4 0x8F48 +#define GL_DOUBLE_MAT2x3 0x8F49 +#define GL_DOUBLE_MAT2x4 0x8F4A +#define GL_DOUBLE_MAT3x2 0x8F4B +#define GL_DOUBLE_MAT3x4 0x8F4C +#define GL_DOUBLE_MAT4x2 0x8F4D +#define GL_DOUBLE_MAT4x3 0x8F4E +#endif + +// ARB_texture_multisample +#ifndef GL_ARB_texture_multisample +#define GL_SAMPLER_2D_MULTISAMPLE 0x9108 +#define GL_INT_SAMPLER_2D_MULTISAMPLE 0x9109 +#define GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE 0x910A +#define GL_SAMPLER_2D_MULTISAMPLE_ARRAY 0x910B +#define GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY 0x910C +#define GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY 0x910D +#endif + +// GL_ARB_shader_image_load_store +#ifndef GL_ARB_shader_image_load_store +#define GL_IMAGE_1D 0x904C +#define GL_IMAGE_2D 0x904D +#define GL_IMAGE_3D 0x904E +#define GL_IMAGE_2D_RECT 0x904F +#define GL_IMAGE_CUBE 0x9050 +#define GL_IMAGE_BUFFER 0x9051 +#define GL_IMAGE_1D_ARRAY 0x9052 +#define GL_IMAGE_2D_ARRAY 0x9053 +#define GL_IMAGE_CUBE_MAP_ARRAY 0x9054 +#define GL_IMAGE_2D_MULTISAMPLE 0x9055 +#define GL_IMAGE_2D_MULTISAMPLE_ARRAY 0x9056 +#define GL_INT_IMAGE_1D 0x9057 +#define GL_INT_IMAGE_2D 0x9058 +#define GL_INT_IMAGE_3D 0x9059 +#define GL_INT_IMAGE_2D_RECT 0x905A +#define GL_INT_IMAGE_CUBE 0x905B +#define GL_INT_IMAGE_BUFFER 0x905C +#define GL_INT_IMAGE_1D_ARRAY 0x905D +#define GL_INT_IMAGE_2D_ARRAY 0x905E +#define GL_INT_IMAGE_CUBE_MAP_ARRAY 0x905F +#define GL_INT_IMAGE_2D_MULTISAMPLE 0x9060 +#define GL_INT_IMAGE_2D_MULTISAMPLE_ARRAY 0x9061 +#define GL_UNSIGNED_INT_IMAGE_1D 0x9062 +#define GL_UNSIGNED_INT_IMAGE_2D 0x9063 +#define GL_UNSIGNED_INT_IMAGE_3D 0x9064 +#define GL_UNSIGNED_INT_IMAGE_2D_RECT 0x9065 +#define GL_UNSIGNED_INT_IMAGE_CUBE 0x9066 +#define GL_UNSIGNED_INT_IMAGE_BUFFER 0x9067 +#define GL_UNSIGNED_INT_IMAGE_1D_ARRAY 0x9068 +#define GL_UNSIGNED_INT_IMAGE_2D_ARRAY 0x9069 +#define GL_UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY 0x906A +#define GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE 0x906B +#define GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE_ARRAY 0x906C +#endif + +#ifndef GL_VERSION_3_1 +#define GL_SAMPLER_2D_RECT 0x8B63 +#define GL_SAMPLER_2D_RECT_SHADOW 0x8B64 +#define GL_SAMPLER_BUFFER 0x8DC2 +#define GL_INT_SAMPLER_2D_RECT 0x8DCD +#define GL_INT_SAMPLER_BUFFER 0x8DD0 +#define GL_UNSIGNED_INT_SAMPLER_2D_RECT 0x8DD5 +#define GL_UNSIGNED_INT_SAMPLER_BUFFER 0x8DD8 +#define GL_TEXTURE_BUFFER 0x8C2A +#define GL_MAX_TEXTURE_BUFFER_SIZE 0x8C2B +#define GL_TEXTURE_BINDING_BUFFER 0x8C2C +#define GL_TEXTURE_BUFFER_DATA_STORE_BINDING 0x8C2D +#define GL_TEXTURE_RECTANGLE 0x84F5 +#define GL_TEXTURE_BINDING_RECTANGLE 0x84F6 +#define GL_PROXY_TEXTURE_RECTANGLE 0x84F7 +#define GL_MAX_RECTANGLE_TEXTURE_SIZE 0x84F8 +#define GL_RGB_SNORM 0x8F92 +#define GL_RGBA_SNORM 0x8F93 +#define GL_R8_SNORM 0x8F94 +#define GL_RG8_SNORM 0x8F95 +#define GL_RGB8_SNORM 0x8F96 +#define GL_RGBA8_SNORM 0x8F97 +#define GL_R16_SNORM 0x8F98 +#define GL_RG16_SNORM 0x8F99 +#define GL_RGB16_SNORM 0x8F9A +#define GL_RGBA16_SNORM 0x8F9B +#define GL_SIGNED_NORMALIZED 0x8F9C +#define GL_PRIMITIVE_RESTART 0x8F9D +#define GL_PRIMITIVE_RESTART_INDEX 0x8F9E +#endif + +#ifndef GL_RED_SNORM +#define GL_RED_SNORM 0x8F90 +#endif +#ifndef GL_RG_SNORM +#define GL_RG_SNORM 0x8F91 +#endif + + +#ifndef GL_VERSION_4_0 +#define GL_SAMPLER_CUBE_MAP_ARRAY 0x900C +#define GL_SAMPLER_CUBE_MAP_ARRAY_SHADOW 0x900D +#define GL_INT_SAMPLER_CUBE_MAP_ARRAY 0x900E +#define GL_UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAY 0x900F +#endif + +// ARB_shader_atomic_counters +#ifndef GL_ARB_shader_atomic_counters +#define GL_ATOMIC_COUNTER_BUFFER 0x92C0 +#define GL_ATOMIC_COUNTER_BUFFER_BINDING 0x92C1 +#define GL_ATOMIC_COUNTER_BUFFER_START 0x92C2 +#define GL_ATOMIC_COUNTER_BUFFER_SIZE 0x92C3 +#define GL_ATOMIC_COUNTER_BUFFER_DATA_SIZE 0x92C4 +#define GL_ATOMIC_COUNTER_BUFFER_ACTIVE_ATOMIC_COUNTERS 0x92C5 +#define GL_ATOMIC_COUNTER_BUFFER_ACTIVE_ATOMIC_COUNTER_INDICES 0x92C6 +#define GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_VERTEX_SHADER 0x92C7 +#define GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_TESS_CONTROL_SHADER 0x92C8 +#define GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_TESS_EVALUATION_SHADER 0x92C9 +#define GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_GEOMETRY_SHADER 0x92CA +#define GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_FRAGMENT_SHADER 0x92CB +#define GL_MAX_VERTEX_ATOMIC_COUNTER_BUFFERS 0x92CC +#define GL_MAX_TESS_CONTROL_ATOMIC_COUNTER_BUFFERS 0x92CD +#define GL_MAX_TESS_EVALUATION_ATOMIC_COUNTER_BUFFERS 0x92CE +#define GL_MAX_GEOMETRY_ATOMIC_COUNTER_BUFFERS 0x92CF +#define GL_MAX_FRAGMENT_ATOMIC_COUNTER_BUFFERS 0x92D0 +#define GL_MAX_COMBINED_ATOMIC_COUNTER_BUFFERS 0x92D1 +#define GL_MAX_VERTEX_ATOMIC_COUNTERS 0x92D2 +#define GL_MAX_TESS_CONTROL_ATOMIC_COUNTERS 0x92D3 +#define GL_MAX_TESS_EVALUATION_ATOMIC_COUNTERS 0x92D4 +#define GL_MAX_GEOMETRY_ATOMIC_COUNTERS 0x92D5 +#define GL_MAX_FRAGMENT_ATOMIC_COUNTERS 0x92D6 +#define GL_MAX_COMBINED_ATOMIC_COUNTERS 0x92D7 +#define GL_MAX_ATOMIC_COUNTER_BUFFER_SIZE 0x92D8 +#define GL_MAX_ATOMIC_COUNTER_BUFFER_BINDINGS 0x92DC +#define GL_ACTIVE_ATOMIC_COUNTER_BUFFERS 0x92D9 +#define GL_UNIFORM_ATOMIC_COUNTER_BUFFER_INDEX 0x92DA +#define GL_UNSIGNED_INT_ATOMIC_COUNTER 0x92DB +#endif + +// ARB_compute_shader +#ifndef GL_ARB_compute_shader +#define GL_COMPUTE_SHADER 0x91B9 +#define GL_MAX_COMPUTE_UNIFORM_BLOCKS 0x91BB +#define GL_MAX_COMPUTE_TEXTURE_IMAGE_UNITS 0x91BC +#define GL_MAX_COMPUTE_IMAGE_UNIFORMS 0x91BD +#define GL_MAX_COMPUTE_SHARED_MEMORY_SIZE 0x8262 +#define GL_MAX_COMPUTE_UNIFORM_COMPONENTS 0x8263 +#define GL_MAX_COMPUTE_ATOMIC_COUNTER_BUFFERS 0x8264 +#define GL_MAX_COMPUTE_ATOMIC_COUNTERS 0x8265 +#define GL_MAX_COMBINED_COMPUTE_UNIFORM_COMPONENTS 0x8266 +#define GL_MAX_COMPUTE_LOCAL_INVOCATIONS 0x90EB +#define GL_MAX_COMPUTE_WORK_GROUP_COUNT 0x91BE +#define GL_MAX_COMPUTE_WORK_GROUP_SIZE 0x91BF +#define GL_COMPUTE_LOCAL_WORK_SIZE 0x8267 +#define GL_UNIFORM_BLOCK_REFERENCED_BY_COMPUTE_SHADER 0x90EC +#define GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_COMPUTE_SHADER 0x90ED +#define GL_DISPATCH_INDIRECT_BUFFER 0x90EE +#define GL_DISPATCH_INDIRECT_BUFFER_BINDING 0x90EF +#define GL_COMPUTE_SHADER_BIT 0x00000020 +#endif + +#ifndef GL_ARB_depth_clamp +#define GL_DEPTH_CLAMP 0x864F +#endif + +#ifndef GL_ARB_provoking_vertex +#define GL_QUADS_FOLLOW_PROVOKING_VERTEX_CONVENTION 0x8E4C +#define GL_FIRST_VERTEX_CONVENTION 0x8E4D +#define GL_LAST_VERTEX_CONVENTION 0x8E4E +#define GL_PROVOKING_VERTEX 0x8E4F +#endif + +#ifndef GL_ARB_seamless_cube_map +#define GL_TEXTURE_CUBE_MAP_SEAMLESS 0x884F +#endif + +namespace osg { + +class OSG_EXPORT GL2Extensions : public osg::Referenced +{ + public: + GL2Extensions(unsigned int contextID); + GL2Extensions(const GL2Extensions& rhs); + + void lowestCommonDenominator(const GL2Extensions& rhs); + + void setupGL2Extensions(unsigned int contextID); + + /** Does the GL driver support OpenGL Shading Language? */ + bool isGlslSupported() const; + + float getGlVersion() const { return _glVersion; } + float getLanguageVersion() const { return _glslLanguageVersion; } + + void setShaderObjectsSupported(bool flag) { _isShaderObjectsSupported = flag; } + bool isShaderObjectsSupported() const { return _isShaderObjectsSupported; } + + void setVertexShaderSupported(bool flag) { _isVertexShaderSupported = flag; } + bool isVertexShaderSupported() const { return _isVertexShaderSupported; } + + void setFragmentShaderSupported(bool flag) { _isFragmentShaderSupported = flag; } + bool isFragmentShaderSupported() const { return _isFragmentShaderSupported; } + + void setLanguage100Supported(bool flag) { _isLanguage100Supported = flag; } + bool isLanguage100Supported() const { return _isLanguage100Supported; } + + void setGeometryShader4Supported(bool flag) { _isGeometryShader4Supported = flag; } + bool isGeometryShader4Supported() const { return _isGeometryShader4Supported; } + + void setTessellationShadersSupported(bool flag) { _areTessellationShadersSupported = flag; } + bool areTessellationShadersSupported() const { return _areTessellationShadersSupported; } + + void setGpuShader4Supported(bool flag) { _isGpuShader4Supported = flag; } + bool isGpuShader4Supported() const { return _isGpuShader4Supported; } + + void setUniformBufferObjectSupported(bool flag) { _isUniformBufferObjectSupported = flag; } + bool isUniformBufferObjectSupported() const {return _isUniformBufferObjectSupported; } + + void setGetProgramBinarySupported(bool flag) { _isGetProgramBinarySupported = flag; } + bool isGetProgramBinarySupported() const {return _isGetProgramBinarySupported; } + + void setGpuShaderFp64Supported(bool flag) { _isGpuShaderFp64Supported = flag; } + bool isGpuShaderFp64Supported() const {return _isGpuShaderFp64Supported; } + + void setShaderAtomicCounterSupported(bool flag) { _isShaderAtomicCountersSupported = flag; } + bool isShaderAtomicCounterSupported() const {return _isShaderAtomicCountersSupported; } + + bool isDrawBuffersSupported() const { return _glDrawBuffers!=0; } + + /** Function to call to get the extension of a specified context. + * If the Exentsion object for that context has not yet been created then + * and the 'createIfNotInitalized' flag been set to false then returns NULL. + * If 'createIfNotInitalized' is true then the Extensions object is + * automatically created. However, in this case the extension object + * only be created with the graphics context associated with ContextID..*/ + static GL2Extensions* Get(unsigned int contextID,bool createIfNotInitalized); + + /** allows users to override the extensions across graphics contexts. + * typically used when you have different extensions supported across graphics pipes + * but need to ensure that they all use the same low common denominator extensions.*/ + static void Set(unsigned int contextID, GL2Extensions* extensions); + + + void glBlendEquationSeparate(GLenum modeRGB, GLenum modeAlpha) const; + void glDrawBuffers(GLsizei n, const GLenum *bufs) const; + void glStencilOpSeparate(GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass) const; + void glStencilFuncSeparate(GLenum frontfunc, GLenum backfunc, GLint ref, GLuint mask) const; + void glStencilMaskSeparate(GLenum face, GLuint mask) const; + void glAttachShader(GLuint program, GLuint shader) const; + void glBindAttribLocation(GLuint program, GLuint index, const GLchar *name) const; + void glCompileShader(GLuint shader) const; + GLuint glCreateProgram(void) const; + GLuint glCreateShader(GLenum type) const; + void glDeleteProgram(GLuint program) const; + void glDeleteShader(GLuint shader) const; + void glDetachShader(GLuint program, GLuint shader) const; + void glDisableVertexAttribArray(GLuint index) const; + void glEnableVertexAttribArray(GLuint index) const; + void glGetActiveAttrib(GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name) const; + void glGetActiveUniform(GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name) const; + void glGetAttachedShaders(GLuint program, GLsizei maxCount, GLsizei *count, GLuint *obj) const; + GLint glGetAttribLocation(GLuint program, const GLchar *name) const; + void glGetProgramiv(GLuint program, GLenum pname, GLint *params) const; + void glGetProgramInfoLog(GLuint program, GLsizei bufSize, GLsizei *length, GLchar *infoLog) const; + void glGetShaderiv(GLuint shader, GLenum pname, GLint *params) const; + void glGetShaderInfoLog(GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *infoLog) const; + void glGetShaderSource(GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *source) const; + GLint glGetUniformLocation(GLuint program, const GLchar *name) const; + void glGetUniformfv(GLuint program, GLint location, GLfloat *params) const; + void glGetUniformiv(GLuint program, GLint location, GLint *params) const; + void glGetVertexAttribdv(GLuint index, GLenum pname, GLdouble *params) const; + void glGetVertexAttribfv(GLuint index, GLenum pname, GLfloat *params) const; + void glGetVertexAttribiv(GLuint index, GLenum pname, GLint *params) const; + void glGetVertexAttribPointerv(GLuint index, GLenum pname, GLvoid* *pointer) const; + GLboolean glIsProgram(GLuint program) const; + GLboolean glIsShader(GLuint shader) const; + void glLinkProgram(GLuint program) const; + void glShaderSource(GLuint shader, GLsizei count, const GLchar* *string, const GLint *length) const; + void glUseProgram(GLuint program) const; + void glUniform1f(GLint location, GLfloat v0) const; + void glUniform2f(GLint location, GLfloat v0, GLfloat v1) const; + void glUniform3f(GLint location, GLfloat v0, GLfloat v1, GLfloat v2) const; + void glUniform4f(GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3) const; + void glUniform1i(GLint location, GLint v0) const; + void glUniform2i(GLint location, GLint v0, GLint v1) const; + void glUniform3i(GLint location, GLint v0, GLint v1, GLint v2) const; + void glUniform4i(GLint location, GLint v0, GLint v1, GLint v2, GLint v3) const; + void glUniform1fv(GLint location, GLsizei count, const GLfloat *value) const; + void glUniform2fv(GLint location, GLsizei count, const GLfloat *value) const; + void glUniform3fv(GLint location, GLsizei count, const GLfloat *value) const; + void glUniform4fv(GLint location, GLsizei count, const GLfloat *value) const; + void glUniform1iv(GLint location, GLsizei count, const GLint *value) const; + void glUniform2iv(GLint location, GLsizei count, const GLint *value) const; + void glUniform3iv(GLint location, GLsizei count, const GLint *value) const; + void glUniform4iv(GLint location, GLsizei count, const GLint *value) const; + void glUniformMatrix2fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value) const; + void glUniformMatrix3fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value) const; + void glUniformMatrix4fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value) const; + void glValidateProgram(GLuint program) const; + void glVertexAttrib1d(GLuint index, GLdouble x) const; + void glVertexAttrib1dv(GLuint index, const GLdouble *v) const; + void glVertexAttrib1f(GLuint index, GLfloat x) const; + void glVertexAttrib1fv(GLuint index, const GLfloat *v) const; + void glVertexAttrib1s(GLuint index, GLshort x) const; + void glVertexAttrib1sv(GLuint index, const GLshort *v) const; + void glVertexAttrib2d(GLuint index, GLdouble x, GLdouble y) const; + void glVertexAttrib2dv(GLuint index, const GLdouble *v) const; + void glVertexAttrib2f(GLuint index, GLfloat x, GLfloat y) const; + void glVertexAttrib2fv(GLuint index, const GLfloat *v) const; + void glVertexAttrib2s(GLuint index, GLshort x, GLshort y) const; + void glVertexAttrib2sv(GLuint index, const GLshort *v) const; + void glVertexAttrib3d(GLuint index, GLdouble x, GLdouble y, GLdouble z) const; + void glVertexAttrib3dv(GLuint index, const GLdouble *v) const; + void glVertexAttrib3f(GLuint index, GLfloat x, GLfloat y, GLfloat z) const; + void glVertexAttrib3fv(GLuint index, const GLfloat *v) const; + void glVertexAttrib3s(GLuint index, GLshort x, GLshort y, GLshort z) const; + void glVertexAttrib3sv(GLuint index, const GLshort *v) const; + void glVertexAttrib4Nbv(GLuint index, const GLbyte *v) const; + void glVertexAttrib4Niv(GLuint index, const GLint *v) const; + void glVertexAttrib4Nsv(GLuint index, const GLshort *v) const; + void glVertexAttrib4Nub(GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w) const; + void glVertexAttrib4Nubv(GLuint index, const GLubyte *v) const; + void glVertexAttrib4Nuiv(GLuint index, const GLuint *v) const; + void glVertexAttrib4Nusv(GLuint index, const GLushort *v) const; + void glVertexAttrib4bv(GLuint index, const GLbyte *v) const; + void glVertexAttrib4d(GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w) const; + void glVertexAttrib4dv(GLuint index, const GLdouble *v) const; + void glVertexAttrib4f(GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w) const; + void glVertexAttrib4fv(GLuint index, const GLfloat *v) const; + void glVertexAttrib4iv(GLuint index, const GLint *v) const; + void glVertexAttrib4s(GLuint index, GLshort x, GLshort y, GLshort z, GLshort w) const; + void glVertexAttrib4sv(GLuint index, const GLshort *v) const; + void glVertexAttrib4ubv(GLuint index, const GLubyte *v) const; + void glVertexAttrib4uiv(GLuint index, const GLuint *v) const; + void glVertexAttrib4usv(GLuint index, const GLushort *v) const; + void glVertexAttribPointer(GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid *pointer) const; + void glVertexAttribDivisor(GLuint index, GLuint divisor) const; + + // C++-friendly convenience wrapper methods + GLuint getCurrentProgram() const; + bool getProgramInfoLog( GLuint program, std::string& result ) const; + bool getShaderInfoLog( GLuint shader, std::string& result ) const; + bool getAttribLocation( const char* attribName, GLuint& slot ) const; + bool getFragDataLocation( const char* fragDataName, GLuint& slot) const; + + // GL 2.1 + void glUniformMatrix2x3fv( GLint location, GLsizei count, GLboolean transpose, const GLfloat* value ) const; + void glUniformMatrix3x2fv( GLint location, GLsizei count, GLboolean transpose, const GLfloat* value ) const; + void glUniformMatrix2x4fv( GLint location, GLsizei count, GLboolean transpose, const GLfloat* value ) const; + void glUniformMatrix4x2fv( GLint location, GLsizei count, GLboolean transpose, const GLfloat* value ) const; + void glUniformMatrix3x4fv( GLint location, GLsizei count, GLboolean transpose, const GLfloat* value ) const; + void glUniformMatrix4x3fv( GLint location, GLsizei count, GLboolean transpose, const GLfloat* value ) const; + + // EXT_geometry_shader4 + void glProgramParameteri( GLuint program, GLenum pname, GLint value ) const; + void glFramebufferTexture( GLenum target, GLenum attachment, GLuint texture, GLint level ) const; + void glFramebufferTextureLayer( GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer ) const; + void glFramebufferTextureFace( GLenum target, GLenum attachment, GLuint texture, GLint level, GLenum face ) const; + + // ARB_tessellation_shader + void glPatchParameteri(GLenum pname, GLint value) const; + void glPatchParameterfv(GLenum pname, const GLfloat *values) const; + + // EXT_gpu_shader4 + void glGetUniformuiv( GLuint program, GLint location, GLuint *params ) const; + void glBindFragDataLocation( GLuint program, GLuint color, const GLchar *name ) const; + GLint glGetFragDataLocation( GLuint program, const GLchar *name ) const; + void glUniform1ui( GLint location, GLuint v0 ) const; + void glUniform2ui( GLint location, GLuint v0, GLuint v1 ) const; + void glUniform3ui( GLint location, GLuint v0, GLuint v1, GLuint v2 ) const; + void glUniform4ui( GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3 ) const; + void glUniform1uiv( GLint location, GLsizei count, const GLuint *value ) const; + void glUniform2uiv( GLint location, GLsizei count, const GLuint *value ) const; + void glUniform3uiv( GLint location, GLsizei count, const GLuint *value ) const; + void glUniform4uiv( GLint location, GLsizei count, const GLuint *value ) const; + + // ARB_uniform_buffer_object + void glGetUniformIndices(GLuint program, GLsizei uniformCount, const GLchar* *uniformNames, GLuint *uniformIndices) const; + void glGetActiveUniformsiv(GLuint program, GLsizei uniformCount, const GLuint *uniformIndices, GLenum pname, GLint *params) const; + void glGetActiveUniformName(GLuint program, GLuint uniformIndex, GLsizei bufSize, GLsizei *length, GLchar *uniformName) const; + GLuint glGetUniformBlockIndex(GLuint program, const GLchar *uniformBlockName) const; + void glGetActiveUniformBlockiv(GLuint program, GLuint uniformBlockIndex, GLenum pname, GLint *params) const; + void glGetActiveUniformBlockName(GLuint program, GLuint uniformBlockIndex, GLsizei bufSize, GLsizei *length, GLchar *uniformBlockName) const; + void glUniformBlockBinding(GLuint program, GLuint uniformBlockIndex, GLuint uniformBlockBinding) const; + + // ARB_get_program_binary + void glGetProgramBinary(GLuint program, GLsizei bufSize, GLsizei *length, GLenum *binaryFormat, GLvoid *binary) const; + void glProgramBinary(GLuint program, GLenum binaryFormat, const GLvoid *binary, GLsizei length) const; + + // ARB_gpu_shader_fp64 + void glUniform1d( GLint location, GLdouble v0 ) const; + void glUniform2d( GLint location, GLdouble v0, GLdouble v1 ) const; + void glUniform3d( GLint location, GLdouble v0, GLdouble v1, GLdouble v2 ) const; + void glUniform4d( GLint location, GLdouble v0, GLdouble v1, GLdouble v2, GLdouble v3 ) const; + void glUniform1dv( GLint location, GLsizei count, const GLdouble *value ) const; + void glUniform2dv( GLint location, GLsizei count, const GLdouble *value ) const; + void glUniform3dv( GLint location, GLsizei count, const GLdouble *value ) const; + void glUniform4dv( GLint location, GLsizei count, const GLdouble *value ) const; + void glUniformMatrix2dv(GLint location, GLsizei count, GLboolean transpose, const GLdouble *value) const; + void glUniformMatrix3dv(GLint location, GLsizei count, GLboolean transpose, const GLdouble *value) const; + void glUniformMatrix4dv(GLint location, GLsizei count, GLboolean transpose, const GLdouble *value) const; + void glUniformMatrix2x3dv( GLint location, GLsizei count, GLboolean transpose, const GLdouble* value ) const; + void glUniformMatrix3x2dv( GLint location, GLsizei count, GLboolean transpose, const GLdouble* value ) const; + void glUniformMatrix2x4dv( GLint location, GLsizei count, GLboolean transpose, const GLdouble* value ) const; + void glUniformMatrix4x2dv( GLint location, GLsizei count, GLboolean transpose, const GLdouble* value ) const; + void glUniformMatrix3x4dv( GLint location, GLsizei count, GLboolean transpose, const GLdouble* value ) const; + void glUniformMatrix4x3dv( GLint location, GLsizei count, GLboolean transpose, const GLdouble* value ) const; + + // ARB_shader_atomic_counters + void glGetActiveAtomicCounterBufferiv( GLuint program, GLuint bufferIndex, GLenum pname, GLint* params ) const; + + // ARB_compute_shader + void glDispatchCompute( GLuint numGroupsX, GLuint numGroupsY, GLuint numGroupsZ ) const; + + protected: + ~GL2Extensions() {} + + float _glVersion; + float _glslLanguageVersion; + + bool _isShaderObjectsSupported; + bool _isVertexShaderSupported; + bool _isFragmentShaderSupported; + bool _isLanguage100Supported; + bool _isGeometryShader4Supported; + bool _areTessellationShadersSupported; + bool _isGpuShader4Supported; + bool _isUniformBufferObjectSupported; + bool _isGetProgramBinarySupported; + bool _isGpuShaderFp64Supported; + bool _isShaderAtomicCountersSupported; + + typedef void (GL_APIENTRY * BlendEquationSeparateProc)(GLenum modeRGB, GLenum modeAlpha); + typedef void (GL_APIENTRY * DrawBuffersProc)(GLsizei n, const GLenum *bufs); + typedef void (GL_APIENTRY * StencilOpSeparateProc)(GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass); + typedef void (GL_APIENTRY * StencilFuncSeparateProc)(GLenum frontfunc, GLenum backfunc, GLint ref, GLuint mask); + typedef void (GL_APIENTRY * StencilMaskSeparateProc)(GLenum face, GLuint mask); + typedef void (GL_APIENTRY * AttachShaderProc)(GLuint program, GLuint shader); + typedef void (GL_APIENTRY * BindAttribLocationProc)(GLuint program, GLuint index, const GLchar *name); + typedef void (GL_APIENTRY * CompileShaderProc)(GLuint shader); + typedef GLuint (GL_APIENTRY * CreateProgramProc)(void); + typedef GLuint (GL_APIENTRY * CreateShaderProc)(GLenum type); + typedef void (GL_APIENTRY * DeleteProgramProc)(GLuint program); + typedef void (GL_APIENTRY * DeleteObjectARBProc)(GLuint program); + typedef void (GL_APIENTRY * DeleteShaderProc)(GLuint shader); + typedef void (GL_APIENTRY * DetachShaderProc)(GLuint program, GLuint shader); + typedef void (GL_APIENTRY * DisableVertexAttribArrayProc)(GLuint index); + typedef void (GL_APIENTRY * EnableVertexAttribArrayProc)(GLuint index); + typedef void (GL_APIENTRY * GetActiveAttribProc)(GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name); + typedef void (GL_APIENTRY * GetActiveUniformProc)(GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name); + typedef void (GL_APIENTRY * GetAttachedShadersProc)(GLuint program, GLsizei maxCount, GLsizei *count, GLuint *obj); + typedef GLint (GL_APIENTRY * GetAttribLocationProc)(GLuint program, const GLchar *name); + typedef void (GL_APIENTRY * GetProgramivProc)(GLuint program, GLenum pname, GLint *params); + typedef void (GL_APIENTRY * GetObjectParameterivARBProc)(GLuint program, GLenum pname, GLint *params); + typedef void (GL_APIENTRY * GetProgramInfoLogProc)(GLuint program, GLsizei bufSize, GLsizei *length, GLchar *infoLog); + typedef void (GL_APIENTRY * GetInfoLogARBProc)(GLuint program, GLsizei bufSize, GLsizei *length, GLchar *infoLog); + typedef void (GL_APIENTRY * GetShaderivProc)(GLuint shader, GLenum pname, GLint *params); + typedef void (GL_APIENTRY * GetShaderInfoLogProc)(GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *infoLog); + typedef void (GL_APIENTRY * GetShaderSourceProc)(GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *source); + typedef GLint (GL_APIENTRY * GetUniformLocationProc)(GLuint program, const GLchar *name); + typedef void (GL_APIENTRY * GetUniformfvProc)(GLuint program, GLint location, GLfloat *params); + typedef void (GL_APIENTRY * GetUniformivProc)(GLuint program, GLint location, GLint *params); + typedef void (GL_APIENTRY * GetVertexAttribdvProc)(GLuint index, GLenum pname, GLdouble *params); + typedef void (GL_APIENTRY * GetVertexAttribfvProc)(GLuint index, GLenum pname, GLfloat *params); + typedef void (GL_APIENTRY * GetVertexAttribivProc)(GLuint index, GLenum pname, GLint *params); + typedef void (GL_APIENTRY * GetVertexAttribPointervProc)(GLuint index, GLenum pname, GLvoid* *pointer); + typedef GLboolean (GL_APIENTRY * IsProgramProc)(GLuint program); + typedef GLboolean (GL_APIENTRY * IsShaderProc)(GLuint shader); + typedef void (GL_APIENTRY * LinkProgramProc)(GLuint program); + typedef void (GL_APIENTRY * ShaderSourceProc)(GLuint shader, GLsizei count, const GLchar* *string, const GLint *length); + typedef void (GL_APIENTRY * UseProgramProc)(GLuint program); + typedef void (GL_APIENTRY * Uniform1fProc)(GLint location, GLfloat v0); + typedef void (GL_APIENTRY * Uniform2fProc)(GLint location, GLfloat v0, GLfloat v1); + typedef void (GL_APIENTRY * Uniform3fProc)(GLint location, GLfloat v0, GLfloat v1, GLfloat v2); + typedef void (GL_APIENTRY * Uniform4fProc)(GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); + typedef void (GL_APIENTRY * Uniform1iProc)(GLint location, GLint v0); + typedef void (GL_APIENTRY * Uniform2iProc)(GLint location, GLint v0, GLint v1); + typedef void (GL_APIENTRY * Uniform3iProc)(GLint location, GLint v0, GLint v1, GLint v2); + typedef void (GL_APIENTRY * Uniform4iProc)(GLint location, GLint v0, GLint v1, GLint v2, GLint v3); + typedef void (GL_APIENTRY * Uniform1fvProc)(GLint location, GLsizei count, const GLfloat *value); + typedef void (GL_APIENTRY * Uniform2fvProc)(GLint location, GLsizei count, const GLfloat *value); + typedef void (GL_APIENTRY * Uniform3fvProc)(GLint location, GLsizei count, const GLfloat *value); + typedef void (GL_APIENTRY * Uniform4fvProc)(GLint location, GLsizei count, const GLfloat *value); + typedef void (GL_APIENTRY * Uniform1ivProc)(GLint location, GLsizei count, const GLint *value); + typedef void (GL_APIENTRY * Uniform2ivProc)(GLint location, GLsizei count, const GLint *value); + typedef void (GL_APIENTRY * Uniform3ivProc)(GLint location, GLsizei count, const GLint *value); + typedef void (GL_APIENTRY * Uniform4ivProc)(GLint location, GLsizei count, const GLint *value); + typedef void (GL_APIENTRY * UniformMatrix2fvProc)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); + typedef void (GL_APIENTRY * UniformMatrix3fvProc)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); + typedef void (GL_APIENTRY * UniformMatrix4fvProc)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); + typedef void (GL_APIENTRY * ValidateProgramProc)(GLuint program); + typedef void (GL_APIENTRY * VertexAttrib1dProc)(GLuint index, GLdouble x); + typedef void (GL_APIENTRY * VertexAttrib1dvProc)(GLuint index, const GLdouble *v); + typedef void (GL_APIENTRY * VertexAttrib1fProc)(GLuint index, GLfloat x); + typedef void (GL_APIENTRY * VertexAttrib1fvProc)(GLuint index, const GLfloat *v); + typedef void (GL_APIENTRY * VertexAttrib1sProc)(GLuint index, GLshort x); + typedef void (GL_APIENTRY * VertexAttrib1svProc)(GLuint index, const GLshort *v); + typedef void (GL_APIENTRY * VertexAttrib2dProc)(GLuint index, GLdouble x, GLdouble y); + typedef void (GL_APIENTRY * VertexAttrib2dvProc)(GLuint index, const GLdouble *v); + typedef void (GL_APIENTRY * VertexAttrib2fProc)(GLuint index, GLfloat x, GLfloat y); + typedef void (GL_APIENTRY * VertexAttrib2fvProc)(GLuint index, const GLfloat *v); + typedef void (GL_APIENTRY * VertexAttrib2sProc)(GLuint index, GLshort x, GLshort y); + typedef void (GL_APIENTRY * VertexAttrib2svProc)(GLuint index, const GLshort *v); + typedef void (GL_APIENTRY * VertexAttrib3dProc)(GLuint index, GLdouble x, GLdouble y, GLdouble z); + typedef void (GL_APIENTRY * VertexAttrib3dvProc)(GLuint index, const GLdouble *v); + typedef void (GL_APIENTRY * VertexAttrib3fProc)(GLuint index, GLfloat x, GLfloat y, GLfloat z); + typedef void (GL_APIENTRY * VertexAttrib3fvProc)(GLuint index, const GLfloat *v); + typedef void (GL_APIENTRY * VertexAttrib3sProc)(GLuint index, GLshort x, GLshort y, GLshort z); + typedef void (GL_APIENTRY * VertexAttrib3svProc)(GLuint index, const GLshort *v); + typedef void (GL_APIENTRY * VertexAttrib4NbvProc)(GLuint index, const GLbyte *v); + typedef void (GL_APIENTRY * VertexAttrib4NivProc)(GLuint index, const GLint *v); + typedef void (GL_APIENTRY * VertexAttrib4NsvProc)(GLuint index, const GLshort *v); + typedef void (GL_APIENTRY * VertexAttrib4NubProc)(GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w); + typedef void (GL_APIENTRY * VertexAttrib4NubvProc)(GLuint index, const GLubyte *v); + typedef void (GL_APIENTRY * VertexAttrib4NuivProc)(GLuint index, const GLuint *v); + typedef void (GL_APIENTRY * VertexAttrib4NusvProc)(GLuint index, const GLushort *v); + typedef void (GL_APIENTRY * VertexAttrib4bvProc)(GLuint index, const GLbyte *v); + typedef void (GL_APIENTRY * VertexAttrib4dProc)(GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); + typedef void (GL_APIENTRY * VertexAttrib4dvProc)(GLuint index, const GLdouble *v); + typedef void (GL_APIENTRY * VertexAttrib4fProc)(GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); + typedef void (GL_APIENTRY * VertexAttrib4fvProc)(GLuint index, const GLfloat *v); + typedef void (GL_APIENTRY * VertexAttrib4ivProc)(GLuint index, const GLint *v); + typedef void (GL_APIENTRY * VertexAttrib4sProc)(GLuint index, GLshort x, GLshort y, GLshort z, GLshort w); + typedef void (GL_APIENTRY * VertexAttrib4svProc)(GLuint index, const GLshort *v); + typedef void (GL_APIENTRY * VertexAttrib4ubvProc)(GLuint index, const GLubyte *v); + typedef void (GL_APIENTRY * VertexAttrib4uivProc)(GLuint index, const GLuint *v); + typedef void (GL_APIENTRY * VertexAttrib4usvProc)(GLuint index, const GLushort *v); + typedef void (GL_APIENTRY * VertexAttribPointerProc)(GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid *pointer); + typedef void (GL_APIENTRY * VertexAttribDivisorProc)(GLuint index, GLuint divisor); + typedef void (GL_APIENTRY * UniformMatrix2x3fvProc)( GLint location, GLsizei count, GLboolean transpose, const GLfloat* value ); + typedef void (GL_APIENTRY * UniformMatrix3x2fvProc)( GLint location, GLsizei count, GLboolean transpose, const GLfloat* value ); + typedef void (GL_APIENTRY * UniformMatrix2x4fvProc)( GLint location, GLsizei count, GLboolean transpose, const GLfloat* value ); + typedef void (GL_APIENTRY * UniformMatrix4x2fvProc)( GLint location, GLsizei count, GLboolean transpose, const GLfloat* value ); + typedef void (GL_APIENTRY * UniformMatrix3x4fvProc)( GLint location, GLsizei count, GLboolean transpose, const GLfloat* value ); + typedef void (GL_APIENTRY * UniformMatrix4x3fvProc)( GLint location, GLsizei count, GLboolean transpose, const GLfloat* value ); + typedef void (GL_APIENTRY * ProgramParameteriProc)( GLuint program, GLenum pname, GLint value ); + typedef void (GL_APIENTRY * FramebufferTextureProc)( GLenum target, GLenum attachment, GLuint texture, GLint level ); + typedef void (GL_APIENTRY * FramebufferTextureLayerProc)( GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer ); + typedef void (GL_APIENTRY * FramebufferTextureFaceProc)( GLenum target, GLenum attachment, GLuint texture, GLint level, GLenum face ); + typedef void (GL_APIENTRY * PatchParameteriProc)( GLenum pname, GLint value ); + typedef void (GL_APIENTRY * PatchParameterfvProc)( GLenum pname, const GLfloat* values ); + typedef void (GL_APIENTRY * GetUniformuivProc)( GLuint program, GLint location, GLuint* params ); + typedef void (GL_APIENTRY * BindFragDataLocationProc)( GLuint program, GLuint color, const GLchar* name ); + typedef GLint (GL_APIENTRY * GetFragDataLocationProc)( GLuint program, const GLchar* name ); + typedef void (GL_APIENTRY * Uniform1uiProc)( GLint location, GLuint v0 ); + typedef void (GL_APIENTRY * Uniform2uiProc)( GLint location, GLuint v0, GLuint v1 ); + typedef void (GL_APIENTRY * Uniform3uiProc)( GLint location, GLuint v0, GLuint v1, GLuint v2 ); + typedef void (GL_APIENTRY * Uniform4uiProc)( GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3 ); + typedef void (GL_APIENTRY * Uniform1uivProc)( GLint location, GLsizei count, const GLuint *value ); + typedef void (GL_APIENTRY * Uniform2uivProc)( GLint location, GLsizei count, const GLuint *value ); + typedef void (GL_APIENTRY * Uniform3uivProc)( GLint location, GLsizei count, const GLuint *value ); + typedef void (GL_APIENTRY * Uniform4uivProc)( GLint location, GLsizei count, const GLuint *value ); + typedef GLuint (GL_APIENTRY * GetHandleProc) (GLenum pname); + typedef void (GL_APIENTRY * GetUniformIndicesProc)(GLuint program, GLsizei uniformCount, const GLchar* *uniformNames, GLuint *uniformIndices); + typedef void (GL_APIENTRY * GetActiveUniformsivProc)(GLuint program, GLsizei uniformCount, const GLuint *uniformIndices, GLenum pname, GLint *params); + typedef void (GL_APIENTRY * GetActiveUniformNameProc)(GLuint program, GLuint uniformIndex, GLsizei bufSize, GLsizei *length, GLchar *uniformName); + typedef GLuint (GL_APIENTRY * GetUniformBlockIndexProc)(GLuint program, const GLchar *uniformBlockName); + typedef void (GL_APIENTRY * GetActiveUniformBlockivProc)(GLuint program, GLuint uniformBlockIndex, GLenum pname, GLint *params); + typedef void (GL_APIENTRY * GetActiveUniformBlockNameProc)(GLuint program, GLuint uniformBlockIndex, GLsizei bufSize, GLsizei *length, GLchar *uniformBlockName); + typedef void (GL_APIENTRY * UniformBlockBindingProc)(GLuint program, GLuint uniformBlockIndex, GLuint uniformBlockBinding); + typedef void (GL_APIENTRY * GetProgramBinaryProc)(GLuint program, GLsizei bufSize, GLsizei *length, GLenum *binaryFormat, GLvoid *binary); + typedef void (GL_APIENTRY * ProgramBinaryProc)(GLuint program, GLenum binaryFormat, const GLvoid *binary, GLsizei length); + typedef void (GL_APIENTRY * Uniform1dProc)(GLint location, GLdouble v0); + typedef void (GL_APIENTRY * Uniform2dProc)(GLint location, GLdouble v0, GLdouble v1); + typedef void (GL_APIENTRY * Uniform3dProc)(GLint location, GLdouble v0, GLdouble v1, GLdouble v2); + typedef void (GL_APIENTRY * Uniform4dProc)(GLint location, GLdouble v0, GLdouble v1, GLdouble v2, GLdouble v3); + typedef void (GL_APIENTRY * Uniform1dvProc)(GLint location, GLsizei count, const GLdouble *value); + typedef void (GL_APIENTRY * Uniform2dvProc)(GLint location, GLsizei count, const GLdouble *value); + typedef void (GL_APIENTRY * Uniform3dvProc)(GLint location, GLsizei count, const GLdouble *value); + typedef void (GL_APIENTRY * Uniform4dvProc)(GLint location, GLsizei count, const GLdouble *value); + typedef void (GL_APIENTRY * UniformMatrix2dvProc)(GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); + typedef void (GL_APIENTRY * UniformMatrix3dvProc)(GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); + typedef void (GL_APIENTRY * UniformMatrix4dvProc)(GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); + typedef void (GL_APIENTRY * UniformMatrix2x3dvProc)( GLint location, GLsizei count, GLboolean transpose, const GLdouble* value ); + typedef void (GL_APIENTRY * UniformMatrix3x2dvProc)( GLint location, GLsizei count, GLboolean transpose, const GLdouble* value ); + typedef void (GL_APIENTRY * UniformMatrix2x4dvProc)( GLint location, GLsizei count, GLboolean transpose, const GLdouble* value ); + typedef void (GL_APIENTRY * UniformMatrix4x2dvProc)( GLint location, GLsizei count, GLboolean transpose, const GLdouble* value ); + typedef void (GL_APIENTRY * UniformMatrix3x4dvProc)( GLint location, GLsizei count, GLboolean transpose, const GLdouble* value ); + typedef void (GL_APIENTRY * UniformMatrix4x3dvProc)( GLint location, GLsizei count, GLboolean transpose, const GLdouble* value ); + typedef void (GL_APIENTRY * GetActiveAtomicCounterBufferivProc)( GLuint program, GLuint bufferIndex, GLenum pname, GLint* params ); + typedef void (GL_APIENTRY * DispatchComputeProc)( GLuint numGroupsX, GLuint numGroupsY, GLuint numGroupsZ ); + + BlendEquationSeparateProc _glBlendEquationSeparate; + DrawBuffersProc _glDrawBuffers; + StencilOpSeparateProc _glStencilOpSeparate; + StencilFuncSeparateProc _glStencilFuncSeparate; + StencilMaskSeparateProc _glStencilMaskSeparate; + AttachShaderProc _glAttachShader; + BindAttribLocationProc _glBindAttribLocation; + CompileShaderProc _glCompileShader; + CreateProgramProc _glCreateProgram; + CreateShaderProc _glCreateShader; + DeleteProgramProc _glDeleteProgram; + DeleteShaderProc _glDeleteShader; + DetachShaderProc _glDetachShader; + DisableVertexAttribArrayProc _glDisableVertexAttribArray; + EnableVertexAttribArrayProc _glEnableVertexAttribArray; + GetActiveAttribProc _glGetActiveAttrib; + GetActiveUniformProc _glGetActiveUniform; + GetAttachedShadersProc _glGetAttachedShaders; + GetAttribLocationProc _glGetAttribLocation; + GetProgramivProc _glGetProgramiv; + GetProgramInfoLogProc _glGetProgramInfoLog; + GetShaderivProc _glGetShaderiv; + GetShaderInfoLogProc _glGetShaderInfoLog; + GetShaderSourceProc _glGetShaderSource; + GetUniformLocationProc _glGetUniformLocation; + GetUniformfvProc _glGetUniformfv; + GetUniformivProc _glGetUniformiv; + GetVertexAttribdvProc _glGetVertexAttribdv; + GetVertexAttribfvProc _glGetVertexAttribfv; + GetVertexAttribivProc _glGetVertexAttribiv; + GetVertexAttribPointervProc _glGetVertexAttribPointerv; + IsProgramProc _glIsProgram; + IsShaderProc _glIsShader; + LinkProgramProc _glLinkProgram; + ShaderSourceProc _glShaderSource; + UseProgramProc _glUseProgram; + Uniform1fProc _glUniform1f; + Uniform2fProc _glUniform2f; + Uniform3fProc _glUniform3f; + Uniform4fProc _glUniform4f; + Uniform1iProc _glUniform1i; + Uniform2iProc _glUniform2i; + Uniform3iProc _glUniform3i; + Uniform4iProc _glUniform4i; + Uniform1fvProc _glUniform1fv; + Uniform2fvProc _glUniform2fv; + Uniform3fvProc _glUniform3fv; + Uniform4fvProc _glUniform4fv; + Uniform1ivProc _glUniform1iv; + Uniform2ivProc _glUniform2iv; + Uniform3ivProc _glUniform3iv; + Uniform4ivProc _glUniform4iv; + UniformMatrix2fvProc _glUniformMatrix2fv; + UniformMatrix3fvProc _glUniformMatrix3fv; + UniformMatrix4fvProc _glUniformMatrix4fv; + ValidateProgramProc _glValidateProgram; + VertexAttrib1dProc _glVertexAttrib1d; + VertexAttrib1dvProc _glVertexAttrib1dv; + VertexAttrib1fProc _glVertexAttrib1f; + VertexAttrib1fvProc _glVertexAttrib1fv; + VertexAttrib1sProc _glVertexAttrib1s; + VertexAttrib1svProc _glVertexAttrib1sv; + VertexAttrib2dProc _glVertexAttrib2d; + VertexAttrib2dvProc _glVertexAttrib2dv; + VertexAttrib2fProc _glVertexAttrib2f; + VertexAttrib2fvProc _glVertexAttrib2fv; + VertexAttrib2sProc _glVertexAttrib2s; + VertexAttrib2svProc _glVertexAttrib2sv; + VertexAttrib3dProc _glVertexAttrib3d; + VertexAttrib3dvProc _glVertexAttrib3dv; + VertexAttrib3fProc _glVertexAttrib3f; + VertexAttrib3fvProc _glVertexAttrib3fv; + VertexAttrib3sProc _glVertexAttrib3s; + VertexAttrib3svProc _glVertexAttrib3sv; + VertexAttrib4NbvProc _glVertexAttrib4Nbv; + VertexAttrib4NivProc _glVertexAttrib4Niv; + VertexAttrib4NsvProc _glVertexAttrib4Nsv; + VertexAttrib4NubProc _glVertexAttrib4Nub; + VertexAttrib4NubvProc _glVertexAttrib4Nubv; + VertexAttrib4NuivProc _glVertexAttrib4Nuiv; + VertexAttrib4NusvProc _glVertexAttrib4Nusv; + VertexAttrib4bvProc _glVertexAttrib4bv; + VertexAttrib4dProc _glVertexAttrib4d; + VertexAttrib4dvProc _glVertexAttrib4dv; + VertexAttrib4fProc _glVertexAttrib4f; + VertexAttrib4fvProc _glVertexAttrib4fv; + VertexAttrib4ivProc _glVertexAttrib4iv; + VertexAttrib4sProc _glVertexAttrib4s; + VertexAttrib4svProc _glVertexAttrib4sv; + VertexAttrib4ubvProc _glVertexAttrib4ubv; + VertexAttrib4uivProc _glVertexAttrib4uiv; + VertexAttrib4usvProc _glVertexAttrib4usv; + VertexAttribPointerProc _glVertexAttribPointer; + VertexAttribDivisorProc _glVertexAttribDivisor; + + GetInfoLogARBProc _glGetInfoLogARB; + GetObjectParameterivARBProc _glGetObjectParameterivARB; + DeleteObjectARBProc _glDeleteObjectARB; + GetHandleProc _glGetHandleARB; + + // GL 2.1 + UniformMatrix2x3fvProc _glUniformMatrix2x3fv; + UniformMatrix3x2fvProc _glUniformMatrix3x2fv; + UniformMatrix2x4fvProc _glUniformMatrix2x4fv; + UniformMatrix4x2fvProc _glUniformMatrix4x2fv; + UniformMatrix3x4fvProc _glUniformMatrix3x4fv; + UniformMatrix4x3fvProc _glUniformMatrix4x3fv; + + // EXT_geometry_shader4 + ProgramParameteriProc _glProgramParameteri; + FramebufferTextureProc _glFramebufferTexture; + FramebufferTextureLayerProc _glFramebufferTextureLayer; + FramebufferTextureFaceProc _glFramebufferTextureFace; + + // ARB_tesselation_shader + PatchParameteriProc _glPatchParameteri; + PatchParameterfvProc _glPatchParameterfv; + + // EXT_gpu_shader4 + GetUniformuivProc _glGetUniformuiv; + BindFragDataLocationProc _glBindFragDataLocation; + GetFragDataLocationProc _glGetFragDataLocation; + Uniform1uiProc _glUniform1ui; + Uniform2uiProc _glUniform2ui; + Uniform3uiProc _glUniform3ui; + Uniform4uiProc _glUniform4ui; + Uniform1uivProc _glUniform1uiv; + Uniform2uivProc _glUniform2uiv; + Uniform3uivProc _glUniform3uiv; + Uniform4uivProc _glUniform4uiv; + + // ARB_uniform_buffer_object + GetUniformIndicesProc _glGetUniformIndices; + GetActiveUniformsivProc _glGetActiveUniformsiv; + GetActiveUniformNameProc _glGetActiveUniformName; + GetUniformBlockIndexProc _glGetUniformBlockIndex; + GetActiveUniformBlockivProc _glGetActiveUniformBlockiv; + GetActiveUniformBlockNameProc _glGetActiveUniformBlockName; + UniformBlockBindingProc _glUniformBlockBinding; + + // ARB_get_program_binary + GetProgramBinaryProc _glGetProgramBinary; + ProgramBinaryProc _glProgramBinary; + + // ARB_gpu_shader_fp64 + Uniform1dProc _glUniform1d; + Uniform2dProc _glUniform2d; + Uniform3dProc _glUniform3d; + Uniform4dProc _glUniform4d; + Uniform1dvProc _glUniform1dv; + Uniform2dvProc _glUniform2dv; + Uniform3dvProc _glUniform3dv; + Uniform4dvProc _glUniform4dv; + UniformMatrix2dvProc _glUniformMatrix2dv; + UniformMatrix3dvProc _glUniformMatrix3dv; + UniformMatrix4dvProc _glUniformMatrix4dv; + UniformMatrix2x3dvProc _glUniformMatrix2x3dv; + UniformMatrix3x2dvProc _glUniformMatrix3x2dv; + UniformMatrix2x4dvProc _glUniformMatrix2x4dv; + UniformMatrix4x2dvProc _glUniformMatrix4x2dv; + UniformMatrix3x4dvProc _glUniformMatrix3x4dv; + UniformMatrix4x3dvProc _glUniformMatrix4x3dv; + + // ARB_shader_atomic_counters + GetActiveAtomicCounterBufferivProc _glGetActiveAtomicCounterBufferiv; + + // ARB_compute_shader + DispatchComputeProc _glDispatchCompute; +}; + +} + +#endif diff --git a/libs/include/android/osg/GLBeginEndAdapter b/libs/include/android/osg/GLBeginEndAdapter new file mode 100755 index 0000000..2cee4ee --- /dev/null +++ b/libs/include/android/osg/GLBeginEndAdapter @@ -0,0 +1,174 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_GLBeginEndAdapter +#define OSG_GLBeginEndAdapter 1 + +#include +#include +#include + +#ifndef GL_TEXTURE0 +#define GL_TEXTURE0 0x84C0 +#endif + +namespace osg { + +// forward declare +class State; + +/** A class adapting OpenGL 1.0 glBegin()/glEnd() style code to vertex array based code */ +class OSG_EXPORT GLBeginEndAdapter +{ + public: + + GLBeginEndAdapter(State* state=0); + + void setState(State* state) { _state = state; } + State* getState() { return _state; } + const State* getState() const { return _state; } + + enum MatrixMode + { + APPLY_LOCAL_MATRICES_TO_VERTICES, + APPLY_LOCAL_MATRICES_TO_MODELVIEW + }; + + void setMatrixMode(MatrixMode mode) { _mode = mode; } + MatrixMode setMatrixMode() const { return _mode; } + + void PushMatrix(); + void PopMatrix(); + + void LoadIdentity(); + void LoadMatrixd(const GLdouble* m); + void MultMatrixd(const GLdouble* m); + + void Translatef(GLfloat x, GLfloat y, GLfloat z) { Translated(x,y,z); } + void Scalef(GLfloat x, GLfloat y, GLfloat z) { Scaled(x,y,z); } + void Rotatef(GLfloat angle, GLfloat x, GLfloat y, GLfloat z) { Rotated(angle,x,y,z); } + + void Translated(GLdouble x, GLdouble y, GLdouble z); + void Scaled(GLdouble x, GLdouble y, GLdouble z); + void Rotated(GLdouble angle, GLdouble x, GLdouble y, GLdouble z); + + void Vertex3f(GLfloat x, GLfloat y, GLfloat z); + void Vertex3fv(const GLfloat* v) { Vertex3f(v[0], v[1], v[2]); } + + void Vertex3dv(GLdouble x, GLdouble y, GLdouble z) { Vertex3f(x,y,z); } + void Vertex3dv(const GLdouble* v) { Vertex3f(v[0], v[1], v[2]); } + + void Color4f(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha) + { + _overallColorAssigned = true; + _colorAssigned = true; + _color.set(red,green,blue,alpha); + } + + void Color3fv(const GLfloat* c) { Color4f(c[0], c[1], c[2], 1); } + void Color4fv(const GLfloat* c) { Color4f(c[0], c[1], c[2], c[3]); } + void Color4ubv(const GLubyte* c) { const float div = 1.0f/255.0f; Color4f(float(c[0])*div, float(c[1])*div, float(c[2])*div, float(c[3])*div); } + + void Normal3f(GLfloat x, GLfloat y, GLfloat z) + { + _overallNormalAssigned = true; + _normalAssigned = true; + _normal.set(x,y,z); + } + + void Normal3fv(const GLfloat* n) { Normal3f(n[0], n[1], n[2]); } + + void TexCoord1f(GLfloat x) { MultiTexCoord4f(GL_TEXTURE0, x, 0.0f, 0.0f, 1.0f); } + void TexCoord1fv(const GLfloat* tc) { MultiTexCoord4f(GL_TEXTURE0, tc[0], 0.0f, 0.0f, 1.0f); } + + void TexCoord2f(GLfloat x, GLfloat y) { MultiTexCoord4f(GL_TEXTURE0, x, y, 0.0f, 1.0f); } + void TexCoord2fv(const GLfloat* tc) { MultiTexCoord4f(GL_TEXTURE0, tc[0], tc[1], 0.0f, 1.0f); } + + void TexCoord3f(GLfloat x, GLfloat y, GLfloat z) { MultiTexCoord4f(GL_TEXTURE0, x, y, z, 1.0f); } + void TexCoord3fv(const GLfloat* tc) { MultiTexCoord4f(GL_TEXTURE0, tc[0], tc[1], tc[2], 1.0f); } + + void TexCoord4f(GLfloat x, GLfloat y, GLfloat z, GLfloat w) { MultiTexCoord4f(GL_TEXTURE0, x, y, z, w); } + void TexCoord4fv(const GLfloat* tc) { MultiTexCoord4f(GL_TEXTURE0, tc[0], tc[1], tc[2], tc[3]); } + + void MultiTexCoord1f(GLenum target, GLfloat x) { MultiTexCoord4f(target, x, 0.0f, 0.0f, 1.0f); } + void MultiTexCoord1fv(GLenum target, const GLfloat* tc) { MultiTexCoord4f(target, tc[0], 0.0f, 0.0f, 1.0f); } + + void MultiTexCoord2f(GLenum target, GLfloat x, GLfloat y) { MultiTexCoord4f(target, x, y, 0.0f, 1.0f); } + void MultiTexCoord2fv(GLenum target, const GLfloat* tc) { MultiTexCoord4f(target, tc[0],tc[1], 0.0f, 1.0f); } + + void MultiTexCoord3f(GLenum target, GLfloat x, GLfloat y, GLfloat z) {MultiTexCoord4f(target, x, y, z, 1.0f); } + void MultiTexCoord3fv(GLenum target, const GLfloat* tc) { MultiTexCoord4f(target, tc[0], tc[1], tc[2], 1.0f); } + + void MultiTexCoord4f(GLenum target, GLfloat x, GLfloat y, GLfloat z, GLfloat w); + void MultiTexCoord4fv(GLenum target, const GLfloat* tc) { MultiTexCoord4f(target, tc[0], tc[1], tc[2], tc[3]); } + + void VertexAttrib1f(GLuint unit, GLfloat x) { VertexAttrib4f(unit, x, 0.0f, 0.0f, 0.0f); } + void VertexAttrib1fv(GLuint unit, const GLfloat* tc) { VertexAttrib4f(unit, tc[0], 0.0f, 0.0f, 0.0f); } + + void VertexAttrib2f(GLuint unit, GLfloat x, GLfloat y) { VertexAttrib4f(unit, x, y, 0.0f, 0.0f); } + void VertexAttrib2fv(GLuint unit, const GLfloat* tc) { VertexAttrib4f(unit, tc[0],tc[1], 0.0f, 0.0f); } + + void VertexAttrib3f(GLuint unit, GLfloat x, GLfloat y, GLfloat z) {VertexAttrib4f(unit, x, y, z, 0.0f); } + void VertexAttrib3fv(GLuint unit, const GLfloat* tc) { VertexAttrib4f(unit, tc[0], tc[1], tc[2], 0.0f); } + + void VertexAttrib4f(GLuint unit, GLfloat x, GLfloat y, GLfloat z, GLfloat w); + void VertexAttrib4fv(GLuint unit, const GLfloat* tc) { VertexAttrib4f(unit, tc[0], tc[1], tc[2], tc[3]); } + + void Begin(GLenum mode); + void End(); + + void reset(); + + protected: + + State* _state; + + MatrixMode _mode; + + typedef std::list MatrixStack; + MatrixStack _matrixStack; + + bool _normalAssigned; + osg::Vec3f _normal; + + bool _colorAssigned; + osg::Vec4f _color; + + bool _overallNormalAssigned; + bool _overallColorAssigned; + osg::Vec3f _overallNormal; + osg::Vec4f _overallColor; + + typedef std::vector AssignedList; + typedef std::vector VertexList; + + AssignedList _texCoordAssignedList; + VertexList _texCoordList; + + AssignedList _vertexAttribAssignedList; + VertexList _vertexAttribList; + + + typedef std::vector< osg::ref_ptr > VertexArrayList; + + GLenum _primitiveMode; + osg::ref_ptr _vertices; + osg::ref_ptr _normals; + osg::ref_ptr _colors; + VertexArrayList _texCoordsList; + VertexArrayList _vertexAttribsList; +}; + +} + +#endif diff --git a/libs/include/android/osg/GLExtensions b/libs/include/android/osg/GLExtensions new file mode 100755 index 0000000..cac563a --- /dev/null +++ b/libs/include/android/osg/GLExtensions @@ -0,0 +1,155 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_GLEXTENSIONS +#define OSG_GLEXTENSIONS 1 + +#include +#include +#include +#include + + +namespace osg { + +/** Return floating-point OpenGL version number. + * Note: Must only be called within a valid OpenGL context, + * undefined behavior may occur otherwise. +*/ +extern OSG_EXPORT float getGLVersionNumber(); + +/** Return true if "extension" is contained in "extensionString". +*/ +extern OSG_EXPORT bool isExtensionInExtensionString(const char *extension, const char *extensionString); + +/** Return true if OpenGL "extension" is supported. + * Note: Must only be called within a valid OpenGL context, + * undefined behavior may occur otherwise. +*/ +extern OSG_EXPORT bool isGLExtensionSupported(unsigned int contextID, const char *extension); + +/** Return true if OpenGL "extension" or minimum OpenGL version number is supported. + * Note: Must only be called within a valid OpenGL context, + * undefined behavior may occur otherwise. +*/ +extern OSG_EXPORT bool isGLExtensionOrVersionSupported(unsigned int contextID, const char *extension, float requiredGlVersion); + +/** Return the address of the specified OpenGL function. + * Return NULL if function not supported by OpenGL library. + * Note, glGLExtensionFuncPtr is declared inline so that the code + * is compiled locally to the calling code. This should get by Windows' + * dumb implementation of having different GL function ptr's for each + * library when linked to it. +*/ +extern OSG_EXPORT void* getGLExtensionFuncPtr(const char *funcName); + +/** Set a list of extensions to disable for different OpenGL renderers. This allows + * OSG applications to work around OpenGL drivers' bugs which are due to problematic extension support. + * The format of the string is: + * "GLRendererString : ExtensionName, ExtensionName; GLRenderString2 : ExtensionName;" + * An example of is : "SUN_XVR1000:GL_EXT_texture_filter_anisotropic" + * The default setting of GLExtensionDisableString is obtained from the OSG_GL_EXTENSION_DISABLE + * environmental variable. +*/ +extern OSG_EXPORT void setGLExtensionDisableString(const std::string& disableString); + +/** Get the list of extensions that are disabled for various OpenGL renderers. */ +extern OSG_EXPORT std::string& getGLExtensionDisableString(); + +/** Return the address of the specified OpenGL function. If not found then + * check a second function name, if this fails then return NULL as function is + * not supported by OpenGL library. This is used for checking something + * like glActiveTexture (which is in OGL1.3) or glActiveTextureARB. +*/ +inline void* getGLExtensionFuncPtr(const char *funcName,const char *fallbackFuncName) +{ + void* ptr = getGLExtensionFuncPtr(funcName); + if (ptr) return ptr; + return getGLExtensionFuncPtr(fallbackFuncName); +} + +/** Return the address of the specified OpenGL function. If not found then + * check a second function name, if this fails then return NULL as function is + * not supported by OpenGL library. This is used for checking something + * like glActiveTexture (which is in OGL1.3) or glActiveTextureARB. +*/ +inline void* getGLExtensionFuncPtr(const char *funcName1, const char *funcName2, const char *funcName3) +{ + void* ptr = getGLExtensionFuncPtr(funcName1); + if (ptr) return ptr; + + ptr = getGLExtensionFuncPtr(funcName2); + if (ptr) return ptr; + + return getGLExtensionFuncPtr(funcName3); +} + +template +T convertPointerType(R src) +{ + T dest; + memcpy(&dest, &src, sizeof(src)); + return dest; +} + +template +bool setGLExtensionFuncPtr(T& t, const char* str1) +{ + void* data = osg::getGLExtensionFuncPtr(str1); + if (data) + { + memcpy(&t, &data, sizeof(T)); + return true; + } + else + { + t = 0; + return false; + } +} + +template +bool setGLExtensionFuncPtr(T& t, const char* str1, const char* str2) +{ + void* data = osg::getGLExtensionFuncPtr(str1,str2); + if (data) + { + memcpy(&t, &data, sizeof(T)); + return true; + } + else + { + t = 0; + return false; + } +} + +template +bool setGLExtensionFuncPtr(T& t, const char* str1, const char* str2, const char* str3) +{ + void* data = osg::getGLExtensionFuncPtr(str1,str2,str3); + if (data) + { + memcpy(&t, &data, sizeof(T)); + return true; + } + else + { + t = 0; + return false; + } +} + +} + +#endif diff --git a/libs/include/android/osg/GLObjects b/libs/include/android/osg/GLObjects new file mode 100755 index 0000000..55be131 --- /dev/null +++ b/libs/include/android/osg/GLObjects @@ -0,0 +1,42 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_GLOBJECTS +#define OSG_GLOBJECTS 1 + +#include + +namespace osg { + +/** Flush all deleted OpenGL objects within the specified availableTime. + * Note, must be called from a thread which has current the graphics context associated with contextID. */ +extern OSG_EXPORT void flushDeletedGLObjects(unsigned int contextID, double currentTime, double& availableTime); + +/** Flush all deleted OpenGL objects. + * Note, must be called from a thread which has current the graphics context associated with contextID. */ +extern OSG_EXPORT void flushAllDeletedGLObjects(unsigned int contextID); + +/** Do a GL delete all OpenGL objects. + * Note, must be called from a thread which has current the graphics context associated with contextID. */ +extern OSG_EXPORT void deleteAllGLObjects(unsigned int contextID); + +/** Discard all OpenGL objects. + * Note, unlike deleteAllGLjects discard does not + * do any OpenGL calls so can be called from any thread, but as a consequence it + * also doesn't remove the associated OpenGL resource so discard should only be + * called when the associated graphics context is being/has been closed. */ +extern OSG_EXPORT void discardAllGLObjects(unsigned int contextID); + +} + +#endif diff --git a/libs/include/android/osg/GLU b/libs/include/android/osg/GLU new file mode 100755 index 0000000..27fd7c8 --- /dev/null +++ b/libs/include/android/osg/GLU @@ -0,0 +1,186 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_GLU +#define OSG_GLU 1 + +#include + +namespace osg +{ + +/* Pixel storage modes, used by gluScaleImage */ +struct OSG_EXPORT PixelStorageModes +{ + // sets defaults as per glGet docs in OpenGL red book + PixelStorageModes(); + + // use glGet's to retrieve all the current settings + void retrieveStoreModes(); + + // use glGet's to retrieve all the current 3D settings + void retrieveStoreModes3D(); + + GLint pack_alignment; + GLint pack_row_length; + GLint pack_skip_rows; + GLint pack_skip_pixels; + GLint pack_lsb_first; + GLint pack_swap_bytes; + GLint pack_skip_images; + GLint pack_image_height; + + GLint unpack_alignment; + GLint unpack_row_length; + GLint unpack_skip_rows; + GLint unpack_skip_pixels; + GLint unpack_lsb_first; + GLint unpack_swap_bytes; + GLint unpack_skip_images; + GLint unpack_image_height; +} ; + +extern OSG_EXPORT const GLubyte * gluErrorString (GLenum error); + +/** OSG specific gluScaleImage function that allows you to pass in the PixelStoreModes, which + * enables the code to avoid glGet's that are associated with the conventional gluScaleImage function. + * Avoiding glGet's allows this gluScaleImage function to be called at any time, from any thread, there + * is no need to have a graphics context current.*/ +extern OSG_EXPORT GLint gluScaleImage (PixelStorageModes* psm, GLenum format, GLsizei wIn, GLsizei hIn, GLenum typeIn, const void *dataIn, GLsizei wOut, GLsizei hOut, GLenum typeOut, GLvoid* dataOut); + +/** Traditional GLU gluScaleImage function that sets up the PixelStoreModes automatically by doing glGets.; + * The use of glGet's means that you can only call this function from a thread with a valid graphics context. + * The use of glGet's will also result in lower performance due to the round trip to the OpenGL driver.*/ +extern OSG_EXPORT GLint gluScaleImage (GLenum format, GLsizei wIn, GLsizei hIn, GLenum typeIn, const void *dataIn, GLsizei wOut, GLsizei hOut, GLenum typeOut, GLvoid* dataOut); + +extern OSG_EXPORT GLint gluBuild1DMipmapLevels (GLenum target, GLint internalFormat, GLsizei width, GLenum format, GLenum type, GLint level, GLint base, GLint max, const void *data); +extern OSG_EXPORT GLint gluBuild1DMipmaps (GLenum target, GLint internalFormat, GLsizei width, GLenum format, GLenum type, const void *data); +extern OSG_EXPORT GLint gluBuild2DMipmapLevels (GLenum target, GLint internalFormat, GLsizei width, GLsizei height, GLenum format, GLenum type, GLint level, GLint base, GLint max, const void *data); +extern OSG_EXPORT GLint gluBuild2DMipmaps (GLenum target, GLint internalFormat, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *data); + +typedef void (GL_APIENTRY * GLTexImage3DProc) ( GLenum target, GLint level, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid *pixels); + +/** Small variation on normal gluBuild3DMipmapLevels as we pass in the function pointer to glTexImage3D rather than rely on GLU style querry for this functon pointer.*/ +extern OSG_EXPORT GLint gluBuild3DMipmapLevels (GLTexImage3DProc glTextImage3DProc, GLenum target, GLint internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, GLint level, GLint base, GLint max, const void *data); + +/** Small variation on normal gluBuild3DMipmapLevels as we pass in the function pointer to glTexImage3D rather than rely on GLU style querry for this functon pointer.*/ +extern OSG_EXPORT GLint gluBuild3DMipmaps (GLTexImage3DProc glTextImage3DProc, GLenum target, GLint internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *data); + +/* ErrorCode */ +#define GLU_INVALID_ENUM 100900 +#define GLU_INVALID_VALUE 100901 +#define GLU_OUT_OF_MEMORY 100902 +#define GLU_INCOMPATIBLE_GL_VERSION 100903 +#define GLU_INVALID_OPERATION 100904 + +/* Boolean */ +#define GLU_FALSE 0 +#define GLU_TRUE 1 + +/* QuadricDrawStyle */ +#define GLU_POINT 100010 +#define GLU_LINE 100011 +#define GLU_FILL 100012 +#define GLU_SILHOUETTE 100013 + +/* QuadricCallback */ +/* GLU_ERROR */ + +/* QuadricNormal */ +#define GLU_SMOOTH 100000 +#define GLU_FLAT 100001 +#define GLU_NONE 100002 + +/* QuadricOrientation */ +#define GLU_OUTSIDE 100020 +#define GLU_INSIDE 100021 + +/* TessCallback */ +#define GLU_TESS_BEGIN 100100 +#define GLU_BEGIN 100100 +#define GLU_TESS_VERTEX 100101 +#define GLU_VERTEX 100101 +#define GLU_TESS_END 100102 +#define GLU_END 100102 +#define GLU_TESS_ERROR 100103 +#define GLU_TESS_EDGE_FLAG 100104 +#define GLU_EDGE_FLAG 100104 +#define GLU_TESS_COMBINE 100105 +#define GLU_TESS_BEGIN_DATA 100106 +#define GLU_TESS_VERTEX_DATA 100107 +#define GLU_TESS_END_DATA 100108 +#define GLU_TESS_ERROR_DATA 100109 +#define GLU_TESS_EDGE_FLAG_DATA 100110 +#define GLU_TESS_COMBINE_DATA 100111 + +/* TessContour */ +#define GLU_CW 100120 +#define GLU_CCW 100121 +#define GLU_INTERIOR 100122 +#define GLU_EXTERIOR 100123 +#define GLU_UNKNOWN 100124 + +/* TessProperty */ +#define GLU_TESS_WINDING_RULE 100140 +#define GLU_TESS_BOUNDARY_ONLY 100141 +#define GLU_TESS_TOLERANCE 100142 + +/* TessError */ +#define GLU_TESS_ERROR1 100151 +#define GLU_TESS_ERROR2 100152 +#define GLU_TESS_ERROR3 100153 +#define GLU_TESS_ERROR4 100154 +#define GLU_TESS_ERROR5 100155 +#define GLU_TESS_ERROR6 100156 +#define GLU_TESS_ERROR7 100157 +#define GLU_TESS_ERROR8 100158 +#define GLU_TESS_MISSING_BEGIN_POLYGON 100151 +#define GLU_TESS_MISSING_BEGIN_CONTOUR 100152 +#define GLU_TESS_MISSING_END_POLYGON 100153 +#define GLU_TESS_MISSING_END_CONTOUR 100154 +#define GLU_TESS_COORD_TOO_LARGE 100155 +#define GLU_TESS_NEED_COMBINE_CALLBACK 100156 + +/* TessWinding */ +#define GLU_TESS_WINDING_ODD 100130 +#define GLU_TESS_WINDING_NONZERO 100131 +#define GLU_TESS_WINDING_POSITIVE 100132 +#define GLU_TESS_WINDING_NEGATIVE 100133 +#define GLU_TESS_WINDING_ABS_GEQ_TWO 100134 + +struct GLUtesselator; +typedef GLUtesselator GLUtesselatorObj; +typedef GLUtesselator GLUtriangulatorObj; + +#define GLU_TESS_MAX_COORD 1.0e150 + +/* Internal convenience typedefs */ +typedef void (GL_APIENTRY * _GLUfuncptr)(); +typedef void (GL_APIENTRY * GLU_TESS_CALLBACK)(); + +extern OSG_EXPORT GLUtesselator* GL_APIENTRY gluNewTess (void); +extern OSG_EXPORT void GL_APIENTRY gluDeleteTess (GLUtesselator* tess); + +extern OSG_EXPORT void GL_APIENTRY gluTessBeginContour (GLUtesselator* tess); +extern OSG_EXPORT void GL_APIENTRY gluTessCallback (GLUtesselator* tess, GLenum which, _GLUfuncptr CallBackFunc); +extern OSG_EXPORT void GL_APIENTRY gluTessEndContour (GLUtesselator* tess); +extern OSG_EXPORT void GL_APIENTRY gluTessNormal (GLUtesselator* tess, GLdouble valueX, GLdouble valueY, GLdouble valueZ); +extern OSG_EXPORT void GL_APIENTRY gluTessProperty (GLUtesselator* tess, GLenum which, GLdouble data); +extern OSG_EXPORT void GL_APIENTRY gluTessVertex (GLUtesselator* tess, GLdouble *location, GLvoid* data); +extern OSG_EXPORT void GL_APIENTRY gluTessBeginPolygon (GLUtesselator* tess, GLvoid* data); +extern OSG_EXPORT void GL_APIENTRY gluTessEndPolygon (GLUtesselator* tess); +extern OSG_EXPORT void GL_APIENTRY gluGetTessProperty( GLUtesselator *tess, GLenum which, GLdouble *value ); + +} + +#endif // __osgGLU_h diff --git a/libs/include/android/osg/Geode b/libs/include/android/osg/Geode new file mode 100755 index 0000000..66bb154 --- /dev/null +++ b/libs/include/android/osg/Geode @@ -0,0 +1,167 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_GEODE +#define OSG_GEODE 1 + +#include +#include +#include + +namespace osg { + +/** A \c Geode is a "geometry node", that is, a leaf node on the scene graph + * that can have "renderable things" attached to it. In OSG, renderable things + * are represented by objects from the \c Drawable class, so a \c Geode is a + * \c Node whose purpose is grouping Drawables. +*/ +class OSG_EXPORT Geode : public Node +{ + public: + + typedef std::vector< ref_ptr > DrawableList; + + Geode(); + + /** Copy constructor using CopyOp to manage deep vs shallow copy.*/ + Geode(const Geode&,const CopyOp& copyop=CopyOp::SHALLOW_COPY); + + META_Node(osg, Geode); + + virtual Geode* asGeode() { return this; } + virtual const Geode* asGeode() const { return this; } + + /** Add a \c Drawable to the \c Geode. + * If \c drawable is not \c NULL and is not contained in the \c Geode + * then increment its reference count, add it to the drawables list and + * dirty the bounding sphere to force it to be recomputed on the next + * call to \c getBound(). + * @param drawable The \c Drawable to be added to the \c Geode. + * @return \c true for success; \c false otherwise. + */ + virtual bool addDrawable( Drawable *drawable ); + + /** Remove a \c Drawable from the \c Geode. + * Equivalent to removeDrawable(getDrawableIndex(drawable). + * @param drawable The drawable to be removed. + * @return \c true if at least one \c Drawable was removed. \c false + * otherwise. + */ + virtual bool removeDrawable( Drawable *drawable ); + + /** Remove Drawable(s) from the specified position in + * Geode's drawable list. + * @param i The index of the first \c Drawable to remove. + * @param numDrawablesToRemove The number of Drawable to + * remove. + * @return \c true if at least one \c Drawable was removed. \c false + * otherwise. + */ + virtual bool removeDrawables(unsigned int i,unsigned int numDrawablesToRemove=1); + + /** Replace specified Drawable with another Drawable. + * Equivalent to setDrawable(getDrawableIndex(origDraw),newDraw), + * see docs for \c setDrawable() for further details on implementation. + */ + virtual bool replaceDrawable( Drawable *origDraw, Drawable *newDraw ); + + /** Set \c Drawable at position \c i. + * Decrement the reference count origGSet and increments the + * reference count of newGset, and dirty the bounding sphere + * to force it to recompute on next getBound() and returns true. + * If origDrawable is not found then return false and do not + * add newGset. If newGset is NULL then return false and do + * not remove origGset. + * @return \c true if set correctly, \c false on failure + * (if node==NULL || i is out of range). + */ + virtual bool setDrawable( unsigned int i, Drawable* drawable ); + + /** Return the number of Drawables currently attached to the + * \c Geode. + */ + inline unsigned int getNumDrawables() const { return static_cast(_drawables.size()); } + + /** Return the \c Drawable at position \c i.*/ + inline Drawable* getDrawable( unsigned int i ) { return _drawables[i].get(); } + + /** Return the \c Drawable at position \c i.*/ + inline const Drawable* getDrawable( unsigned int i ) const { return _drawables[i].get(); } + + /** Return \c true if a given \c Drawable is contained within \c Geode.*/ + inline bool containsDrawable(const Drawable* gset) const + { + for (DrawableList::const_iterator itr=_drawables.begin(); + itr!=_drawables.end(); + ++itr) + { + if (itr->get()==gset) return true; + } + return false; + } + + /** Get the index number of \c drawable. + * @return A value between 0 and getNumDrawables()-1 if + * \c drawable is found; if not found, then + * getNumDrawables() is returned. + */ + inline unsigned int getDrawableIndex( const Drawable* drawable ) const + { + for (unsigned int drawableNum=0;drawableNum<_drawables.size();++drawableNum) + { + if (_drawables[drawableNum]==drawable) return drawableNum; + } + return static_cast(_drawables.size()); // drawable not found. + } + + /** Get the list of drawables.*/ + const DrawableList& getDrawableList() const { return _drawables; } + + /** Compile OpenGL Display List for each drawable.*/ + void compileDrawables(RenderInfo& renderInfo); + + /** Return the Geode's bounding box, which is the union of all the + * bounding boxes of the geode's drawables.*/ + inline const BoundingBox& getBoundingBox() const + { + if(!_boundingSphereComputed) getBound(); + return _bbox; + } + + virtual BoundingSphere computeBound() const; + + /** Set whether to use a mutex to ensure ref() and unref() are thread safe.*/ + virtual void setThreadSafeRefUnref(bool threadSafe); + + /** Resize any per context GLObject buffers to specified size. */ + virtual void resizeGLObjectBuffers(unsigned int maxSize); + + /** If State is non-zero, this function releases any associated OpenGL objects for + * the specified graphics context. Otherwise, releases OpenGL objects + * for all graphics contexts. */ + virtual void releaseGLObjects(osg::State* = 0) const; + + + protected: + + virtual ~Geode(); + + + mutable osg::BoundingBox _bbox; + DrawableList _drawables; + +}; + +} + +#endif diff --git a/libs/include/android/osg/Geometry b/libs/include/android/osg/Geometry new file mode 100755 index 0000000..68246d9 --- /dev/null +++ b/libs/include/android/osg/Geometry @@ -0,0 +1,351 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_GEOMETRY +#define OSG_GEOMETRY 1 + +#include +#include +#include +#include +#include +#include + +// leave defined for OpenSceneGraph-3.2 release, post 3.2 associated methods will be only be available in deprecated_osg::Geometry +#define OSG_DEPRECATED_GEOMETRY_BINDING 1 + +namespace osg { + +class OSG_EXPORT Geometry : public Drawable +{ + public: + + Geometry(); + + /** Copy constructor using CopyOp to manage deep vs shallow copy. */ + Geometry(const Geometry& geometry,const CopyOp& copyop=CopyOp::SHALLOW_COPY); + + virtual Object* cloneType() const { return new Geometry(); } + virtual Object* clone(const CopyOp& copyop) const { return new Geometry(*this,copyop); } + virtual bool isSameKindAs(const Object* obj) const { return dynamic_cast(obj)!=NULL; } + virtual const char* libraryName() const { return "osg"; } + virtual const char* className() const { return "Geometry"; } + + virtual Geometry* asGeometry() { return this; } + virtual const Geometry* asGeometry() const { return this; } + + bool empty() const; + + typedef std::vector< osg::ref_ptr > ArrayList; + + void setVertexArray(Array* array); + Array* getVertexArray() { return _vertexArray.get(); } + const Array* getVertexArray() const { return _vertexArray.get(); } + + + void setNormalArray(Array* array, osg::Array::Binding binding=osg::Array::BIND_UNDEFINED); + Array* getNormalArray() { return _normalArray.get(); } + const Array* getNormalArray() const { return _normalArray.get(); } + + + + void setColorArray(Array* array, osg::Array::Binding binding=osg::Array::BIND_UNDEFINED); + Array* getColorArray() { return _colorArray.get(); } + const Array* getColorArray() const { return _colorArray.get(); } + + + + void setSecondaryColorArray(Array* array, osg::Array::Binding binding=osg::Array::BIND_UNDEFINED); + Array* getSecondaryColorArray() { return _secondaryColorArray.get(); } + const Array* getSecondaryColorArray() const { return _secondaryColorArray.get(); } + + + void setFogCoordArray(Array* array, osg::Array::Binding binding=osg::Array::BIND_UNDEFINED); + Array* getFogCoordArray() { return _fogCoordArray.get(); } + const Array* getFogCoordArray() const { return _fogCoordArray.get(); } + + + void setTexCoordArray(unsigned int unit,Array* array, osg::Array::Binding binding=osg::Array::BIND_UNDEFINED); + Array* getTexCoordArray(unsigned int unit); + const Array* getTexCoordArray(unsigned int unit) const; + + unsigned int getNumTexCoordArrays() const { return static_cast(_texCoordList.size()); } + ArrayList& getTexCoordArrayList() { return _texCoordList; } + const ArrayList& getTexCoordArrayList() const { return _texCoordList; } + + + + void setVertexAttribArray(unsigned int index, Array* array, osg::Array::Binding binding=osg::Array::BIND_UNDEFINED); + Array *getVertexAttribArray(unsigned int index); + const Array *getVertexAttribArray(unsigned int index) const; + + + unsigned int getNumVertexAttribArrays() const { return static_cast(_vertexAttribList.size()); } + ArrayList& getVertexAttribArrayList() { return _vertexAttribList; } + const ArrayList& getVertexAttribArrayList() const { return _vertexAttribList; } + + + + typedef std::vector< ref_ptr > PrimitiveSetList; + + void setPrimitiveSetList(const PrimitiveSetList& primitives); + + PrimitiveSetList& getPrimitiveSetList() { return _primitives; } + const PrimitiveSetList& getPrimitiveSetList() const { return _primitives; } + + unsigned int getNumPrimitiveSets() const { return static_cast(_primitives.size()); } + PrimitiveSet* getPrimitiveSet(unsigned int pos) { return _primitives[pos].get(); } + const PrimitiveSet* getPrimitiveSet(unsigned int pos) const { return _primitives[pos].get(); } + + /** Add a primitive set to the geometry. */ + bool addPrimitiveSet(PrimitiveSet* primitiveset); + + /** Set a primitive set to the specified position in geometry's primitive set list. */ + bool setPrimitiveSet(unsigned int i,PrimitiveSet* primitiveset); + + /** Insert a primitive set to the specified position in geometry's primitive set list. */ + bool insertPrimitiveSet(unsigned int i,PrimitiveSet* primitiveset); + + /** Remove primitive set(s) from the specified position in geometry's primitive set list. */ + bool removePrimitiveSet(unsigned int i,unsigned int numElementsToRemove=1); + + /** Get the index number of a primitive set, return a value between + * 0 and getNumPrimitiveSet()-1 if found, if not found then return getNumPrimitiveSet(). + * When checking for a valid find value use if ((value=geometry->getPrimitiveSetIndex(primitive))!=geometry.getNumPrimitiveSet()) + */ + unsigned int getPrimitiveSetIndex(const PrimitiveSet* primitiveset) const; + + + /** return true if any arrays are shared.*/ + bool containsSharedArrays() const; + + /** duplicate any shared arrays.*/ + void duplicateSharedArrays(); + + + /** When set to true, ignore the setUseDisplayList() settings, and hints to the drawImplementation + method to use OpenGL vertex buffer objects for rendering.*/ + virtual void setUseVertexBufferObjects(bool flag); + + /** Force a recompile on next draw() of any OpenGL display list associated with this geoset.*/ + virtual void dirtyDisplayList(); + + + /** Resize any per context GLObject buffers to specified size. */ + virtual void resizeGLObjectBuffers(unsigned int maxSize); + + /** If State is non-zero, this function releases OpenGL objects for + * the specified graphics context. Otherwise, releases OpenGL objects + * for all graphics contexts. */ + virtual void releaseGLObjects(State* state=0) const; + + bool getArrayList(ArrayList& arrayList) const; + + typedef std::vector DrawElementsList; + bool getDrawElementsList(DrawElementsList& drawElementsList) const; + + osg::VertexBufferObject* getOrCreateVertexBufferObject(); + osg::ElementBufferObject* getOrCreateElementBufferObject(); + + + /** Return the estimated size of GLObjects (display lists/vertex buffer objects) that are associated with this drawable. + * This size is used a hint for reuse of deleted display lists/vertex buffer objects. */ + virtual unsigned int getGLObjectSizeHint() const; + + /** Immediately compile this \c Drawable into an OpenGL Display List/VertexBufferObjects. + * @note Operation is ignored if \c _useDisplayList is \c false or VertexBufferObjects are not used. + */ + virtual void compileGLObjects(RenderInfo& renderInfo) const; + + /** Draw Geometry directly ignoring an OpenGL display list which could be attached. + * This is the internal draw method which does the drawing itself, + * and is the method to override when deriving from Geometry for user-drawn objects. + */ + virtual void drawImplementation(RenderInfo& renderInfo) const; + + /** Return true, osg::Geometry does support accept(Drawable::AttributeFunctor&). */ + virtual bool supports(const Drawable::AttributeFunctor&) const { return true; } + + /** Accept an Drawable::AttributeFunctor and call its methods to tell it about the internal attributes that this Drawable has. */ + virtual void accept(Drawable::AttributeFunctor& af); + + /** Return true, osg::Geometry does support accept(Drawable::ConstAttributeFunctor&). */ + virtual bool supports(const Drawable::ConstAttributeFunctor&) const { return true; } + + /** Accept a Drawable::ConstAttributeFunctor and call its methods to tell it about the internal attributes that this Drawable has. */ + virtual void accept(Drawable::ConstAttributeFunctor& af) const; + + /** Return true, osg::Geometry does support accept(PrimitiveFunctor&). */ + virtual bool supports(const PrimitiveFunctor&) const { return true; } + + /** Accept a PrimitiveFunctor and call its methods to tell it about the internal primitives that this Drawable has. */ + virtual void accept(PrimitiveFunctor& pf) const; + + /** Return true, osg::Geometry does support accept(PrimitiveIndexFunctor&). */ + virtual bool supports(const PrimitiveIndexFunctor&) const { return true; } + + /** Accept a PrimitiveFunctor and call its methods to tell it about the internal primitives that this Drawable has. */ + virtual void accept(PrimitiveIndexFunctor& pf) const; + + + protected: + + Geometry& operator = (const Geometry&) { return *this;} + + virtual ~Geometry(); + + + void addVertexBufferObjectIfRequired(osg::Array* array); + void addElementBufferObjectIfRequired(osg::PrimitiveSet* primitiveSet); + + + PrimitiveSetList _primitives; + osg::ref_ptr _vertexArray; + osg::ref_ptr _normalArray; + osg::ref_ptr _colorArray; + osg::ref_ptr _secondaryColorArray; + osg::ref_ptr _fogCoordArray; + ArrayList _texCoordList; + ArrayList _vertexAttribList; + + bool _containsDeprecatedData; + + public: + + + /** Return true if the deprecated use array indicies or BIND_PER_PRIMITIVE binding has been assigned to arrays.*/ + bool containsDeprecatedData() const { return _containsDeprecatedData; } + + /** fallback for deprecated functionality. Return true if the Geometry contains any array indices or BIND_PER_PRIMITIVE arrays. */ + bool checkForDeprecatedData(); + + /** fallback for deprecated functionality. Removes any array indices and BIND_PER_PRIMITIVE arrays.*/ + void fixDeprecatedData(); + +#if defined(OSG_DEPRECATED_GEOMETRY_BINDING) + /** deprecated, Same values as Array::Binding.*/ + enum AttributeBinding + { + BIND_OFF=0, + BIND_OVERALL=1, + BIND_PER_PRIMITIVE_SET=2, + BIND_PER_VERTEX=4 + }; + + /** deprecated, use array->set*Binding(..). */ + void setNormalBinding(AttributeBinding ab); + void setColorBinding(AttributeBinding ab); + void setSecondaryColorBinding(AttributeBinding ab); + void setFogCoordBinding(AttributeBinding ab); + void setVertexAttribBinding(unsigned int index,AttributeBinding ab); + + /** deprecated, use array->get*Binding(..). */ + AttributeBinding getNormalBinding() const; + AttributeBinding getColorBinding() const; + AttributeBinding getSecondaryColorBinding() const; + AttributeBinding getFogCoordBinding() const; + AttributeBinding getVertexAttribBinding(unsigned int index) const; + + /** deprecated, use array->set*Normalize(..). */ + void setVertexAttribNormalize(unsigned int index,GLboolean norm); + + /** deprecated, use array->get*Normalize(..). */ + GLboolean getVertexAttribNormalize(unsigned int index) const; +#endif +}; + +/** Convenience function to be used for creating quad geometry with texture coords. + * Tex coords go from left bottom (l,b) to right top (r,t). +*/ +extern OSG_EXPORT Geometry* createTexturedQuadGeometry(const Vec3& corner,const Vec3& widthVec,const Vec3& heightVec, float l, float b, float r, float t); + +/** Convenience function to be used for creating quad geometry with texture coords. + * Tex coords go from bottom left (0,0) to top right (s,t). +*/ +inline Geometry* createTexturedQuadGeometry(const Vec3& corner,const Vec3& widthVec,const Vec3& heightVec, float s=1.0f, float t=1.0f) +{ + return createTexturedQuadGeometry(corner,widthVec,heightVec, 0.0f, 0.0f, s, t); +} + +} // namespace osg + + + +/** Contains deprecated features of namespace osg. */ +namespace deprecated_osg { + +/** Geometry class contaning deprecated features. + * Users should only use deprecatged_osg::Geometry when absolutely neccessary for keeping things compiling, + * it is recommended that you should migrate your code to work just with osg::Geometry as existing + * deprecated_osg::Geometry will be removed in future release. +*/ +class OSG_EXPORT Geometry : public osg::Geometry +{ + public: + Geometry() : osg::Geometry() {} + Geometry(const Geometry& geometry,const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY) : osg::Geometry(geometry, copyop) {} + + /** Same values as Array::Binding.*/ + enum AttributeBinding + { + BIND_OFF=0, + BIND_OVERALL=1, + BIND_PER_PRIMITIVE_SET=2, + BIND_PER_PRIMITIVE=3, + BIND_PER_VERTEX=4 + }; + + void setNormalBinding(AttributeBinding ab); + AttributeBinding getNormalBinding() const; + + void setColorBinding(AttributeBinding ab); + AttributeBinding getColorBinding() const; + + void setSecondaryColorBinding(AttributeBinding ab); + AttributeBinding getSecondaryColorBinding() const; + + void setFogCoordBinding(AttributeBinding ab); + AttributeBinding getFogCoordBinding() const; + + void setVertexAttribBinding(unsigned int index,AttributeBinding ab); + AttributeBinding getVertexAttribBinding(unsigned int index) const; + + void setVertexAttribNormalize(unsigned int index,GLboolean norm); + GLboolean getVertexAttribNormalize(unsigned int index) const; + + void setVertexIndices(osg::IndexArray* array); + const osg::IndexArray* getVertexIndices() const; + + void setNormalIndices(osg::IndexArray* array); + const osg::IndexArray* getNormalIndices() const; + + void setColorIndices(osg::IndexArray* array); + const osg::IndexArray* getColorIndices() const; + + void setSecondaryColorIndices(osg::IndexArray* array); + const osg::IndexArray* getSecondaryColorIndices() const; + + void setFogCoordIndices(osg::IndexArray* array); + const osg::IndexArray* getFogCoordIndices() const; + + void setTexCoordIndices(unsigned int unit,osg::IndexArray* array); + const osg::IndexArray* getTexCoordIndices(unsigned int unit) const; + + void setVertexAttribIndices(unsigned int index,osg::IndexArray* array); + const osg::IndexArray* getVertexAttribIndices(unsigned int index) const; + +}; + +} // namespace deprecated_osg + +#endif diff --git a/libs/include/android/osg/GraphicsContext b/libs/include/android/osg/GraphicsContext new file mode 100755 index 0000000..cd30b2f --- /dev/null +++ b/libs/include/android/osg/GraphicsContext @@ -0,0 +1,532 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_GRAPHICSCONTEXT +#define OSG_GRAPHICSCONTEXT 1 + +#include +#include +#include + +#include + +namespace osg { + +// forward declare osg::Camera +class Camera; + +/** Base class for providing Windowing API agnostic access to creating and managing graphics context.*/ +class OSG_EXPORT GraphicsContext : public Object +{ + public: + + struct OSG_EXPORT ScreenIdentifier + { + ScreenIdentifier(); + + ScreenIdentifier(int in_screenNum); + + ScreenIdentifier(const std::string& in_hostName,int in_displayNum, int in_screenNum); + + /** Return the display name in the form hostName::displayNum:screenNum. */ + std::string displayName() const; + + /** Read the DISPLAY environmental variable, and set the ScreenIdentifier accordingly. + * Note, if either of displayNum or screenNum are not defined then -1 is set respectively to + * signify that this parameter has not been set. When parameters are undefined one can call + * call setUndefinedScreenDetailsToDefaultScreen() after readDISPLAY() to ensure valid values. */ + void readDISPLAY(); + + /** Set the screenIndentifier from the displayName string. + * Note, if either of displayNum or screenNum are not defined then -1 is set to + * signify that this parameter has not been set. When parameters are undefined one can call + * call setUndefinedScreenDetailsToDefaultScreen() after readDISPLAY() to ensure valid values. */ + void setScreenIdentifier(const std::string& displayName); + + /** Set any undefined displayNum or screenNum values (i.e. -1) to the default display & screen of 0 respectively.*/ + void setUndefinedScreenDetailsToDefaultScreen() + { + if (displayNum<0) displayNum = 0; + if (screenNum<0) screenNum = 0; + } + + std::string hostName; + int displayNum; + int screenNum; + }; + + /** GraphicsContext Traits object provides the specification of what type of graphics context is required.*/ + struct OSG_EXPORT Traits : public osg::Referenced, public ScreenIdentifier + { + Traits(DisplaySettings* ds=0); + + // graphics context original and size + int x; + int y; + int width; + int height; + + // window decoration and behaviour + std::string windowName; + bool windowDecoration; + bool supportsResize; + + // buffer depths, 0 equals off. + unsigned int red; + unsigned int blue; + unsigned int green; + unsigned int alpha; + unsigned int depth; + unsigned int stencil; + + // multi sample parameters + unsigned int sampleBuffers; + unsigned int samples; + + // buffer configuration + bool pbuffer; + bool quadBufferStereo; + bool doubleBuffer; + + // render to texture + GLenum target; + GLenum format; + unsigned int level; + unsigned int face; + unsigned int mipMapGeneration; + + // V-sync + bool vsync; + + // Swap Group + bool swapGroupEnabled; + GLuint swapGroup; + GLuint swapBarrier; + + // use multithreaded OpenGL-engine (OS X only) + bool useMultiThreadedOpenGLEngine; + + // enable cursor + bool useCursor; + + // settings used in set up of graphics context, only presently used by GL3 build of OSG. + std::string glContextVersion; + unsigned int glContextFlags; + unsigned int glContextProfileMask; + + /** return true if glContextVersion is set in the form major.minor, and assign the appropriate major and minor values to the associated parameters.*/ + bool getContextVersion(unsigned int& major, unsigned int& minor) const; + + // shared context + osg::observer_ptr sharedContext; + + osg::ref_ptr inheritedWindowData; + + // ask the GraphicsWindow implementation to set the pixel format of an inherited window + bool setInheritedWindowPixelFormat; + + // X11 hint whether to override the window managers window size/position redirection + bool overrideRedirect; + + DisplaySettings::SwapMethod swapMethod; + }; + + /** Simple resolution structure used by WindowingSystemInterface to get and set screen resolution. + * Note the '0' value stands for 'unset'. */ + struct ScreenSettings { + ScreenSettings() : + width(0), + height(0), + refreshRate(0), + colorDepth(0) + {} + ScreenSettings(int width, int height, double refreshRate=0, unsigned int colorDepth=0) : + width(width), + height(height), + refreshRate(refreshRate), + colorDepth(colorDepth) + {} + + int width; + int height; + double refreshRate; ///< Screen refresh rate, in Hz. + unsigned int colorDepth; ///< RGB(A) color buffer depth. + }; + + typedef std::vector ScreenSettingsList; + + /** Callback to be implemented to provide access to Windowing API's ability to create Windows/pbuffers.*/ + struct WindowingSystemInterface : public osg::Referenced + { + virtual unsigned int getNumScreens(const ScreenIdentifier& screenIdentifier = ScreenIdentifier()) = 0; + + virtual void getScreenSettings(const ScreenIdentifier& screenIdentifier, ScreenSettings & resolution) = 0; + + virtual bool setScreenSettings(const ScreenIdentifier& /*screenIdentifier*/, const ScreenSettings & /*resolution*/) { return false; } + + virtual void enumerateScreenSettings(const ScreenIdentifier& screenIdentifier, ScreenSettingsList & resolutionList) = 0; + + virtual GraphicsContext* createGraphicsContext(Traits* traits) = 0; + + virtual ~WindowingSystemInterface() {} + + + /** Gets screen resolution without using the ScreenResolution structure. + * \deprecated Provided only for backward compatibility. */ + inline void getScreenResolution(const ScreenIdentifier& screenIdentifier, unsigned int& width, unsigned int& height) + { + ScreenSettings settings; + getScreenSettings(screenIdentifier, settings); + width = settings.width; + height = settings.height; + } + + /** Sets screen resolution without using the ScreenSettings structure. + * \deprecated Provided only for backward compatibility. */ + inline bool setScreenResolution(const ScreenIdentifier& screenIdentifier, unsigned int width, unsigned int height) + { + return setScreenSettings(screenIdentifier, ScreenSettings(width, height)); + } + + /** \deprecated Provided only for backward compatibility. */ + inline bool setScreenRefreshRate(const ScreenIdentifier& screenIdentifier, double refreshRate) + { + ScreenSettings settings; + getScreenSettings(screenIdentifier, settings); + settings.refreshRate = refreshRate; + return setScreenSettings(screenIdentifier, settings); + } + }; + + + /** Set the query the windowing system for screens and create graphics context - this functor should be supplied by the windows toolkit. */ + static void setWindowingSystemInterface(WindowingSystemInterface* wsInterface); + + /** Get the WindowingSystemInterface*/ + static WindowingSystemInterface* getWindowingSystemInterface(); + + /** Create a graphics context for a specified set of traits.*/ + static GraphicsContext* createGraphicsContext(Traits* traits); + + /** Create a contextID for a new graphics context, this contextID is used to set up the osg::State associate with context. + * Automatically increments the usage count of the contextID to 1.*/ + static unsigned int createNewContextID(); + + /** Get the current max ContextID.*/ + static unsigned int getMaxContextID(); + + /** Increment the usage count associate with a contextID. The usage count specifies how many graphics contexts a specific contextID is shared between.*/ + static void incrementContextIDUsageCount(unsigned int contextID); + + /** Decrement the usage count associate with a contextID. Once the contextID goes to 0 the contextID is then free to be reused.*/ + static void decrementContextIDUsageCount(unsigned int contextID); + + typedef std::vector GraphicsContexts; + + /** Get all the registered graphics contexts.*/ + static GraphicsContexts getAllRegisteredGraphicsContexts(); + + /** Get all the registered graphics contexts associated with a specific contextID.*/ + static GraphicsContexts getRegisteredGraphicsContexts(unsigned int contextID); + + /** Get the GraphicsContext for doing background compilation for GraphicsContexts associated with specified contextID.*/ + static void setCompileContext(unsigned int contextID, GraphicsContext* gc); + + /** Get existing or create a new GraphicsContext to do background compilation for GraphicsContexts associated with specified contextID.*/ + static GraphicsContext* getOrCreateCompileContext(unsigned int contextID); + + /** Get the GraphicsContext for doing background compilation for GraphicsContexts associated with specified contextID.*/ + static GraphicsContext* getCompileContext(unsigned int contextID); + + public: + + /** Add operation to end of OperationQueue.*/ + void add(Operation* operation); + + /** Remove operation from OperationQueue.*/ + void remove(Operation* operation); + + /** Remove named operation from OperationQueue.*/ + void remove(const std::string& name); + + /** Remove all operations from OperationQueue.*/ + void removeAllOperations(); + + /** Run the operations. */ + virtual void runOperations(); + + typedef std::list< ref_ptr > GraphicsOperationQueue; + + /** Get the operations queue, not you must use the OperationsMutex when accessing the queue.*/ + GraphicsOperationQueue& getOperationsQueue() { return _operations; } + + /** Get the operations queue mutex.*/ + OpenThreads::Mutex* getOperationsMutex() { return &_operationsMutex; } + + /** Get the operations queue block used to mark an empty queue, if you end items into the empty queue you must release this block.*/ + osg::RefBlock* getOperationsBlock() { return _operationsBlock.get(); } + + /** Get the current operations that is being run.*/ + Operation* getCurrentOperation() { return _currentOperation.get(); } + + + public: + + /** Get the traits of the GraphicsContext.*/ + inline const Traits* getTraits() const { return _traits.get(); } + + /** Return whether a valid and usable GraphicsContext has been created.*/ + virtual bool valid() const = 0; + + + /** Set the State object which tracks the current OpenGL state for this graphics context.*/ + inline void setState(State* state) { _state = state; } + + /** Get the State object which tracks the current OpenGL state for this graphics context.*/ + inline State* getState() { return _state.get(); } + + /** Get the const State object which tracks the current OpenGL state for this graphics context.*/ + inline const State* getState() const { return _state.get(); } + + + /** Sets the clear color. */ + inline void setClearColor(const Vec4& color) { _clearColor = color; } + + /** Returns the clear color. */ + inline const Vec4& getClearColor() const { return _clearColor; } + + /** Set the clear mask used in glClear(..). + * Defaults to 0 - so no clear is done by default by the GraphicsContext, instead the Cameras attached to the GraphicsContext will do the clear. + * GraphicsContext::setClearMask() is useful for when the Camera Viewports don't cover the whole context, so the context will fill in the gaps. */ + inline void setClearMask(GLbitfield mask) { _clearMask = mask; } + + /** Get the clear mask.*/ + inline GLbitfield getClearMask() const { return _clearMask; } + + /** Do an OpenGL clear of the full graphics context/window. + * Note, must only be called from a thread with this context current.*/ + virtual void clear(); + + double getTimeSinceLastClear() const { return osg::Timer::instance()->delta_s(_lastClearTick, osg::Timer::instance()->tick()); } + + + /** Realize the GraphicsContext.*/ + bool realize(); + + /** close the graphics context. + * close(bool) stops any associated graphics threads, releases the contextID for the GraphicsContext then + * optional calls closeImplementation() to do the actual deletion of the graphics. This call is made optional + * as there are times when the graphics context has already been deleted externally and only the OSG side + * of the its data need to be closed down. */ + void close(bool callCloseImplementation=true); + + /** swap the front and back buffers.*/ + void swapBuffers(); + + /** Return true if the graphics context has been realized and is ready to use.*/ + inline bool isRealized() const { return isRealizedImplementation(); } + + + /** Make this graphics context current. + * Implemented by calling makeCurrentImplementation(). + * Returns true on success. */ + bool makeCurrent(); + + /** Make this graphics context current with specified read context. + * Implemented by calling makeContextCurrentImplementation(). + * Returns true on success. */ + bool makeContextCurrent(GraphicsContext* readContext); + + /** Release the graphics context. + * Returns true on success. */ + bool releaseContext(); + + /** Return true if the current thread has this OpenGL graphics context.*/ + inline bool isCurrent() const { return _threadOfLastMakeCurrent == OpenThreads::Thread::CurrentThread(); } + + /** Bind the graphics context to associated texture.*/ + inline void bindPBufferToTexture(GLenum buffer) { bindPBufferToTextureImplementation(buffer); } + + + + /** Create a graphics thread to the graphics context, so that the thread handles all OpenGL operations.*/ + void createGraphicsThread(); + + /** Assign a graphics thread to the graphics context, so that the thread handles all OpenGL operations.*/ + void setGraphicsThread(GraphicsThread* gt); + + /** Get the graphics thread assigned the graphics context.*/ + GraphicsThread* getGraphicsThread() { return _graphicsThread.get(); } + + /** Get the const graphics thread assigned the graphics context.*/ + const GraphicsThread* getGraphicsThread() const { return _graphicsThread.get(); } + + + /** Realize the GraphicsContext implementation, + * Pure virtual - must be implemented by concrete implementations of GraphicsContext. */ + virtual bool realizeImplementation() = 0; + + /** Return true if the graphics context has been realized, and is ready to use, implementation. + * Pure virtual - must be implemented by concrete implementations of GraphicsContext. */ + virtual bool isRealizedImplementation() const = 0; + + /** Close the graphics context implementation. + * Pure virtual - must be implemented by concrete implementations of GraphicsContext. */ + virtual void closeImplementation() = 0; + + /** Make this graphics context current implementation. + * Pure virtual - must be implemented by concrete implementations of GraphicsContext. */ + virtual bool makeCurrentImplementation() = 0; + + /** Make this graphics context current with specified read context implementation. + * Pure virtual - must be implemented by concrete implementations of GraphicsContext. */ + virtual bool makeContextCurrentImplementation(GraphicsContext* readContext) = 0; + + /** Release the graphics context implementation.*/ + virtual bool releaseContextImplementation() = 0; + + /** Pure virtual, Bind the graphics context to associated texture implementation. + * Pure virtual - must be implemented by concrete implementations of GraphicsContext. */ + virtual void bindPBufferToTextureImplementation(GLenum buffer) = 0; + + struct SwapCallback : public osg::Referenced + { + virtual void swapBuffersImplementation(GraphicsContext* gc) = 0; + }; + /** Set the swap callback which overrides the + * GraphicsContext::swapBuffersImplementation(), allowing + * developers to provide custom behavior for swap. + * The callback must call + * GraphicsContext::swapBuffersImplementation() */ + void setSwapCallback(SwapCallback* rc) { _swapCallback = rc; } + + /** Get the swap callback which overrides the GraphicsContext::swapBuffersImplementation().*/ + SwapCallback* getSwapCallback() { return _swapCallback.get(); } + + /** Get the const swap callback which overrides the GraphicsContext::swapBuffersImplementation().*/ + const SwapCallback* getSwapCallback() const { return _swapCallback.get(); } + + /** convinience method for handling whether to call swapbuffers callback or the standard context swapBuffersImplementation. + * swapBuffersCallbackOrImplemenation() is called by swapBuffers() and osg::SwapBuffersOperation, end users should normally + * call swapBuffers() rather than swapBuffersCallbackOrImplemenation(). */ + void swapBuffersCallbackOrImplemenation() + { + if (_state.valid()) _state->frameCompleted(); + + if (_swapCallback.valid()) _swapCallback->swapBuffersImplementation(this); + else swapBuffersImplementation(); + } + + /** Swap the front and back buffers implementation. + * Pure virtual - must be implemented by concrete implementations of GraphicsContext. */ + virtual void swapBuffersImplementation() = 0; + + + + /** resized method should be called when the underlying window has been resized and the GraphicsWindow and associated Cameras must + be updated to keep in sync with the new size. */ + void resized(int x, int y, int width, int height) + { + if (_resizedCallback.valid()) _resizedCallback->resizedImplementation(this, x, y, width, height); + else resizedImplementation(x, y, width, height); + } + + struct ResizedCallback : public osg::Referenced + { + virtual void resizedImplementation(GraphicsContext* gc, int x, int y, int width, int height) = 0; + }; + + /** Set the resized callback which overrides the GraphicsConext::realizedImplementation(), allow developers to provide custom behavior + * in response to a window being resized.*/ + void setResizedCallback(ResizedCallback* rc) { _resizedCallback = rc; } + + /** Get the resized callback which overrides the GraphicsConext::realizedImplementation().*/ + ResizedCallback* getResizedCallback() { return _resizedCallback.get(); } + + /** Get the const resized callback which overrides the GraphicsConext::realizedImplementation().*/ + const ResizedCallback* getResizedCallback() const { return _resizedCallback.get(); } + + /** resized implementation, by default resizes the viewports and aspect ratios the cameras associated with the graphics Window. */ + virtual void resizedImplementation(int x, int y, int width, int height); + + + typedef std::list< osg::Camera* > Cameras; + + /** Get the the list of cameras associated with this graphics context.*/ + Cameras& getCameras() { return _cameras; } + + /** Get the the const list of cameras associated with this graphics context.*/ + const Cameras& getCameras() const { return _cameras; } + + /** set the default FBO-id, this id will be used when the rendering-backend is finished with RTT FBOs */ + void setDefaultFboId(GLuint i) { _defaultFboId = i; } + + GLuint getDefaultFboId() const { return _defaultFboId; } + + public: + + virtual bool isSameKindAs(const Object* object) const { return dynamic_cast(object)!=0; } + virtual const char* libraryName() const { return "osg"; } + virtual const char* className() const { return "GraphicsContext"; } + + protected: + + GraphicsContext(); + GraphicsContext(const GraphicsContext&, const osg::CopyOp&); + + virtual ~GraphicsContext(); + + virtual Object* cloneType() const { return 0; } + virtual Object* clone(const CopyOp&) const { return 0; } + + /** Register a GraphicsContext.*/ + static void registerGraphicsContext(GraphicsContext* gc); + + /** Unregister a GraphicsContext.*/ + static void unregisterGraphicsContext(GraphicsContext* gc); + + + void addCamera(osg::Camera* camera); + void removeCamera(osg::Camera* camera); + + Cameras _cameras; + + friend class osg::Camera; + + ref_ptr _traits; + ref_ptr _state; + + Vec4 _clearColor; + GLbitfield _clearMask; + + OpenThreads::Thread* _threadOfLastMakeCurrent; + + OpenThreads::Mutex _operationsMutex; + osg::ref_ptr _operationsBlock; + GraphicsOperationQueue _operations; + osg::ref_ptr _currentOperation; + + ref_ptr _graphicsThread; + + ref_ptr _resizedCallback; + ref_ptr _swapCallback; + + Timer_t _lastClearTick; + + GLuint _defaultFboId; +}; + + +} + +#endif diff --git a/libs/include/android/osg/GraphicsCostEstimator b/libs/include/android/osg/GraphicsCostEstimator new file mode 100755 index 0000000..88fbc1e --- /dev/null +++ b/libs/include/android/osg/GraphicsCostEstimator @@ -0,0 +1,142 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_GRAPHICSCOSTESTIMATOR +#define OSG_GRAPHICSCOSTESTIMATOR + +#include +#include +#include + +namespace osg +{ + +class Geometry; +class Texture; +class Program; +class Node; +class RenderInfo; + +struct ClampedLinearCostFunction1D +{ + ClampedLinearCostFunction1D(double cost0=0.0, double dcost_di=0.0, unsigned int min_input=0): + _cost0(cost0), + _dcost_di(dcost_di), + _min_input(min_input) {} + + void set(double cost0, double dcost_di, unsigned int min_input) + { + _cost0 = cost0; + _dcost_di = dcost_di; + _min_input = min_input; + } + + double operator() (unsigned int input) const + { + return _cost0 + _dcost_di * double(input<=_min_input ? 0u : input-_min_input); + } + double _cost0; + double _dcost_di; + unsigned int _min_input; +}; + +/** Pair of double representing CPU and GPU times in seconds as first and second elements in std::pair. */ +typedef std::pair CostPair; + + +class OSG_EXPORT GeometryCostEstimator : public osg::Referenced +{ +public: + GeometryCostEstimator(); + void setDefaults(); + void calibrate(osg::RenderInfo& renderInfo); + CostPair estimateCompileCost(const osg::Geometry* geometry) const; + CostPair estimateDrawCost(const osg::Geometry* geometry) const; + +protected: + ClampedLinearCostFunction1D _arrayCompileCost; + ClampedLinearCostFunction1D _primtiveSetCompileCost; + + ClampedLinearCostFunction1D _arrayDrawCost; + ClampedLinearCostFunction1D _primtiveSetDrawCost; + + double _displayListCompileConstant; + double _displayListCompileFactor; +}; + +class OSG_EXPORT TextureCostEstimator : public osg::Referenced +{ +public: + TextureCostEstimator(); + void setDefaults(); + void calibrate(osg::RenderInfo& renderInfo); + CostPair estimateCompileCost(const osg::Texture* texture) const; + CostPair estimateDrawCost(const osg::Texture* texture) const; + +protected: + ClampedLinearCostFunction1D _compileCost; + ClampedLinearCostFunction1D _drawCost; +}; + + +class OSG_EXPORT ProgramCostEstimator : public osg::Referenced +{ +public: + ProgramCostEstimator(); + void setDefaults(); + void calibrate(osg::RenderInfo& renderInfo); + CostPair estimateCompileCost(const osg::Program* program) const; + CostPair estimateDrawCost(const osg::Program* program) const; + +protected: + ClampedLinearCostFunction1D _shaderCompileCost; + ClampedLinearCostFunction1D _linkCost; + ClampedLinearCostFunction1D _drawCost; +}; + +class OSG_EXPORT GraphicsCostEstimator : public osg::Referenced +{ +public: + GraphicsCostEstimator(); + + /** set defaults for computing the costs.*/ + void setDefaults(); + + /** calibrate the costs of various compile and draw operations */ + void calibrate(osg::RenderInfo& renderInfo); + + CostPair estimateCompileCost(const osg::Geometry* geometry) const { return _geometryEstimator->estimateCompileCost(geometry); } + CostPair estimateDrawCost(const osg::Geometry* geometry) const { return _geometryEstimator->estimateDrawCost(geometry); } + + CostPair estimateCompileCost(const osg::Texture* texture) const { return _textureEstimator->estimateCompileCost(texture); } + CostPair estimateDrawCost(const osg::Texture* texture) const { return _textureEstimator->estimateDrawCost(texture); } + + CostPair estimateCompileCost(const osg::Program* program) const { return _programEstimator->estimateCompileCost(program); } + CostPair estimateDrawCost(const osg::Program* program) const { return _programEstimator->estimateDrawCost(program); } + + CostPair estimateCompileCost(const osg::Node* node) const; + CostPair estimateDrawCost(const osg::Node* node) const; + +protected: + + virtual ~GraphicsCostEstimator(); + + osg::ref_ptr _geometryEstimator; + osg::ref_ptr _textureEstimator; + osg::ref_ptr _programEstimator; + +}; + +} + +#endif diff --git a/libs/include/android/osg/GraphicsThread b/libs/include/android/osg/GraphicsThread new file mode 100755 index 0000000..60ee085 --- /dev/null +++ b/libs/include/android/osg/GraphicsThread @@ -0,0 +1,136 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_GRAPHICSTHREAD +#define OSG_GRAPHICSTHREAD 1 + +#include +#include + +namespace osg { + +class GraphicsContext; + +/** GraphicsThread is a helper class for running OpenGL GraphicsOperation within a single thread assigned to a specific GraphicsContext.*/ +class OSG_EXPORT GraphicsThread : public osg::OperationThread +{ + public: + + GraphicsThread(); + + /** Run does the graphics thread run loop.*/ + virtual void run(); +}; + +struct OSG_EXPORT GraphicsOperation : public Operation +{ + GraphicsOperation(const std::string& name, bool keep): + Operation(name,keep) {} + + /** Override the standard Operation operator and dynamic cast object to a GraphicsContext, + * on success call operation()(GraphicsContext*).*/ + virtual void operator () (Object* object); + + virtual void operator () (GraphicsContext* context) = 0; +}; + + +/** SwapBufferOperation calls swap buffers on the GraphicsContext.*/ +struct OSG_EXPORT SwapBuffersOperation : public GraphicsOperation +{ + SwapBuffersOperation(): + GraphicsOperation("SwapBuffers",true) {} + + virtual void operator () (GraphicsContext* context); +}; + +/** BarrierOperation allows one to synchronize multiple GraphicsThreads with each other.*/ +struct OSG_EXPORT BarrierOperation : public Operation, public OpenThreads::Barrier +{ + enum PreBlockOp + { + NO_OPERATION, + GL_FLUSH, + GL_FINISH + }; + + BarrierOperation(int numThreads, PreBlockOp op=NO_OPERATION, bool keep=true): + Operation("Barrier", keep), + OpenThreads::Barrier(numThreads), + _preBlockOp(op) {} + + virtual void release(); + + virtual void operator () (Object* object); + + PreBlockOp _preBlockOp; +}; + +/** ReleaseContext_Block_MakeCurrentOperation releases the context for another thread to acquire, + * then blocks waiting for context to be released, once the block is release the context is re-acquired.*/ +struct OSG_EXPORT ReleaseContext_Block_MakeCurrentOperation : public GraphicsOperation, public RefBlock +{ + ReleaseContext_Block_MakeCurrentOperation(): + GraphicsOperation("ReleaseContext_Block_MakeCurrent", false) {} + + virtual void release(); + + virtual void operator () (GraphicsContext* context); +}; + +struct OSG_EXPORT BlockAndFlushOperation : public GraphicsOperation, public OpenThreads::Block +{ + BlockAndFlushOperation(); + + virtual void release(); + + virtual void operator () (GraphicsContext*); +}; + + +struct OSG_EXPORT FlushDeletedGLObjectsOperation : public GraphicsOperation +{ + FlushDeletedGLObjectsOperation(double availableTime, bool keep=false); + + virtual void operator () (GraphicsContext*); + + double _availableTime; +}; + +class OSG_EXPORT RunOperations : public osg::GraphicsOperation +{ +public: + + RunOperations(): + osg::GraphicsOperation("RunOperation",true) {} + + virtual void operator () (osg::GraphicsContext* context); + +}; + +class OSG_EXPORT EndOfDynamicDrawBlock : public OpenThreads::BlockCount, public osg::State::DynamicObjectRenderingCompletedCallback +{ + public: + + EndOfDynamicDrawBlock(unsigned int); + + void completed(osg::State* state); + + protected: + + ~EndOfDynamicDrawBlock() {} +}; + +} + +#endif diff --git a/libs/include/android/osg/Group b/libs/include/android/osg/Group new file mode 100755 index 0000000..9434d72 --- /dev/null +++ b/libs/include/android/osg/Group @@ -0,0 +1,172 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_GROUP +#define OSG_GROUP 1 + +#include +#include + +namespace osg { + +typedef std::vector< ref_ptr > NodeList; + +/** General group node which maintains a list of children. + * Children are reference counted. This allows children to be shared + * with memory management handled automatically via osg::Referenced. +*/ +class OSG_EXPORT Group : public Node +{ + public : + + + Group(); + + /** Copy constructor using CopyOp to manage deep vs shallow copy. */ + Group(const Group&,const CopyOp& copyop=CopyOp::SHALLOW_COPY); + + META_Node(osg, Group); + + virtual Group* asGroup() { return this; } + virtual const Group* asGroup() const { return this; } + + virtual void traverse(NodeVisitor& nv); + + /** Add Node to Group. + * If node is not NULL and is not contained in Group then increment its + * reference count, add it to the child list and dirty the bounding + * sphere to force it to recompute on next getBound() and return true for success. + * Otherwise return false. Scene nodes can't be added as child nodes. + */ + virtual bool addChild( Node *child ); + + /** Insert Node to Group at specific location. + * The new child node is inserted into the child list + * before the node at the specified index. No nodes + * are removed from the group with this operation. + */ + virtual bool insertChild( unsigned int index, Node *child ); + + /** Remove Node from Group. + * If Node is contained in Group then remove it from the child + * list, decrement its reference count, and dirty the + * bounding sphere to force it to recompute on next getBound() and + * return true for success. If Node is not found then return false + * and do not change the reference count of the Node. + * Note, do not override, only override removeChildren(,) is required. + */ + inline bool removeChild( Node *child ) + { + unsigned int pos = getChildIndex(child); + if (pos<_children.size()) return removeChildren(pos,1); + else return false; + } + + /** Remove Node from Group. + * If Node is contained in Group then remove it from the child + * list, decrement its reference count, and dirty the + * bounding sphere to force it to recompute on next getBound() and + * return true for success. If Node is not found then return false + * and do not change the reference count of the Node. + * Note, do not override, only override removeChildren(,) is required. + */ + inline bool removeChild( unsigned int pos, unsigned int numChildrenToRemove=1 ) + { + if (pos<_children.size()) return removeChildren(pos,numChildrenToRemove); + else return false; + } + + /** Remove children from Group. + * Note, must be override by subclasses of Group which add per child attributes.*/ + virtual bool removeChildren(unsigned int pos,unsigned int numChildrenToRemove); + + /** Replace specified Node with another Node. + * Equivalent to setChild(getChildIndex(orignChild),node) + * See docs for setChild for further details on implementation. + */ + virtual bool replaceChild( Node *origChild, Node* newChild ); + + /** Return the number of children nodes. */ + inline unsigned int getNumChildren() const { return static_cast(_children.size()); } + + /** Set child node at position i. + * Return true if set correctly, false on failure (if node==NULL || i is out of range). + * When Set can be successful applied, the algorithm is : decrement the reference count origNode and increment the + * reference count of newNode, and dirty the bounding sphere + * to force it to recompute on next getBound() and return true. + * If origNode is not found then return false and do not + * add newNode. If newNode is NULL then return false and do + * not remove origNode. Also returns false if newChild is a Scene node. + */ + virtual bool setChild( unsigned int i, Node* node ); + + /** Return child node at position i. */ + inline Node* getChild( unsigned int i ) { return _children[i].get(); } + + /** Return child node at position i. */ + inline const Node* getChild( unsigned int i ) const { return _children[i].get(); } + + /** Return true if node is contained within Group. */ + inline bool containsNode( const Node* node ) const + { + + for (NodeList::const_iterator itr=_children.begin(); + itr!=_children.end(); + ++itr) + { + if (itr->get()==node) return true; + } + return false; + } + + /** Get the index number of child, return a value between + * 0 and _children.size()-1 if found, if not found then + * return _children.size(). + */ + inline unsigned int getChildIndex( const Node* node ) const + { + for (unsigned int childNum=0;childNum<_children.size();++childNum) + { + if (_children[childNum]==node) return childNum; + } + return static_cast(_children.size()); // node not found. + } + + /** Set whether to use a mutex to ensure ref() and unref() are thread safe.*/ + virtual void setThreadSafeRefUnref(bool threadSafe); + + /** Resize any per context GLObject buffers to specified size. */ + virtual void resizeGLObjectBuffers(unsigned int maxSize); + + /** If State is non-zero, this function releases any associated OpenGL objects for + * the specified graphics context. Otherwise, releases OpenGL objects + * for all graphics contexts. */ + virtual void releaseGLObjects(osg::State* = 0) const; + + virtual BoundingSphere computeBound() const; + + protected: + + virtual ~Group(); + + virtual void childRemoved(unsigned int /*pos*/, unsigned int /*numChildrenToRemove*/) {} + virtual void childInserted(unsigned int /*pos*/) {} + + NodeList _children; + + +}; + +} + +#endif diff --git a/libs/include/android/osg/Hint b/libs/include/android/osg/Hint new file mode 100755 index 0000000..274af53 --- /dev/null +++ b/libs/include/android/osg/Hint @@ -0,0 +1,81 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_HINT +#define OSG_HINT 1 + +#include + +namespace osg +{ + +class OSG_EXPORT Hint : public StateAttribute +{ +public: + + Hint(): + _target(GL_NONE), + _mode(GL_DONT_CARE) {} + + Hint(GLenum target, GLenum mode): + _target(target), + _mode(mode) {} + + /** Copy constructor using CopyOp to manage deep vs shallow copy.*/ + Hint(const Hint& hint,const CopyOp& copyop=CopyOp::SHALLOW_COPY): + StateAttribute(hint,copyop), + _target(hint._target), + _mode(hint._mode) {} + + virtual osg::Object* cloneType() const { return new Hint( _target, GL_DONT_CARE ); } + virtual osg::Object* clone(const osg::CopyOp& copyop) const { return new Hint(*this,copyop); } + virtual bool isSameKindAs(const osg::Object* obj) const { return dynamic_cast(obj)!=NULL; } + virtual const char* libraryName() const { return "osg"; } + virtual const char* className() const { return "Hint"; } + virtual Type getType() const { return HINT; } + + virtual int compare(const StateAttribute& sa) const + { + // check the types are equal and then create the rhs variable + // used by the COMPARE_StateAttribute_Parameter macros below. + COMPARE_StateAttribute_Types(Hint,sa) + + // compare each parameter in turn against the rhs. + COMPARE_StateAttribute_Parameter(_target) + COMPARE_StateAttribute_Parameter(_mode) + + return 0; + } + + /** Return the member identifier within the attribute's class type. Used for light number/clip plane number etc.*/ + virtual unsigned int getMember() const { return static_cast(_target); } + + void setTarget(GLenum target); + inline GLenum getTarget() const { return _target; } + + inline void setMode(GLenum mode) { _mode = mode; } + inline GLenum getMode() const { return _mode; } + + virtual void apply(State& state) const; + +protected: + + + GLenum _target; + GLenum _mode; +}; + + +} + +#endif diff --git a/libs/include/android/osg/Image b/libs/include/android/osg/Image new file mode 100755 index 0000000..fb2dcaa --- /dev/null +++ b/libs/include/android/osg/Image @@ -0,0 +1,531 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_IMAGE +#define OSG_IMAGE 1 + +#include +#include +#include +#include +#include +#include + +#include +#include + +#ifndef GL_VERSION_1_2 + // 1.2 definitions... + #define GL_BGR 0x80E0 + #define GL_BGRA 0x80E1 + #define GL_UNSIGNED_BYTE_3_3_2 0x8032 + #define GL_UNSIGNED_BYTE_2_3_3_REV 0x8362 + #define GL_UNSIGNED_SHORT_5_6_5 0x8363 + #define GL_UNSIGNED_SHORT_5_6_5_REV 0x8364 + #define GL_UNSIGNED_SHORT_4_4_4_4 0x8033 + #define GL_UNSIGNED_SHORT_4_4_4_4_REV 0x8365 + #define GL_UNSIGNED_SHORT_5_5_5_1 0x8034 + #define GL_UNSIGNED_SHORT_1_5_5_5_REV 0x8366 + #define GL_UNSIGNED_INT_8_8_8_8 0x8035 + #define GL_UNSIGNED_INT_8_8_8_8_REV 0x8367 + #define GL_UNSIGNED_INT_10_10_10_2 0x8036 + #define GL_UNSIGNED_INT_2_10_10_10_REV 0x8368 +#endif + +#ifndef GL_COMPRESSED_ALPHA + #define GL_COMPRESSED_ALPHA 0x84E9 + #define GL_COMPRESSED_LUMINANCE 0x84EA + #define GL_COMPRESSED_LUMINANCE_ALPHA 0x84EB + #define GL_COMPRESSED_INTENSITY 0x84EC + #define GL_COMPRESSED_RGB 0x84ED + #define GL_COMPRESSED_RGBA 0x84EE +#endif + + +#ifndef GL_ABGR_EXT +#define GL_ABGR_EXT 0x8000 +#endif + +#if defined(OSG_GLES1_AVAILABLE) || defined(OSG_GLES2_AVAILABLE) + #define GL_RED 0x1903 + #define GL_GREEN 0x1904 + #define GL_BLUE 0x1905 + #define GL_DEPTH_COMPONENT 0x1902 + #define GL_STENCIL_INDEX 0x1901 +#endif + +#if defined(OSG_GLES1_AVAILABLE) || defined(OSG_GLES2_AVAILABLE) || defined(OSG_GL3_AVAILABLE) + #define GL_BITMAP 0x1A00 + #define GL_COLOR_INDEX 0x1900 + #define GL_INTENSITY12 0x804C + #define GL_INTENSITY16 0x804D + #define GL_INTENSITY4 0x804A + #define GL_INTENSITY8 0x804B + #define GL_LUMINANCE12 0x8041 + #define GL_LUMINANCE12_ALPHA4 0x8046 + #define GL_LUMINANCE12_ALPHA12 0x8047 + #define GL_LUMINANCE16 0x8042 + #define GL_LUMINANCE16_ALPHA16 0x8048 + #define GL_LUMINANCE4 0x803F + #define GL_LUMINANCE4_ALPHA4 0x8043 + #define GL_LUMINANCE6_ALPHA2 0x8044 + #define GL_LUMINANCE8 0x8040 + #define GL_LUMINANCE8_ALPHA8 0x8045 + #define GL_RGBA8 0x8058 + #define GL_RGBA16 0x805B + #define GL_PACK_ROW_LENGTH 0x0D02 +#endif + +#ifndef GL_PACK_SKIP_IMAGES + #define GL_PACK_SKIP_IMAGES 0x806B + #define GL_PACK_IMAGE_HEIGHT 0x806C + #define GL_UNPACK_SKIP_IMAGES 0x806D + #define GL_UNPACK_IMAGE_HEIGHT 0x806E +#endif + +#ifndef GL_OES_compressed_ETC1_RGB8_texture + #define GL_ETC1_RGB8_OES 0x8D64 +#endif + +#ifndef GL_DEPTH_COMPONENT +#define GL_DEPTH_COMPONENT 0x1902 +#endif + +#ifndef GL_VERSION_1_4 +#define GL_DEPTH_COMPONENT16 0x81A5 +#define GL_DEPTH_COMPONENT24 0x81A6 +#define GL_DEPTH_COMPONENT32 0x81A7 +#endif + +#ifndef GL_DEPTH_COMPONENT32F +#define GL_DEPTH_COMPONENT32F 0x8CAC +#endif + +#ifndef GL_DEPTH_COMPONENT32F_NV +#define GL_DEPTH_COMPONENT32F_NV 0x8DAB +#endif + +namespace osg { + +// forward declare +class NodeVisitor; + +/** Image class for encapsulating the storage texture image data. */ +class OSG_EXPORT Image : public BufferData +{ + + public : + + Image(); + + /** Copy constructor using CopyOp to manage deep vs shallow copy. */ + Image(const Image& image,const CopyOp& copyop=CopyOp::SHALLOW_COPY); + + virtual Object* cloneType() const { return new Image(); } + virtual Object* clone(const CopyOp& copyop) const { return new Image(*this,copyop); } + virtual bool isSameKindAs(const Object* obj) const { return dynamic_cast(obj)!=0; } + virtual const char* libraryName() const { return "osg"; } + virtual const char* className() const { return "Image"; } + + virtual osg::Image* asImage() { return this; } + virtual const osg::Image* asImage() const { return this; } + + virtual const GLvoid* getDataPointer() const { return data(); } + virtual unsigned int getTotalDataSize() const { return getTotalSizeInBytesIncludingMipmaps(); } + + /** Return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs. */ + virtual int compare(const Image& rhs) const; + + void setFileName(const std::string& fileName); + inline const std::string& getFileName() const { return _fileName; } + + enum WriteHint { + NO_PREFERENCE, + STORE_INLINE, + EXTERNAL_FILE + }; + + void setWriteHint(WriteHint writeHint) { _writeHint = writeHint; } + WriteHint getWriteHint() const { return _writeHint; } + + enum AllocationMode { + NO_DELETE, + USE_NEW_DELETE, + USE_MALLOC_FREE + }; + + /** Set the method used for deleting data once it goes out of scope. */ + void setAllocationMode(AllocationMode mode) { _allocationMode = mode; } + + /** Get the method used for deleting data once it goes out of scope. */ + AllocationMode getAllocationMode() const { return _allocationMode; } + + + /** Allocate a pixel block of specified size and type. */ + virtual void allocateImage(int s,int t,int r, + GLenum pixelFormat,GLenum type, + int packing=1); + + + /** Set the image dimensions, format and data. */ + virtual void setImage(int s,int t,int r, + GLint internalTextureformat, + GLenum pixelFormat,GLenum type, + unsigned char* data, + AllocationMode mode, + int packing=1, int rowLength=0); + + /** Read pixels from current frame buffer at specified position and size, using glReadPixels. + * Create memory for storage if required, reuse existing pixel coords if possible. + */ + virtual void readPixels(int x,int y,int width,int height, + GLenum pixelFormat, GLenum type, int packing=1); + + + /** Read the contents of the current bound texture, handling compressed pixelFormats if present. + * Create memory for storage if required, reuse existing pixel coords if possible. + */ + virtual void readImageFromCurrentTexture(unsigned int contextID, bool copyMipMapsIfAvailable, GLenum type = GL_UNSIGNED_BYTE, unsigned int face = 0); + + /** swap the data and settings between two image objects.*/ + void swap(osg::Image& rhs); + + /** Scale image to specified size. */ + void scaleImage(int s,int t,int r) { scaleImage(s,t,r, getDataType()); } + + /** Scale image to specified size and with specified data type. */ + virtual void scaleImage(int s,int t,int r, GLenum newDataType); + + /** Copy a source Image into a subpart of this Image at specified position. + * Typically used to copy to an already allocated image, such as creating + * a 3D image from a stack 2D images. + * If this Image is empty then image data is created to + * accomodate the source image in its offset position. + * If source is NULL then no operation happens, this Image is left unchanged. + */ + virtual void copySubImage(int s_offset, int t_offset, int r_offset, const osg::Image* source); + + + enum Origin + { + BOTTOM_LEFT, + TOP_LEFT + }; + + /** Set the origin of the image. + * The default value is BOTTOM_LEFT and is consistent with OpenGL. + * TOP_LEFT is used for imagery that follows standard Imagery convention, such as movies, + * and hasn't been flipped yet. For such images one much flip the t axis of the tex coords. + * to handle this origin position. */ + void setOrigin(Origin origin) { _origin = origin; } + + /** Get the origin of the image.*/ + Origin getOrigin() const { return _origin; } + + + /** Width of image. */ + inline int s() const { return _s; } + + /** Height of image. */ + inline int t() const { return _t; } + + /** Depth of image. */ + inline int r() const { return _r; } + + void setRowLength(int length); + inline int getRowLength() const { return _rowLength; } + + void setInternalTextureFormat(GLint internalFormat); + inline GLint getInternalTextureFormat() const { return _internalTextureFormat; } + + void setPixelFormat(GLenum pixelFormat); + inline GLenum getPixelFormat() const { return _pixelFormat; } + + void setDataType(GLenum dataType); + inline GLenum getDataType() const { return _dataType; } + + void setPacking(unsigned int packing) { _packing = packing; } + inline unsigned int getPacking() const { return _packing; } + + /** Return true of the pixel format is an OpenGL compressed pixel format.*/ + bool isCompressed() const; + + /** Set the pixel aspect ratio, defined as the pixel width divided by the pixel height.*/ + inline void setPixelAspectRatio(float pixelAspectRatio) { _pixelAspectRatio = pixelAspectRatio; } + + /** Get the pixel aspect ratio.*/ + inline float getPixelAspectRatio() const { return _pixelAspectRatio; } + + /** Return the number of bits required for each pixel. */ + inline unsigned int getPixelSizeInBits() const { return computePixelSizeInBits(_pixelFormat,_dataType); } + + /** Return the number of bytes each row of pixels occupies once it has been packed. */ + inline unsigned int getRowSizeInBytes() const { return computeRowWidthInBytes(_s,_pixelFormat,_dataType,_packing); } + + /** Return the number of bytes between each successive row. + * Note, getRowSizeInBytes() will only equal getRowStepInBytes() when isDataContiguous() return true. */ + inline unsigned int getRowStepInBytes() const { return computeRowWidthInBytes(_rowLength==0?_s:_rowLength,_pixelFormat,_dataType,_packing); } + + /** Return the number of bytes each image (_s*_t) of pixels occupies. */ + inline unsigned int getImageSizeInBytes() const { return getRowSizeInBytes()*_t; } + + /** Return the number of bytes between each successive image. + * Note, getImageSizeInBytes() will only equal getImageStepInBytes() when isDataContiguous() return true. */ + inline unsigned int getImageStepInBytes() const { return getRowStepInBytes()*_t; } + + /** Return the number of bytes the whole row/image/volume of pixels occupies. */ + inline unsigned int getTotalSizeInBytes() const { return getImageSizeInBytes()*_r; } + + /** Return the number of bytes the whole row/image/volume of pixels occupies, including all mip maps if included. */ + unsigned int getTotalSizeInBytesIncludingMipmaps() const; + + /** Return true if the Image represent a valid and usable imagery.*/ + bool valid() const { return _s!=0 && _t!=0 && _r!=0 && _data!=0 && _dataType!=0; } + + /** Raw image data. + * Note, data in successive rows may not be contiguous, isDataContiguous() return false then you should + * take care to access the data per row rather than treating the whole data as a single block. */ + inline unsigned char* data() { return _data; } + + /** Raw const image data. + * Note, data in successive rows may not be contiguous, isDataContiguous() return false then you should + * take care to access the data per row rather than treating the whole data as a single block. */ + inline const unsigned char* data() const { return _data; } + + inline unsigned char* data(unsigned int column, unsigned int row = 0, unsigned int image = 0) + { + if (!_data) return NULL; + return _data+(column*getPixelSizeInBits())/8+row*getRowStepInBytes()+image*getImageSizeInBytes(); + } + + inline const unsigned char* data(unsigned int column, unsigned int row = 0, unsigned int image = 0) const + { + if (!_data) return NULL; + return _data+(column*getPixelSizeInBits())/8+row*getRowStepInBytes()+image*getImageSizeInBytes(); + } + + /** return true if the data stored in the image is a contiguous block of data.*/ + bool isDataContiguous() const { return _rowLength==0 || _rowLength==_s; } + + /** Convenience class for assisting the copying of image data when the image data isn't contiguous.*/ + class OSG_EXPORT DataIterator + { + public: + DataIterator(const Image* image); + DataIterator(const DataIterator& ri); + ~DataIterator() {} + + /** advance iterator to next block of data.*/ + void operator ++ (); + + /** is iterator valid.*/ + bool valid() const { return _currentPtr!=0; } + + /** data pointer of current block to copy.*/ + const unsigned char* data() const { return _currentPtr; } + + /** Size of current block to copy.*/ + unsigned int size() const { return _currentSize; } + + protected: + + + void assign(); + + const osg::Image* _image; + int _rowNum; + int _imageNum; + unsigned int _mipmapNum; + const unsigned char* _currentPtr; + unsigned int _currentSize; + }; + + /** Get the color value for specified texcoord.*/ + Vec4 getColor(unsigned int s,unsigned t=0,unsigned r=0) const; + + /** Get the color value for specified texcoord.*/ + Vec4 getColor(const Vec2& texcoord) const { return getColor(Vec3(texcoord.x(),texcoord.y(),0.0f)); } + + /** Get the color value for specified texcoord.*/ + Vec4 getColor(const Vec3& texcoord) const; + + + /** Flip the image horizontally, around s dimension. */ + void flipHorizontal(); + + /** Flip the image vertically, around t dimension. */ + void flipVertical(); + + /** Flip the image around the r dimension. Only relevent for 3D textures. */ + void flipDepth(); + + /** Ensure image dimensions are a power of two. + * Mipmapped textures require the image dimensions to be + * power of two and are within the maxiumum texture size for + * the host machine. + */ + void ensureValidSizeForTexturing(GLint maxTextureSize); + + static bool isPackedType(GLenum type); + static GLenum computePixelFormat(GLenum pixelFormat); + static GLenum computeFormatDataType(GLenum pixelFormat); + static unsigned int computeBlockSize(GLenum pixelFormat, GLenum packing); + static unsigned int computeNumComponents(GLenum pixelFormat); + static unsigned int computePixelSizeInBits(GLenum pixelFormat,GLenum type); + static unsigned int computeRowWidthInBytes(int width,GLenum pixelFormat,GLenum type,int packing); + static unsigned int computeImageSizeInBytes(int width,int height, int depth, GLenum pixelFormat, GLenum type, int packing = 1, int slice_packing = 1, int image_packing = 1); + static int computeNearestPowerOfTwo(int s,float bias=0.5f); + static int computeNumberOfMipmapLevels(int s,int t = 1, int r = 1); + + /** Precomputed mipmaps stuff. */ + typedef std::vector< unsigned int > MipmapDataType; + + inline bool isMipmap() const {return !_mipmapData.empty();}; + + unsigned int getNumMipmapLevels() const + { + return static_cast(_mipmapData.size())+1; + }; + + /** Send offsets into data. It is assumed that first mipmap offset (index 0) is 0.*/ + inline void setMipmapLevels(const MipmapDataType& mipmapDataVector) { _mipmapData = mipmapDataVector; } + + inline const MipmapDataType& getMipmapLevels() const { return _mipmapData; } + + inline unsigned int getMipmapOffset(unsigned int mipmapLevel) const + { + if(mipmapLevel == 0) + return 0; + else if (mipmapLevel < getNumMipmapLevels()) + return _mipmapData[mipmapLevel-1]; + return 0; + }; + + inline unsigned char* getMipmapData(unsigned int mipmapLevel) + { + return _data+getMipmapOffset(mipmapLevel); + } + + inline const unsigned char* getMipmapData(unsigned int mipmapLevel) const + { + return _data+getMipmapOffset(mipmapLevel); + } + + /** returns false for texture formats that do not support texture subloading */ + bool supportsTextureSubloading() const; + + /** Return true if this image is translucent - i.e. it has alpha values that are less 1.0 (when normalized). */ + virtual bool isImageTranslucent() const; + + /** Set the optional PixelBufferObject used to map the image memory efficiently to graphics memory. */ + void setPixelBufferObject(PixelBufferObject* buffer) { setBufferObject(buffer); } + + /** Get the PixelBufferObject.*/ + PixelBufferObject* getPixelBufferObject() { return dynamic_cast(getBufferObject()); } + + /** Get the const PixelBufferObject.*/ + const PixelBufferObject* getPixelBufferObject() const { return dynamic_cast(getBufferObject()); } + + /** Return whether the update(NodeVisitor* nv) should be required on each frame to enable proper working of osg::Image.*/ + virtual bool requiresUpdateCall() const { return false; } + + /** update method for osg::Image subclasses that update themselves during the update traversal.*/ + virtual void update(NodeVisitor* /*nv*/) {} + + /** Convenience update callback class that can be attached to a StateAttribute (such as Textures) to ensure + * that the Image::update(NodeVisitor*) method is called during the update traversal. This callback + * is automatically attached when Image::requiresUpdateCall() is true (it's false by default.) + */ + struct OSG_EXPORT UpdateCallback : public osg::StateAttributeCallback + { + virtual void operator () (osg::StateAttribute* attr, osg::NodeVisitor* nv); + }; + + /** Hint whether to enable or disable focus to images acting as front ends to interactive surfaces such as a vnc or browser window. Return true if handled. */ + virtual bool sendFocusHint(bool /*focus*/) { return false; } + + /** Send pointer events to images that are acting as front ends to interactive surfaces such as a vnc or browser window. Return true if handled. */ + virtual bool sendPointerEvent(int /*x*/, int /*y*/, int /*buttonMask*/) { return false; } + + /** Send key events to images that are acting as front ends to interactive surfaces such as a vnc or browser window. Return true if handled.*/ + virtual bool sendKeyEvent(int /*key*/, bool /*keyDown*/) { return false; } + + /** Pass frame information to the custom Image classes, to be called only when objects associated with imagery are not culled.*/ + virtual void setFrameLastRendered(const osg::FrameStamp* /*frameStamp*/) {} + + class DimensionsChangedCallback : public osg::Referenced { + public: + DimensionsChangedCallback() : osg::Referenced() {} + virtual void operator()(osg::Image* image) = 0; + }; + + typedef std::vector< osg::ref_ptr > DimensionsChangedCallbackVector; + + void addDimensionsChangedCallback(DimensionsChangedCallback* cb); + void removeDimensionsChangedCallback(DimensionsChangedCallback* cb); + + protected : + + virtual ~Image(); + + Image& operator = (const Image&) { return *this; } + + void handleDimensionsChangedCallbacks() + { + for(DimensionsChangedCallbackVector::iterator i = _dimensionsChangedCallbacks.begin(); i != _dimensionsChangedCallbacks.end(); ++i) + { + (*i)->operator()(this); + } + } + + std::string _fileName; + WriteHint _writeHint; + + Origin _origin; + + int _s, _t, _r; + int _rowLength; + GLint _internalTextureFormat; + GLenum _pixelFormat; + GLenum _dataType; + unsigned int _packing; + float _pixelAspectRatio; + + AllocationMode _allocationMode; + unsigned char* _data; + + void deallocateData(); + + void setData(unsigned char* data,AllocationMode allocationMode); + + MipmapDataType _mipmapData; + + DimensionsChangedCallbackVector _dimensionsChangedCallbacks; +}; + +class Geode; + +/** Convenience function to be used by image loaders to generate a valid geode + * to return for readNode(). + * Use the image's s and t values to scale the dimensions of the image. +*/ +extern OSG_EXPORT Geode* createGeodeForImage(Image* image); +/** Convenience function to be used by image loaders to generate a valid geode + * to return for readNode(). + * Use the specified s and t values to scale the dimensions of the image. +*/ +extern OSG_EXPORT Geode* createGeodeForImage(Image* image,float s,float t); + +} + +#endif // __SG_IMAGE_H diff --git a/libs/include/android/osg/ImageSequence b/libs/include/android/osg/ImageSequence new file mode 100755 index 0000000..ad675fc --- /dev/null +++ b/libs/include/android/osg/ImageSequence @@ -0,0 +1,167 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_IMAGESEQUENCE +#define OSG_IMAGESEQUENCE 1 + +#include +#include + +#include +#include + +namespace osg { + +/** + * Image Buffer class. +*/ +class OSG_EXPORT ImageSequence : public ImageStream +{ + public: + ImageSequence(); + + /** Copy constructor using CopyOp to manage deep vs shallow copy. */ + ImageSequence(const ImageSequence& ImageSequence, const CopyOp& copyop=CopyOp::SHALLOW_COPY); + + virtual Object* cloneType() const { return new ImageSequence(); } + virtual Object* clone(const CopyOp& copyop) const { return new ImageSequence(*this,copyop); } + virtual bool isSameKindAs(const Object* obj) const { return dynamic_cast(obj)!=0; } + virtual const char* libraryName() const { return "osg"; } + virtual const char* className() const { return "ImageSequence"; } + + /** Return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs. */ + virtual int compare(const Image& rhs) const; + + virtual void setReferenceTime(double t) { _referenceTime = t; } + virtual double getReferenceTime() const { return _referenceTime; } + + virtual void setTimeMultiplier(double tm) { _timeMultiplier = tm; } + virtual double getTimeMultiplier() const { return _timeMultiplier; } + + struct OSG_EXPORT ImageData + { + ImageData(); + ImageData(const ImageData& id); + ImageData& operator = (const ImageData& id); + + std::string _filename; + osg::ref_ptr _image; + osg::ref_ptr _imageRequest; + }; + + typedef std::vector ImageDataList; + + virtual void seek(double time); + + virtual void play(); + + virtual void pause(); + + virtual void rewind(); + + enum Mode + { + PRE_LOAD_ALL_IMAGES, + PAGE_AND_RETAIN_IMAGES, + PAGE_AND_DISCARD_USED_IMAGES, + LOAD_AND_RETAIN_IN_UPDATE_TRAVERSAL, + LOAD_AND_DISCARD_IN_UPDATE_TRAVERSAL + }; + + void setMode(Mode mode); + Mode getMode() const { return _mode; } + + void setLength(double length); + virtual double getLength() const { return _length; } + + + void addImageFile(const std::string& fileName); + + void setImageFile(unsigned int pos, const std::string& fileName); + std::string getImageFile(unsigned int pos) const; + + void addImage(osg::Image* image); + + void setImage(int s,int t,int r, + GLint internalTextureformat, + GLenum pixelFormat,GLenum type, + unsigned char* data, + AllocationMode mode, + int packing=1) { Image::setImage(s,t,r,internalTextureformat, pixelFormat, type, data, mode, packing); } + + void setImage(unsigned int pos, osg::Image* image); + Image* getImage(unsigned int pos); + const Image* getImage(unsigned int pos) const; + + unsigned int getNumImageData() const { return _imageDataList.size(); } + + ImageDataList& getImageDataList() { return _imageDataList; } + const ImageDataList& getImageDataList() const { return _imageDataList; } + + + /** ImageSequence requires a call to update(NodeVisitor*) during the update traversal so return true.*/ + virtual bool requiresUpdateCall() const { return true; } + + /** update method for osg::Image subclasses that update themselves during the update traversal.*/ + virtual void update(NodeVisitor* nv); + + + /** Set the optional osgDB::Options object to use when reading images.*/ + void setReadOptions(osg::Referenced* options) { _readOptions = options; } + + /** Get the optional osgDB::Options object used when reading images.*/ + osg::Referenced* getReadOptions() { return _readOptions.get(); } + + /** Get the optional osgDB::Options object used when reading images.*/ + const osg::Referenced* getReadOptions() const { return _readOptions.get(); } + +protected: + + virtual ~ImageSequence() {} + + virtual void applyLoopingMode(); + + void setImageToChild(int pos); + + void computeTimePerImage(); + + int imageIndex(double time); + + // setImage without aquiring mutex. + void _setImage(unsigned int pos, osg::Image* image); + + double _referenceTime; + double _timeMultiplier; + + Mode _mode; + double _length; + + double _timePerImage; + + mutable OpenThreads::Mutex _mutex; + + ImageDataList _imageDataList; + + int _previousAppliedImageIndex; + + + bool _seekTimeSet; + double _seekTime; + + osg::ref_ptr _readOptions; + +}; + +} // namespace + +#endif diff --git a/libs/include/android/osg/ImageStream b/libs/include/android/osg/ImageStream new file mode 100755 index 0000000..f0fc235 --- /dev/null +++ b/libs/include/android/osg/ImageStream @@ -0,0 +1,124 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_IMAGESTREAM +#define OSG_IMAGESTREAM 1 + +#include +#include + +namespace osg { + +// forward declare of osg::Texture +class Texture; + +/** + * Image Stream class. +*/ +class OSG_EXPORT ImageStream : public Image +{ + public: + ImageStream(); + + /** Copy constructor using CopyOp to manage deep vs shallow copy. */ + ImageStream(const ImageStream& image,const CopyOp& copyop=CopyOp::SHALLOW_COPY); + + virtual Object* cloneType() const { return new ImageStream(); } + virtual Object* clone(const CopyOp& copyop) const { return new ImageStream(*this,copyop); } + virtual bool isSameKindAs(const Object* obj) const { return dynamic_cast(obj)!=0; } + virtual const char* libraryName() const { return "osg"; } + virtual const char* className() const { return "ImageStream"; } + + /** Return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs. */ + virtual int compare(const Image& rhs) const; + + enum StreamStatus + { + INVALID, + PLAYING, + PAUSED, + REWINDING + }; + + virtual void seek(double /*time*/) {} + + virtual void play() { _status=PLAYING; } + + virtual void pause() { _status=PAUSED; } + + virtual void rewind() { _status=REWINDING; } + + virtual void quit(bool /*waitForThreadToExit*/ = true) {} + + StreamStatus getStatus() const { return _status; } + + + enum LoopingMode + { + NO_LOOPING, + LOOPING + }; + + void setLoopingMode(LoopingMode mode) + { + if (_loopingMode == mode) return; + + _loopingMode = mode; + applyLoopingMode(); + } + + LoopingMode getLoopingMode() const { return _loopingMode; } + + virtual double getCreationTime() const { return HUGE_VAL; } + virtual double getLength() const { return 0.0; } + virtual double getFrameRate() const { return 0.0; } + virtual double getCurrentTime() const { return 0.0; } + + virtual void setReferenceTime(double) {} + virtual double getReferenceTime() const { return 0.0; } + + virtual void setTimeMultiplier(double) {} + virtual double getTimeMultiplier() const { return 0.0; } + + virtual void setVolume(float) {} + virtual float getVolume() const { return 0.0f; } + + /// set the balance of the audio: -1 = left, 0 = center, 1 = right + virtual float getAudioBalance() { return 0.0f; } + virtual void setAudioBalance(float /*b*/) {} + + typedef std::vector< osg::ref_ptr > AudioStreams; + void setAudioStreams(const AudioStreams& asl) { _audioStreams = asl; } + AudioStreams& getAudioStreams() { return _audioStreams; } + const AudioStreams& getAudioStreams() const { return _audioStreams; } + + /** create a suitable texture for this imagestream, return NULL, if not supported + * implement this method in subclasses to use special technologies like CoreVideo + * or similar. + */ + virtual osg::Texture* createSuitableTexture() { return NULL; } + + protected: + virtual void applyLoopingMode() {} + + virtual ~ImageStream() {} + + StreamStatus _status; + LoopingMode _loopingMode; + + AudioStreams _audioStreams; +}; + +} // namespace + +#endif diff --git a/libs/include/android/osg/ImageUtils b/libs/include/android/osg/ImageUtils new file mode 100755 index 0000000..ba3ab70 --- /dev/null +++ b/libs/include/android/osg/ImageUtils @@ -0,0 +1,180 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_IMAGEUTILS +#define OSG_IMAGEUTILS 1 + +#include + +#include + +namespace osg { + +template +void _readRow(unsigned int num, GLenum pixelFormat, const T* data,float scale, O& operation) +{ + switch(pixelFormat) + { + case(GL_LUMINANCE): { for(unsigned int i=0;i +void readRow(unsigned int num, GLenum pixelFormat, GLenum dataType, const unsigned char* data, O& operation) +{ + switch(dataType) + { + case(GL_BYTE): _readRow(num,pixelFormat, (const char*)data, 1.0f/128.0f, operation); break; + case(GL_UNSIGNED_BYTE): _readRow(num,pixelFormat, (const unsigned char*)data, 1.0f/255.0f, operation); break; + case(GL_SHORT): _readRow(num,pixelFormat, (const short*) data, 1.0f/32768.0f, operation); break; + case(GL_UNSIGNED_SHORT): _readRow(num,pixelFormat, (const unsigned short*)data, 1.0f/65535.0f, operation); break; + case(GL_INT): _readRow(num,pixelFormat, (const int*) data, 1.0f/2147483648.0f, operation); break; + case(GL_UNSIGNED_INT): _readRow(num,pixelFormat, (const unsigned int*) data, 1.0f/4294967295.0f, operation); break; + case(GL_FLOAT): _readRow(num,pixelFormat, (const float*) data, 1.0f, operation); break; + } +} + +template +void readImage(const osg::Image* image, O& operation) +{ + if (!image) return; + + for(int r=0;rr();++r) + { + for(int t=0;tt();++t) + { + readRow(image->s(), image->getPixelFormat(), image->getDataType(), image->data(0,t,r), operation); + } + } +} + +// example ModifyOperator +// struct ModifyOperator +// { +// inline void luminance(float& l) const {} +// inline void alpha(float& a) const {} +// inline void luminance_alpha(float& l,float& a) const {} +// inline void rgb(float& r,float& g,float& b) const {} +// inline void rgba(float& r,float& g,float& b,float& a) const {} +// }; + + +template +void _modifyRow(unsigned int num, GLenum pixelFormat, T* data,float scale, const M& operation) +{ + float inv_scale = 1.0f/scale; + switch(pixelFormat) + { + case(GL_LUMINANCE): { for(unsigned int i=0;i +void modifyRow(unsigned int num, GLenum pixelFormat, GLenum dataType, unsigned char* data, const M& operation) +{ + switch(dataType) + { + case(GL_BYTE): _modifyRow(num,pixelFormat, (char*)data, 1.0f/128.0f, operation); break; + case(GL_UNSIGNED_BYTE): _modifyRow(num,pixelFormat, (unsigned char*)data, 1.0f/255.0f, operation); break; + case(GL_SHORT): _modifyRow(num,pixelFormat, (short*) data, 1.0f/32768.0f, operation); break; + case(GL_UNSIGNED_SHORT): _modifyRow(num,pixelFormat, (unsigned short*)data, 1.0f/65535.0f, operation); break; + case(GL_INT): _modifyRow(num,pixelFormat, (int*) data, 1.0f/2147483648.0f, operation); break; + case(GL_UNSIGNED_INT): _modifyRow(num,pixelFormat, (unsigned int*) data, 1.0f/4294967295.0f, operation); break; + case(GL_FLOAT): _modifyRow(num,pixelFormat, (float*) data, 1.0f, operation); break; + } +} + +template +void modifyImage(osg::Image* image, const M& operation) +{ + if (!image) return; + + for(int r=0;rr();++r) + { + for(int t=0;tt();++t) + { + modifyRow(image->s(), image->getPixelFormat(), image->getDataType(), image->data(0,t,r), operation); + } + } +} + +/** Compute the min max colour values in the image.*/ +extern OSG_EXPORT bool computeMinMax(const osg::Image* image, osg::Vec4& min, osg::Vec4& max); + +/** Compute the min max colour values in the image.*/ +extern OSG_EXPORT bool offsetAndScaleImage(osg::Image* image, const osg::Vec4& offset, const osg::Vec4& scale); + +/** Compute source image to destination image.*/ +extern OSG_EXPORT bool copyImage(const osg::Image* srcImage, int src_s, int src_t, int src_r, int width, int height, int depth, + osg::Image* destImage, int dest_s, int dest_t, int dest_r, bool doRescale = false); + +/** Compute the min max colour values in the image.*/ +extern OSG_EXPORT bool clearImageToColor(osg::Image* image, const osg::Vec4& colour); + +typedef std::vector< osg::ref_ptr > ImageList; + +/** Search through the list of Images and find the maximum number of components used amoung the images.*/ +extern OSG_EXPORT unsigned int maximimNumOfComponents(const ImageList& imageList); + +/** create a 3D osg::Image from a list of osg::Image.*/ +extern OSG_EXPORT osg::Image* createImage3D(const ImageList& imageList, + GLenum desiredPixelFormat, + int s_maximumImageSize = 1024, + int t_maximumImageSize = 1024, + int r_maximumImageSize = 1024, + bool resizeToPowerOfTwo = false); + +/** create a 3D osg::Image from a list of osg::Image.*/ +extern OSG_EXPORT osg::Image* createImage3DWithAlpha(const ImageList& imageList, + int s_maximumImageSize = 1024, + int t_maximumImageSize = 1024, + int r_maximumImageSize = 1024, + bool resizeToPowerOfTwo = false); + + + + +/** create a 2D osg::Image that provides a point at the center of the image. + * The colour across th image is computed from a balance between the center color and the background color controlled by the power of the radius from the center.*/ +extern OSG_EXPORT osg::Image* createSpotLightImage(const osg::Vec4& centerColour, const osg::Vec4& backgroudColour, unsigned int size, float power); + + +enum ColorSpaceOperation +{ + NO_COLOR_SPACE_OPERATION, + MODULATE_ALPHA_BY_LUMINANCE, + MODULATE_ALPHA_BY_COLOR, + REPLACE_ALPHA_WITH_LUMINANCE, + REPLACE_RGB_WITH_LUMINANCE +}; + +/** Convert the RGBA values in a Image based on a ColorSpaceOperation defined scheme.*/ +extern OSG_EXPORT osg::Image* colorSpaceConversion(ColorSpaceOperation op, osg::Image* image, const osg::Vec4& colour); + + +} + + +#endif diff --git a/libs/include/android/osg/KdTree b/libs/include/android/osg/KdTree new file mode 100755 index 0000000..86dee73 --- /dev/null +++ b/libs/include/android/osg/KdTree @@ -0,0 +1,198 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_KDTREE +#define OSG_KDTREE 1 + +#include +#include + +#include + +namespace osg +{ + +/** Implementation of a kdtree for Geometry leaves, to enable fast intersection tests.*/ +class OSG_EXPORT KdTree : public osg::Shape +{ + public: + + + KdTree(); + + KdTree(const KdTree& rhs, const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY); + + META_Shape(osg, KdTree) + + struct OSG_EXPORT BuildOptions + { + BuildOptions(); + + unsigned int _numVerticesProcessed; + unsigned int _targetNumTrianglesPerLeaf; + unsigned int _maxNumLevels; + }; + + + /** Build the kdtree from the specified source geometry object. + * retun true on success. */ + virtual bool build(BuildOptions& buildOptions, osg::Geometry* geometry); + + struct LineSegmentIntersection + { + LineSegmentIntersection(): + ratio(-1.0), + p0(0), + p1(0), + p2(0), + r0(0.0f), + r1(0.0f), + r2(0.0f), + primitiveIndex(0) {} + + bool operator < (const LineSegmentIntersection& rhs) const { return ratio < rhs.ratio; } + + typedef std::vector IndexList; + typedef std::vector RatioList; + + double ratio; + osg::Vec3d intersectionPoint; + osg::Vec3 intersectionNormal; + + unsigned int p0; + unsigned int p1; + unsigned int p2; + float r0; + float r1; + float r2; + + unsigned int primitiveIndex; + }; + + + typedef std::vector LineSegmentIntersections; + + /** compute the intersection of a line segment and the kdtree, return true if an intersection has been found.*/ + virtual bool intersect(const osg::Vec3d& start, const osg::Vec3d& end, LineSegmentIntersections& intersections) const; + + + typedef int value_type; + + struct KdNode + { + KdNode(): + first(0), + second(0) {} + + KdNode(value_type f, value_type s): + first(f), + second(s) {} + + osg::BoundingBox bb; + + value_type first; + value_type second; + }; + + struct Triangle + { + Triangle(): + p0(0),p1(0),p2(0) {} + + Triangle(unsigned int ip0, unsigned int ip1, unsigned int ip2): + p0(ip0), p1(ip1), p2(ip2) {} + + bool operator < (const Triangle& rhs) const + { + if (p0rhs.p0) return false; + if (p1rhs.p1) return false; + return p2 KdNodeList; + typedef std::vector< Triangle > TriangleList; + + int addNode(const KdNode& node) + { + int num = static_cast(_kdNodes.size()); + _kdNodes.push_back(node); + return num; + } + + KdNode& getNode(int nodeNum) { return _kdNodes[nodeNum]; } + const KdNode& getNode(int nodeNum) const { return _kdNodes[nodeNum]; } + + KdNodeList& getNodes() { return _kdNodes; } + const KdNodeList& getNodes() const { return _kdNodes; } + + void setVertices(osg::Vec3Array* vertices) { _vertices = vertices; } + const osg::Vec3Array* getVertices() const { return _vertices.get(); } + + unsigned int addTriangle(const Triangle& tri) + { + unsigned int num = static_cast(_triangles.size()); + _triangles.push_back(tri); + return num; + } + + Triangle& getTriangle(unsigned int i) { return _triangles[i]; } + const Triangle& getTriangle(unsigned int i) const { return _triangles[i]; } + + TriangleList& getTriangles() { return _triangles; } + const TriangleList& getTriangles() const { return _triangles; } + + + protected: + + osg::ref_ptr _vertices; + KdNodeList _kdNodes; + TriangleList _triangles; + +}; + +class OSG_EXPORT KdTreeBuilder : public osg::NodeVisitor +{ + public: + + KdTreeBuilder(); + + KdTreeBuilder(const KdTreeBuilder& rhs); + + META_NodeVisitor(osg, KdTreeBuilder) + + virtual KdTreeBuilder* clone() { return new KdTreeBuilder(*this); } + + void apply(osg::Geode& geode); + + KdTree::BuildOptions _buildOptions; + + osg::ref_ptr _kdTreePrototype; + + + + protected: + + virtual ~KdTreeBuilder() {} + +}; + +} + +#endif diff --git a/libs/include/android/osg/LOD b/libs/include/android/osg/LOD new file mode 100755 index 0000000..0d636ec --- /dev/null +++ b/libs/include/android/osg/LOD @@ -0,0 +1,139 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_LOD +#define OSG_LOD 1 + +#include + +namespace osg { + +/** LOD - Level Of Detail group node which allows switching between children + depending on distance from eye point. + Typical uses are for load balancing - objects further away from + the eye point are rendered at a lower level of detail, and at times + of high stress on the graphics pipeline lower levels of detail can + also be chosen by adjusting the viewers's Camera/CullSettings LODScale value. + Each child has a corresponding valid range consisting of a minimum + and maximum distance. Given a distance to the viewer (d), LOD displays + a child if min <= d < max. LOD may display multiple children simultaneously + if their corresponding ranges overlap. Children can be in any order, + and don't need to be sorted by range or amount of detail. If the number of + ranges (m) is less than the number of children (n), then children m+1 through + n are ignored. +*/ +class OSG_EXPORT LOD : public Group +{ + public : + + LOD(); + + /** Copy constructor using CopyOp to manage deep vs shallow copy.*/ + LOD(const LOD&,const CopyOp& copyop=CopyOp::SHALLOW_COPY); + + META_Node(osg, LOD); + + typedef osg::BoundingSphere::vec_type vec_type; + typedef osg::BoundingSphere::value_type value_type; + + virtual void traverse(NodeVisitor& nv); + + virtual bool addChild(Node *child); + + virtual bool addChild(Node *child, float min, float max); + + virtual bool removeChildren(unsigned int pos,unsigned int numChildrenToRemove=1); + + typedef std::pair MinMaxPair; + typedef std::vector RangeList; + + /** Modes which control how the center of object should be determined when computing which child is active.*/ + enum CenterMode + { + USE_BOUNDING_SPHERE_CENTER, + USER_DEFINED_CENTER, + UNION_OF_BOUNDING_SPHERE_AND_USER_DEFINED + }; + + /** Set how the center of object should be determined when computing which child is active.*/ + void setCenterMode(CenterMode mode) { _centerMode=mode; } + + /** Get how the center of object should be determined when computing which child is active.*/ + CenterMode getCenterMode() const { return _centerMode; } + + /** Sets the object-space point which defines the center of the osg::LOD. + center is affected by any transforms in the hierarchy above the osg::LOD.*/ + inline void setCenter(const vec_type& center) { if (_centerMode!=UNION_OF_BOUNDING_SPHERE_AND_USER_DEFINED) { _centerMode=USER_DEFINED_CENTER; } _userDefinedCenter = center; } + + /** return the LOD center point. */ + inline const vec_type& getCenter() const { if ((_centerMode==USER_DEFINED_CENTER)||(_centerMode==UNION_OF_BOUNDING_SPHERE_AND_USER_DEFINED)) return _userDefinedCenter; else return getBound().center(); } + + + /** Set the object-space reference radius of the volume enclosed by the LOD. + * Used to determine the bounding sphere of the LOD in the absence of any children.*/ + inline void setRadius(value_type radius) { _radius = radius; } + + /** Get the object-space radius of the volume enclosed by the LOD.*/ + inline value_type getRadius() const { return _radius; } + + /** Modes that control how the range values should be interpreted when computing which child is active.*/ + enum RangeMode + { + DISTANCE_FROM_EYE_POINT, + PIXEL_SIZE_ON_SCREEN + }; + + /** Set how the range values should be interpreted when computing which child is active.*/ + void setRangeMode(RangeMode mode) { _rangeMode = mode; } + + /** Get how the range values should be interpreted when computing which child is active.*/ + RangeMode getRangeMode() const { return _rangeMode; } + + + /** Sets the min and max visible ranges of range of specific child. + Values are floating point distance specified in local objects coordinates.*/ + void setRange(unsigned int childNo, float min,float max); + + /** returns the min visible range for specified child.*/ + inline float getMinRange(unsigned int childNo) const { return _rangeList[childNo].first; } + + /** returns the max visible range for specified child.*/ + inline float getMaxRange(unsigned int childNo) const { return _rangeList[childNo].second; } + + /** returns the number of ranges currently set. + * An LOD which has been fully set up will have getNumChildren()==getNumRanges(). */ + inline unsigned int getNumRanges() const { return static_cast(_rangeList.size()); } + + /** set the list of MinMax ranges for each child.*/ + inline void setRangeList(const RangeList& rangeList) { _rangeList=rangeList; } + + /** return the list of MinMax ranges for each child.*/ + inline const RangeList& getRangeList() const { return _rangeList; } + + virtual BoundingSphere computeBound() const; + + protected : + virtual ~LOD() {} + + CenterMode _centerMode; + vec_type _userDefinedCenter; + value_type _radius; + + RangeMode _rangeMode; + RangeList _rangeList; + +}; + +} + +#endif diff --git a/libs/include/android/osg/Light b/libs/include/android/osg/Light new file mode 100755 index 0000000..d0cb67d --- /dev/null +++ b/libs/include/android/osg/Light @@ -0,0 +1,199 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_LIGHT +#define OSG_LIGHT 1 + +#include +#include +#include + +#ifndef GL_LIGHT0 + #define GL_LIGHT0 0x4000 + #define GL_LIGHT1 0x4001 + #define GL_LIGHT2 0x4002 + #define GL_LIGHT3 0x4003 + #define GL_LIGHT4 0x4004 + #define GL_LIGHT5 0x4005 + #define GL_LIGHT6 0x4006 + #define GL_LIGHT7 0x4007 +#endif + +#ifndef GL_LIGHTING + #define GL_LIGHTING 0x0B50 +#endif + +namespace osg { + +/** Light state class which encapsulates OpenGL glLight() functionality. */ +class OSG_EXPORT Light : public StateAttribute +{ + public : + + Light(); + + Light(unsigned int lightnum); + + /** Copy constructor using CopyOp to manage deep vs shallow copy. */ + Light(const Light& light,const CopyOp& copyop=CopyOp::SHALLOW_COPY): + StateAttribute(light,copyop), + _lightnum(light._lightnum), + _ambient(light._ambient), + _diffuse(light._diffuse), + _specular(light._specular), + _position(light._position), + _direction(light._direction), + _constant_attenuation(light._constant_attenuation), + _linear_attenuation(light._linear_attenuation), + _quadratic_attenuation(light._quadratic_attenuation), + _spot_exponent(light._spot_exponent), + _spot_cutoff(light._spot_cutoff) {} + + virtual osg::Object* cloneType() const { return new Light(_lightnum); } + virtual osg::Object* clone(const osg::CopyOp& copyop) const { return new Light(*this,copyop); } + virtual bool isSameKindAs(const osg::Object* obj) const { return dynamic_cast(obj)!=NULL; } + virtual const char* libraryName() const { return "osg"; } + virtual const char* className() const { return "Light"; } + virtual Type getType() const { return LIGHT; } + + /** Return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs. */ + virtual int compare(const StateAttribute& sa) const + { + // check the types are equal and then create the rhs variable + // used by the COMPARE_StateAttribute_Parameter macros below. + COMPARE_StateAttribute_Types(Light,sa) + + // compare each parameter in turn against the rhs. + COMPARE_StateAttribute_Parameter(_lightnum) + COMPARE_StateAttribute_Parameter(_ambient) + COMPARE_StateAttribute_Parameter(_diffuse) + COMPARE_StateAttribute_Parameter(_specular) + COMPARE_StateAttribute_Parameter(_position) + COMPARE_StateAttribute_Parameter(_direction) + COMPARE_StateAttribute_Parameter(_constant_attenuation) + COMPARE_StateAttribute_Parameter(_linear_attenuation) + COMPARE_StateAttribute_Parameter(_quadratic_attenuation) + COMPARE_StateAttribute_Parameter(_spot_exponent) + COMPARE_StateAttribute_Parameter(_spot_cutoff) + + return 0; // passed all the above comparison macros, must be equal. + } + + virtual unsigned int getMember() const { return _lightnum; } + + virtual bool getModeUsage(StateAttribute::ModeUsage& usage) const + { + usage.usesMode(GL_LIGHT0+_lightnum); + return true; + } + + + + /** Set which OpenGL light to operate on. */ + void setLightNum(int num); + + /** Get which OpenGL light this osg::Light operates on. */ + int getLightNum() const { return _lightnum; } + + /** Set the ambient component of the light. */ + inline void setAmbient( const Vec4& ambient ) { _ambient = ambient; } + + /** Get the ambient component of the light. */ + inline const Vec4& getAmbient() const { return _ambient; } + + /** Set the diffuse component of the light. */ + inline void setDiffuse( const Vec4& diffuse ) { _diffuse = diffuse; } + + /** Get the diffuse component of the light. */ + inline const Vec4& getDiffuse() const { return _diffuse; } + + /** Set the specular component of the light. */ + inline void setSpecular( const Vec4& specular ) { _specular = specular; } + + /** Get the specular component of the light. */ + inline const Vec4& getSpecular() const { return _specular; } + + /** Set the position of the light. */ + inline void setPosition( const Vec4& position ) { _position = position; } + + /** Get the position of the light. */ + inline const Vec4& getPosition() const { return _position; } + + /** Set the direction of the light. */ + inline void setDirection( const Vec3& direction ) { _direction = direction; } + + /** Get the direction of the light. */ + inline const Vec3& getDirection() const { return _direction; } + + /** Set the constant attenuation of the light. */ + inline void setConstantAttenuation( float constant_attenuation ) { _constant_attenuation = constant_attenuation; } + + /** Get the constant attenuation of the light. */ + inline float getConstantAttenuation() const { return _constant_attenuation; } + + /** Set the linear attenuation of the light. */ + inline void setLinearAttenuation ( float linear_attenuation ) { _linear_attenuation = linear_attenuation; } + + /** Get the linear attenuation of the light. */ + inline float getLinearAttenuation () const { return _linear_attenuation; } + + /** Set the quadratic attenuation of the light. */ + inline void setQuadraticAttenuation ( float quadratic_attenuation ) { _quadratic_attenuation = quadratic_attenuation; } + + /** Get the quadratic attenuation of the light. */ + inline float getQuadraticAttenuation() const { return _quadratic_attenuation; } + + /** Set the spot exponent of the light. */ + inline void setSpotExponent( float spot_exponent ) { _spot_exponent = spot_exponent; } + + /** Get the spot exponent of the light. */ + inline float getSpotExponent() const { return _spot_exponent; } + + /** Set the spot cutoff of the light. */ + inline void setSpotCutoff( float spot_cutoff ) { _spot_cutoff = spot_cutoff; } + + /** Get the spot cutoff of the light. */ + inline float getSpotCutoff() const { return _spot_cutoff; } + + /** Capture the lighting settings of the current OpenGL state + * and store them in this object. + */ + void captureLightState(); + + /** Apply the light's state to the OpenGL state machine. */ + virtual void apply(State& state) const; + + protected : + + virtual ~Light(); + + /** Initialize the light's settings with some decent defaults. */ + void init(); + + int _lightnum; // OpenGL light number + + Vec4 _ambient; // r, g, b, w + Vec4 _diffuse; // r, g, b, w + Vec4 _specular; // r, g, b, w + Vec4 _position; // x, y, z, w + Vec3 _direction; // x, y, z + float _constant_attenuation; // constant + float _linear_attenuation; // linear + float _quadratic_attenuation; // quadratic + float _spot_exponent; // exponent + float _spot_cutoff; // spread +}; + +} + +#endif diff --git a/libs/include/android/osg/LightModel b/libs/include/android/osg/LightModel new file mode 100755 index 0000000..696f0f7 --- /dev/null +++ b/libs/include/android/osg/LightModel @@ -0,0 +1,95 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_LIGHTMODEL +#define OSG_LIGHTMODEL 1 + +#include +#include + +namespace osg { + +class OSG_EXPORT LightModel : public StateAttribute +{ + public : + + LightModel(); + + /** Copy constructor using CopyOp to manage deep vs shallow copy. */ + LightModel(const LightModel& lw,const CopyOp& copyop=CopyOp::SHALLOW_COPY): + StateAttribute(lw,copyop), + _ambient(lw._ambient), + _colorControl(lw._colorControl), + _localViewer(lw._localViewer), + _twoSided(lw._twoSided) {} + + + META_StateAttribute(osg, LightModel, LIGHTMODEL); + + /** Return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs. */ + virtual int compare(const StateAttribute& sa) const + { + // check the types are equal and then create the rhs variable + // used by the COMPARE_StateAttribute_Parameter macros below. + COMPARE_StateAttribute_Types(LightModel,sa) + + // compare each parameter in turn against the rhs. + COMPARE_StateAttribute_Parameter(_ambient) + COMPARE_StateAttribute_Parameter(_colorControl) + COMPARE_StateAttribute_Parameter(_localViewer) + COMPARE_StateAttribute_Parameter(_twoSided) + + return 0; // passed all the above comparison macros, must be equal. + } + + + void setAmbientIntensity(const osg::Vec4& ambient) { _ambient = ambient; } + const osg::Vec4& getAmbientIntensity() const { return _ambient; } + + + enum ColorControl + { + SEPARATE_SPECULAR_COLOR, + SINGLE_COLOR + }; + + void setColorControl(ColorControl cc) { _colorControl = cc; } + inline ColorControl getColorControl() const { return _colorControl; } + + + void setLocalViewer(bool localViewer) { _localViewer=localViewer; } + inline bool getLocalViewer() const { return _localViewer; } + + + void setTwoSided(bool twoSided) { _twoSided = twoSided; } + inline bool getTwoSided() const { return _twoSided; } + + + + virtual void apply(State& state) const; + + + protected : + + virtual ~LightModel(); + + osg::Vec4 _ambient; + ColorControl _colorControl; + bool _localViewer; + bool _twoSided; + +}; + +} + +#endif diff --git a/libs/include/android/osg/LightSource b/libs/include/android/osg/LightSource new file mode 100755 index 0000000..1131b71 --- /dev/null +++ b/libs/include/android/osg/LightSource @@ -0,0 +1,93 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2004 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_LIGHTSOURCE +#define OSG_LIGHTSOURCE 1 + +#include +#include +#include + +namespace osg { + +/** Leaf Node for defining a light in the scene. */ +class OSG_EXPORT LightSource : public Group +{ + public: + + LightSource(); + + /** Copy constructor using CopyOp to manage deep vs shallow copy. */ + LightSource(const LightSource& ls, + const CopyOp& copyop=CopyOp::SHALLOW_COPY): + Group(ls,copyop), + _value(ls._value), + _light(dynamic_cast(copyop(ls._light.get()))), + _referenceFrame(ls._referenceFrame) {} + + META_Node(osg, LightSource); + + enum ReferenceFrame + { + RELATIVE_RF, + ABSOLUTE_RF + }; + + /** Set the light sources's ReferenceFrame, either to be relative to its + * parent reference frame, or relative to an absolute coordinate + * frame. RELATIVE_RF is the default. + * Note: setting the ReferenceFrame to be ABSOLUTE_RF will + * also set the CullingActive flag on the light source, and hence all + * of its parents, to false, thereby disabling culling of it and + * all its parents. This is necessary to prevent inappropriate + * culling, but may impact cull times if the absolute light source is + * deep in the scene graph. It is therefore recommended to only use + * absolute light source at the top of the scene. + */ + void setReferenceFrame(ReferenceFrame rf); + + ReferenceFrame getReferenceFrame() const { return _referenceFrame; } + + /** Set the attached light. */ + void setLight(Light* light); + + /** Get the attached light. */ + inline Light* getLight() { return _light.get(); } + + /** Get the const attached light. */ + inline const Light* getLight() const { return _light.get(); } + + /** Set the GLModes on StateSet associated with the LightSource. */ + void setStateSetModes(StateSet&,StateAttribute::GLModeValue) const; + + /** Set up the local StateSet. */ + void setLocalStateSetModes(StateAttribute::GLModeValue value = StateAttribute::ON); + + /** Set whether to use a mutex to ensure ref() and unref() are thread safe.*/ + virtual void setThreadSafeRefUnref(bool threadSafe); + + virtual BoundingSphere computeBound() const; + + protected: + + virtual ~LightSource(); + + StateAttribute::GLModeValue _value; + ref_ptr _light; + + ReferenceFrame _referenceFrame; +}; + +} + +#endif diff --git a/libs/include/android/osg/LineSegment b/libs/include/android/osg/LineSegment new file mode 100755 index 0000000..b6b9224 --- /dev/null +++ b/libs/include/android/osg/LineSegment @@ -0,0 +1,101 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2004 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_LINESEGMENT +#define OSG_LINESEGMENT 1 + +#include +#include +#include + +namespace osg { + +/** LineSegment class for representing a line segment. */ +class OSG_EXPORT LineSegment : public Referenced +{ + public: + + typedef Vec3d vec_type; + typedef vec_type::value_type value_type; + + LineSegment() {}; + LineSegment(const LineSegment& seg) : Referenced(),_s(seg._s),_e(seg._e) {} + LineSegment(const vec_type& s,const vec_type& e) : _s(s),_e(e) {} + + LineSegment& operator = (const LineSegment& seg) { _s = seg._s; _e = seg._e; return *this; } + + inline void set(const vec_type& s,const vec_type& e) { _s=s; _e=e; } + + inline vec_type& start() { return _s; } + inline const vec_type& start() const { return _s; } + + inline vec_type& end() { return _e; } + inline const vec_type& end() const { return _e; } + + inline bool valid() const { return _s.valid() && _e.valid() && _s!=_e; } + + /** return true if segment intersects BoundingBox. */ + bool intersect(const BoundingBox& bb) const; + + /** return true if segment intersects BoundingBox + * and return the intersection ratios. + */ + bool intersect(const BoundingBox& bb,float& r1,float& r2) const; + + /** return true if segment intersects BoundingBox + * and return the intersection ratios. + */ + bool intersect(const BoundingBox& bb,double& r1,double& r2) const; + + /** return true if segment intersects BoundingSphere. */ + bool intersect(const BoundingSphere& bs) const; + + /** return true if segment intersects BoundingSphere and return the + * intersection ratio. + */ + bool intersect(const BoundingSphere& bs,float& r1,float& r2) const; + + /** return true if segment intersects BoundingSphere and return the + * intersection ratio. + */ + bool intersect(const BoundingSphere& bs,double& r1,double& r2) const; + + /** return true if segment intersects triangle + * and set ratio long segment. + */ + bool intersect(const Vec3f& v1,const Vec3f& v2,const Vec3f& v3,float& r); + + /** return true if segment intersects triangle + * and set ratio long segment. + */ + bool intersect(const Vec3d& v1,const Vec3d& v2,const Vec3d& v3,double& r); + + + /** post multiply a segment by matrix.*/ + inline void mult(const LineSegment& seg,const Matrix& m) { _s = seg._s*m; _e = seg._e*m; } + /** pre multiply a segment by matrix.*/ + inline void mult(const Matrix& m,const LineSegment& seg) { _s = m*seg._s; _e = m*seg._e; } + + protected: + + virtual ~LineSegment(); + + static bool intersectAndClip(vec_type& s,vec_type& e,const BoundingBox& bb); + + vec_type _s; + vec_type _e; +}; + +} + +#endif diff --git a/libs/include/android/osg/LineStipple b/libs/include/android/osg/LineStipple new file mode 100755 index 0000000..dd52a22 --- /dev/null +++ b/libs/include/android/osg/LineStipple @@ -0,0 +1,83 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2004 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_LINESTIPPLE +#define OSG_LINESTIPPLE 1 + +#include + +#ifndef GL_LINE_STIPPLE + #define GL_LINE_STIPPLE 0x0B24 +#endif + +namespace osg { + +class OSG_EXPORT LineStipple : public StateAttribute +{ + public : + + LineStipple(); + + LineStipple(GLint factor, GLushort pattern): + _factor(factor), + _pattern(pattern) {} + + /** Copy constructor using CopyOp to manage deep vs shallow copy.*/ + LineStipple(const LineStipple& lw,const CopyOp& copyop=CopyOp::SHALLOW_COPY): + StateAttribute(lw,copyop), + _factor(lw._factor), + _pattern(lw._pattern) {} + + META_StateAttribute(osg, LineStipple, LINESTIPPLE); + + /** return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs. */ + virtual int compare(const StateAttribute& sa) const + { + // check if the types are equal and then create the rhs variable. + // used by the COMPARE_StateAttribute_Parameter macros below. + COMPARE_StateAttribute_Types(LineStipple,sa) + + // compare each parameter in turn against the rhs. + COMPARE_StateAttribute_Parameter(_factor) + COMPARE_StateAttribute_Parameter(_pattern) + + return 0; // passed all the above comparison macros, must be equal. + } + + virtual bool getModeUsage(StateAttribute::ModeUsage& usage) const + { + usage.usesMode(GL_LINE_STIPPLE); + return true; + } + + void setFactor(GLint factor); + inline GLint getFactor() const { return _factor; } + + void setPattern(GLushort pattern); + inline GLushort getPattern() const { return _pattern; } + + virtual void apply(State& state) const; + + + protected : + + virtual ~LineStipple(); + + GLint _factor; + GLushort _pattern; + +}; + +} + +#endif diff --git a/libs/include/android/osg/LineWidth b/libs/include/android/osg/LineWidth new file mode 100755 index 0000000..6c45888 --- /dev/null +++ b/libs/include/android/osg/LineWidth @@ -0,0 +1,64 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2004 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_LINEWIDTH +#define OSG_LINEWIDTH 1 + +#include + +namespace osg { + +/** LineWidth - encapsulates the OpenGL glLineWidth for setting the width of lines in pixels. */ +class OSG_EXPORT LineWidth : public StateAttribute +{ + public : + + LineWidth(float width=1.0f); + + /** Copy constructor using CopyOp to manage deep vs shallow copy. */ + LineWidth(const LineWidth& lw,const CopyOp& copyop=CopyOp::SHALLOW_COPY) : + StateAttribute(lw,copyop), + _width(lw._width) {} + + META_StateAttribute(osg, LineWidth, LINEWIDTH); + + /** return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs. */ + virtual int compare(const StateAttribute& sa) const + { + // check if the types are equal and then create the rhs variable + // used by the COMPARE_StateAttribute_Parameter macros below. + COMPARE_StateAttribute_Types(LineWidth,sa) + + // compare each parameter in turn against the rhs. + COMPARE_StateAttribute_Parameter(_width) + + return 0; // passed all the above comparison macros, must be equal. + } + + void setWidth(float width); + + inline float getWidth() const { return _width; } + + virtual void apply(State& state) const; + + protected : + + virtual ~LineWidth(); + + float _width; + +}; + +} + +#endif diff --git a/libs/include/android/osg/LogicOp b/libs/include/android/osg/LogicOp new file mode 100755 index 0000000..2511af1 --- /dev/null +++ b/libs/include/android/osg/LogicOp @@ -0,0 +1,113 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_LOGICOP +#define OSG_LOGICOP 1 + +#include + +#ifndef OSG_GL_FIXED_FUNCTION_AVAILABLE + #define GL_CLEAR 0x1500 + #define GL_SET 0x150F + #define GL_COPY 0x1503 + #define GL_COPY_INVERTED 0x150C + #define GL_NOOP 0x1505 + #define GL_AND 0x1501 + #define GL_NAND 0x150E + #define GL_OR 0x1507 + #define GL_NOR 0x1508 + #define GL_XOR 0x1506 + #define GL_EQUIV 0x1509 + #define GL_AND_REVERSE 0x1502 + #define GL_AND_INVERTED 0x1504 + #define GL_OR_REVERSE 0x150B + #define GL_OR_INVERTED 0x150D + #define GL_COLOR_LOGIC_OP 0x0BF2 +#endif + +namespace osg { + +/** Encapsulates OpenGL LogicOp state. */ +class OSG_EXPORT LogicOp : public StateAttribute +{ + public : + + enum Opcode { + CLEAR = GL_CLEAR, + SET = GL_SET, + COPY = GL_COPY, + COPY_INVERTED = GL_COPY_INVERTED, + NOOP = GL_NOOP, + INVERT = GL_INVERT, + AND = GL_AND, + NAND = GL_NAND, + OR = GL_OR, + NOR = GL_NOR, + XOR = GL_XOR, + EQUIV = GL_EQUIV, + AND_REVERSE = GL_AND_REVERSE, + AND_INVERTED = GL_AND_INVERTED, + OR_REVERSE = GL_OR_REVERSE, + OR_INVERTED = GL_OR_INVERTED + }; + + LogicOp(); + + LogicOp(Opcode opcode); + + /** Copy constructor using CopyOp to manage deep vs shallow copy. */ + LogicOp(const LogicOp& trans,const CopyOp& copyop=CopyOp::SHALLOW_COPY): + StateAttribute(trans,copyop), + _opcode(trans._opcode){} + + META_StateAttribute(osg, LogicOp,LOGICOP); + + /** Return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs. */ + virtual int compare(const StateAttribute& sa) const + { + // Check for equal types, then create the rhs variable + // used by the COMPARE_StateAttribute_Parameter macros below. + COMPARE_StateAttribute_Types(LogicOp,sa) + + // Compare each parameter in turn against the rhs. + COMPARE_StateAttribute_Parameter(_opcode) + + return 0; // Passed all the above comparison macros, so must be equal. + } + + virtual bool getModeUsage(StateAttribute::ModeUsage& usage) const + { + usage.usesMode(GL_COLOR_LOGIC_OP); + return true; + } + + + inline void setOpcode(Opcode opcode) + { + _opcode = opcode; + } + + inline Opcode getOpcode() const { return _opcode; } + + virtual void apply(State& state) const; + + protected : + + virtual ~LogicOp(); + + Opcode _opcode; +}; + +} + +#endif diff --git a/libs/include/android/osg/Material b/libs/include/android/osg/Material new file mode 100755 index 0000000..459d1e4 --- /dev/null +++ b/libs/include/android/osg/Material @@ -0,0 +1,205 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2004 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_MATERIAL +#define OSG_MATERIAL 1 + +#include +#include + +#ifndef OSG_GL_FIXED_FUNCTION_AVAILABLE + #define GL_AMBIENT 0x1200 + #define GL_DIFFUSE 0x1201 + #define GL_SPECULAR 0x1202 + #define GL_EMISSION 0x1600 + #define GL_AMBIENT_AND_DIFFUSE 0x1602 + #define GL_COLOR_MATERIAL 0x0B57 +#endif + +namespace osg { +/** Material - encapsulates OpenGL glMaterial state.*/ +class OSG_EXPORT Material : public StateAttribute +{ + public : + + Material(); + + /** Copy constructor using CopyOp to manage deep vs shallow copy. */ + Material(const Material& mat,const CopyOp& copyop=CopyOp::SHALLOW_COPY): + StateAttribute(mat,copyop), + _colorMode(mat._colorMode), + _ambientFrontAndBack(mat._ambientFrontAndBack), + _ambientFront(mat._ambientFront), + _ambientBack(mat._ambientBack), + _diffuseFrontAndBack(mat._diffuseFrontAndBack), + _diffuseFront(mat._diffuseFront), + _diffuseBack(mat._diffuseBack), + _specularFrontAndBack(mat._specularFrontAndBack), + _specularFront(mat._specularFront), + _specularBack(mat._specularBack), + _emissionFrontAndBack(mat._emissionFrontAndBack), + _emissionFront(mat._emissionFront), + _emissionBack(mat._emissionBack), + _shininessFrontAndBack(mat._shininessFrontAndBack), + _shininessFront(mat._shininessFront), + _shininessBack(mat._shininessBack) {} + + META_StateAttribute(osg, Material, MATERIAL); + + /** return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs. */ + virtual int compare(const StateAttribute& sa) const + { + // check the types are equal and then create the rhs variable + // used by the COMPARE_StateAttribute_Parameter macros below. + COMPARE_StateAttribute_Types(Material,sa) + + // compare each parameter in turn against the rhs. + COMPARE_StateAttribute_Parameter(_colorMode) + COMPARE_StateAttribute_Parameter(_ambientFrontAndBack) + COMPARE_StateAttribute_Parameter(_ambientFront) + COMPARE_StateAttribute_Parameter(_ambientBack) + COMPARE_StateAttribute_Parameter(_diffuseFrontAndBack) + COMPARE_StateAttribute_Parameter(_diffuseFront) + COMPARE_StateAttribute_Parameter(_diffuseBack) + COMPARE_StateAttribute_Parameter(_specularFrontAndBack) + COMPARE_StateAttribute_Parameter(_specularFront) + COMPARE_StateAttribute_Parameter(_specularBack) + COMPARE_StateAttribute_Parameter(_emissionFrontAndBack) + COMPARE_StateAttribute_Parameter(_emissionFront) + COMPARE_StateAttribute_Parameter(_emissionBack) + COMPARE_StateAttribute_Parameter(_shininessFrontAndBack) + COMPARE_StateAttribute_Parameter(_shininessFront) + COMPARE_StateAttribute_Parameter(_shininessBack) + + return 0; // passed all the above comparison macros, must be equal. + } + + Material& operator = (const Material& rhs); + + virtual bool getModeUsage(StateAttribute::ModeUsage& /*usage*/) const + { + // note, since Material does it's own glEnable/glDisable of GL_COLOR_MATERIAL + // we shouldn't declare usage of that mode, so commenting out the below usage. + // usage.usesMode(GL_COLOR_MATERIAL); + return true; + } + + virtual void apply(State& state) const; + + enum Face { + FRONT = GL_FRONT, + BACK = GL_BACK, + FRONT_AND_BACK = GL_FRONT_AND_BACK + }; + + enum ColorMode { + AMBIENT = GL_AMBIENT, + DIFFUSE = GL_DIFFUSE, + SPECULAR = GL_SPECULAR, + EMISSION = GL_EMISSION, + AMBIENT_AND_DIFFUSE = GL_AMBIENT_AND_DIFFUSE, + OFF + }; + + inline void setColorMode(ColorMode mode) { _colorMode = mode; } + inline ColorMode getColorMode() const { return _colorMode; } + + void setAmbient( Face face, const Vec4& ambient ); + const Vec4& getAmbient(Face face) const; + inline bool getAmbientFrontAndBack() const { return _ambientFrontAndBack; } + + void setDiffuse( Face face, const Vec4& diffuse ); + const Vec4& getDiffuse(Face face) const; + inline bool getDiffuseFrontAndBack() const { return _diffuseFrontAndBack; } + + /** Set specular value of specified face(s) of the material, + * valid specular[0..3] range is 0.0 to 1.0. + */ + void setSpecular( Face face, const Vec4& specular ); + + /** Get the specular value for specified face. */ + const Vec4& getSpecular(Face face) const; + + /** Return whether specular values are equal for front and back faces + * or not. + */ + inline bool getSpecularFrontAndBack() const { return _specularFrontAndBack; } + + /** Set emission value of specified face(s) of the material, + * valid emission[0..3] range is 0.0 to 1.0. + */ + void setEmission( Face face, const Vec4& emission ); + + /** Get the emission value for specified face. */ + const Vec4& getEmission(Face face) const; + + /** Return whether emission values are equal for front and back faces + * or not. + */ + inline bool getEmissionFrontAndBack() const { return _emissionFrontAndBack; } + + /** Set shininess of specified face(s) of the material. + * valid shininess range is 0.0 to 128.0. + */ + void setShininess(Face face, float shininess ); + + /** Get the shininess value for specified face. */ + float getShininess(Face face) const; + + /** Return whether shininess values are equal for front and back faces + * or not. + */ + inline bool getShininessFrontAndBack() const { return _shininessFrontAndBack; } + + /** Set the alpha value of ambient, diffuse, specular and emission + * colors of specified face, to 1-transparency. + * Valid transparency range is 0.0 to 1.0. + */ + void setTransparency(Face face,float trans); + + /** Set the alpha value of ambient, diffuse, specular and emission + * colors. Valid transparency range is 0.0 to 1.0. + */ + void setAlpha(Face face,float alpha); + + protected : + + virtual ~Material(); + + ColorMode _colorMode; + + bool _ambientFrontAndBack; + Vec4 _ambientFront; // r, g, b, w + Vec4 _ambientBack; // r, g, b, w + + bool _diffuseFrontAndBack; + Vec4 _diffuseFront; // r, g, b, w + Vec4 _diffuseBack; // r, g, b, w + + bool _specularFrontAndBack; + Vec4 _specularFront; // r, g, b, w + Vec4 _specularBack; // r, g, b, w + + bool _emissionFrontAndBack; + Vec4 _emissionFront; // r, g, b, w + Vec4 _emissionBack; // r, g, b, w + + bool _shininessFrontAndBack; + float _shininessFront; // values 0 - 128.0 + float _shininessBack; // values 0 - 128.0 + +}; + +} + +#endif diff --git a/libs/include/android/osg/Math b/libs/include/android/osg/Math new file mode 100755 index 0000000..1ea7c0d --- /dev/null +++ b/libs/include/android/osg/Math @@ -0,0 +1,152 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2004 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef __OSG_MATH +#define __OSG_MATH + +#include +#include + +#include + +namespace osg { + +// define the standard trig values +#ifdef PI +#undef PI +#undef PI_2 +#undef PI_4 +#endif +const double PI = 3.14159265358979323846; +const double PI_2 = 1.57079632679489661923; +const double PI_4 = 0.78539816339744830962; +const double LN_2 = 0.69314718055994530942; +const double INVLN_2 = 1.0 / LN_2; + + +template +inline T absolute(T v) { return v<(T)0?-v:v; } + +/** return true if float lhs and rhs are equivalent, + * meaning that the difference between them is less than an epsilon value + * which defaults to 1e-6. +*/ +inline bool equivalent(float lhs,float rhs,float epsilon=1e-6) + { float delta = rhs-lhs; return delta<0.0f?delta>=-epsilon:delta<=epsilon; } + +/** return true if double lhs and rhs are equivalent, + * meaning that the difference between them is less than an epsilon value + * which defaults to 1e-6. +*/ +inline bool equivalent(double lhs,double rhs,double epsilon=1e-6) + { double delta = rhs-lhs; return delta<0.0?delta>=-epsilon:delta<=epsilon; } + +/** return the minimum of two values, equivalent to std::min. + * std::min not used because of STL implementation under IRIX not containing + * std::min. +*/ +template +inline T minimum(T lhs,T rhs) { return lhs +inline T maximum(T lhs,T rhs) { return lhs>rhs?lhs:rhs; } + +template +inline T clampTo(T v,T minimum,T maximum) { return vmaximum?maximum:v; } + +template +inline T clampAbove(T v,T minimum) { return v +inline T clampBelow(T v,T maximum) { return v>maximum?maximum:v; } + +template +inline T clampBetween(T v,T minimum, T maximum) + { return clampBelow(clampAbove(v,minimum),maximum); } + +template +inline T sign(T v) { return v<(T)0?(T)-1:(T)1; } + +template +inline T signOrZero(T v) { return v<(T)0 ? (T)-1 : ( v>(T)0 ? (T)1 : 0 ); } + +template +inline T square(T v) { return v*v; } + +template +inline T signedSquare(T v) { return v<(T)0?-v*v:v*v;; } + +inline float inDegrees(float angle) { return angle*(float)PI/180.0f; } +inline double inDegrees(double angle) { return angle*PI/180.0; } + +template +inline T inRadians(T angle) { return angle; } + +inline float DegreesToRadians(float angle) { return angle*(float)PI/180.0f; } +inline double DegreesToRadians(double angle) { return angle*PI/180.0; } + +inline float RadiansToDegrees(float angle) { return angle*180.0f/(float)PI; } +inline double RadiansToDegrees(double angle) { return angle*180.0/PI; } + +inline float round(float v) { return v>=0.0f?floorf(v+0.5f):ceilf(v-0.5f); } +inline double round(double v) { return v>=0.0?floor(v+0.5):ceil(v-0.5); } + +#if defined(_MSC_VER) + inline bool isNaN(double v) { return _isnan(v)!=0; } +#elif defined(__ANDROID__) + inline bool isNaN(float v) { return isnan(v); } + inline bool isNaN(double v) { return isnan(v); } +#else + inline bool isNaN(float v) { return std::isnan(v); } + inline bool isNaN(double v) { return std::isnan(v); } +#endif + + +/** compute the volume of a tetrahedron. */ +template +inline float computeVolume(const T& a,const T& b,const T& c,const T& d) +{ + return fabsf(((b-c)^(a-b))*(d-b)); +} + +/** compute the volume of a prism. */ +template +inline float computeVolume(const T& f1,const T& f2,const T& f3, + const T& b1,const T& b2,const T& b3) +{ + return computeVolume(f1,f2,f3,b1)+ + computeVolume(b1,b2,b3,f2)+ + computeVolume(b1,b3,f2,f3); +} + +/** Convert a ascii number to a double, ignoring locale settings.*/ +extern OSG_EXPORT double asciiToDouble(const char* str); + +/** Convert a ascii number to a float, ignoring locale settings.*/ +inline float asciiToFloat(const char* str) { return static_cast(asciiToDouble(str)); } + +/** Detect first ascii POSITIVE number in string and convert to double.*/ +extern OSG_EXPORT double findAsciiToDouble(const char* str); + +/** Detect first ascii POSITIVE number in string and convert to double.*/ +inline float findAsciiToFloat(const char* str) { return static_cast(findAsciiToDouble(str)); } + +} + + +#endif // __OSG_MATH + diff --git a/libs/include/android/osg/Matrix b/libs/include/android/osg/Matrix new file mode 100755 index 0000000..0277e1e --- /dev/null +++ b/libs/include/android/osg/Matrix @@ -0,0 +1,34 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_MATRIX +#define OSG_MATRIX 1 + +#include +#include +#include + +namespace osg { + +#ifdef OSG_USE_FLOAT_MATRIX + typedef Matrixf Matrix; + typedef RefMatrixf RefMatrix; +#else + typedef Matrixd Matrix; + typedef RefMatrixd RefMatrix; +#endif + +} //namespace osg + + +#endif diff --git a/libs/include/android/osg/MatrixTransform b/libs/include/android/osg/MatrixTransform new file mode 100755 index 0000000..ebb8afb --- /dev/null +++ b/libs/include/android/osg/MatrixTransform @@ -0,0 +1,84 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_MATRIXTRANSFORM +#define OSG_MATRIXTRANSFORM 1 + +#include + +namespace osg { + +/** MatrixTransform - is a subclass of Transform which has an osg::Matrix + * which represents a 4x4 transformation of its children from local coordinates + * into the Transform's parent coordinates. +*/ +class OSG_EXPORT MatrixTransform : public Transform +{ + public : + + + MatrixTransform(); + + /** Copy constructor using CopyOp to manage deep vs shallow copy.*/ + MatrixTransform(const MatrixTransform&,const CopyOp& copyop=CopyOp::SHALLOW_COPY); + + MatrixTransform(const Matrix& matix); + + META_Node(osg, MatrixTransform); + + virtual MatrixTransform* asMatrixTransform() { return this; } + virtual const MatrixTransform* asMatrixTransform() const { return this; } + + + /** Set the transform's matrix.*/ + void setMatrix(const Matrix& mat) { _matrix = mat; _inverseDirty=true; dirtyBound(); } + + /** Get the matrix. */ + inline const Matrix& getMatrix() const { return _matrix; } + + /** pre multiply the transform's matrix.*/ + void preMult(const Matrix& mat) { _matrix.preMult(mat); _inverseDirty=true; dirtyBound(); } + + /** post multiply the transform's matrix.*/ + void postMult(const Matrix& mat) { _matrix.postMult(mat); _inverseDirty=true; dirtyBound(); } + + /** Get the inverse matrix. */ + inline const Matrix& getInverseMatrix() const + { + if (_inverseDirty) + { + _inverse.invert(_matrix); + _inverseDirty = false; + } + return _inverse; + } + + virtual bool computeLocalToWorldMatrix(Matrix& matrix,NodeVisitor*) const; + + virtual bool computeWorldToLocalMatrix(Matrix& matrix,NodeVisitor*) const; + + + protected : + + virtual ~MatrixTransform(); + + Matrix _matrix; + mutable Matrix _inverse; + mutable bool _inverseDirty; + + +}; + +} + +#endif diff --git a/libs/include/android/osg/Matrixd b/libs/include/android/osg/Matrixd new file mode 100755 index 0000000..18eca9a --- /dev/null +++ b/libs/include/android/osg/Matrixd @@ -0,0 +1,831 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2004 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_MATRIXD +#define OSG_MATRIXD 1 + +#include +#include +#include +#include + +namespace osg { + +class Matrixf; + +class OSG_EXPORT Matrixd +{ + public: + + typedef double value_type; + typedef float other_value_type; + + inline Matrixd() { makeIdentity(); } + inline Matrixd( const Matrixd& mat) { set(mat.ptr()); } + Matrixd( const Matrixf& mat ); + inline explicit Matrixd( float const * const ptr ) { set(ptr); } + inline explicit Matrixd( double const * const ptr ) { set(ptr); } + inline explicit Matrixd( const Quat& quat ) { makeRotate(quat); } + + Matrixd(value_type a00, value_type a01, value_type a02, value_type a03, + value_type a10, value_type a11, value_type a12, value_type a13, + value_type a20, value_type a21, value_type a22, value_type a23, + value_type a30, value_type a31, value_type a32, value_type a33); + + ~Matrixd() {} + + int compare(const Matrixd& m) const; + + bool operator < (const Matrixd& m) const { return compare(m)<0; } + bool operator == (const Matrixd& m) const { return compare(m)==0; } + bool operator != (const Matrixd& m) const { return compare(m)!=0; } + + inline value_type& operator()(int row, int col) { return _mat[row][col]; } + inline value_type operator()(int row, int col) const { return _mat[row][col]; } + + inline bool valid() const { return !isNaN(); } + inline bool isNaN() const { return osg::isNaN(_mat[0][0]) || osg::isNaN(_mat[0][1]) || osg::isNaN(_mat[0][2]) || osg::isNaN(_mat[0][3]) || + osg::isNaN(_mat[1][0]) || osg::isNaN(_mat[1][1]) || osg::isNaN(_mat[1][2]) || osg::isNaN(_mat[1][3]) || + osg::isNaN(_mat[2][0]) || osg::isNaN(_mat[2][1]) || osg::isNaN(_mat[2][2]) || osg::isNaN(_mat[2][3]) || + osg::isNaN(_mat[3][0]) || osg::isNaN(_mat[3][1]) || osg::isNaN(_mat[3][2]) || osg::isNaN(_mat[3][3]); } + + inline Matrixd& operator = (const Matrixd& rhs) + { + if( &rhs == this ) return *this; + set(rhs.ptr()); + return *this; + } + + Matrixd& operator = (const Matrixf& other); + + inline void set(const Matrixd& rhs) { set(rhs.ptr()); } + + void set(const Matrixf& rhs); + + inline void set(float const * const ptr) + { + value_type* local_ptr = (value_type*)_mat; + for(int i=0;i<16;++i) local_ptr[i]=(value_type)ptr[i]; + } + + inline void set(double const * const ptr) + { + value_type* local_ptr = (value_type*)_mat; + for(int i=0;i<16;++i) local_ptr[i]=(value_type)ptr[i]; + } + + void set(value_type a00, value_type a01, value_type a02,value_type a03, + value_type a10, value_type a11, value_type a12,value_type a13, + value_type a20, value_type a21, value_type a22,value_type a23, + value_type a30, value_type a31, value_type a32,value_type a33); + + value_type * ptr() { return (value_type*)_mat; } + const value_type * ptr() const { return (const value_type *)_mat; } + + bool isIdentity() const + { + return _mat[0][0]==1.0 && _mat[0][1]==0.0 && _mat[0][2]==0.0 && _mat[0][3]==0.0 && + _mat[1][0]==0.0 && _mat[1][1]==1.0 && _mat[1][2]==0.0 && _mat[1][3]==0.0 && + _mat[2][0]==0.0 && _mat[2][1]==0.0 && _mat[2][2]==1.0 && _mat[2][3]==0.0 && + _mat[3][0]==0.0 && _mat[3][1]==0.0 && _mat[3][2]==0.0 && _mat[3][3]==1.0; + } + + void makeIdentity(); + + void makeScale( const Vec3f& ); + void makeScale( const Vec3d& ); + void makeScale( value_type, value_type, value_type ); + + void makeTranslate( const Vec3f& ); + void makeTranslate( const Vec3d& ); + void makeTranslate( value_type, value_type, value_type ); + + void makeRotate( const Vec3f& from, const Vec3f& to ); + void makeRotate( const Vec3d& from, const Vec3d& to ); + void makeRotate( value_type angle, const Vec3f& axis ); + void makeRotate( value_type angle, const Vec3d& axis ); + void makeRotate( value_type angle, value_type x, value_type y, value_type z ); + void makeRotate( const Quat& ); + void makeRotate( value_type angle1, const Vec3f& axis1, + value_type angle2, const Vec3f& axis2, + value_type angle3, const Vec3f& axis3); + void makeRotate( value_type angle1, const Vec3d& axis1, + value_type angle2, const Vec3d& axis2, + value_type angle3, const Vec3d& axis3); + + + /** decompose the matrix into translation, rotation, scale and scale orientation.*/ + void decompose( osg::Vec3f& translation, + osg::Quat& rotation, + osg::Vec3f& scale, + osg::Quat& so ) const; + + /** decompose the matrix into translation, rotation, scale and scale orientation.*/ + void decompose( osg::Vec3d& translation, + osg::Quat& rotation, + osg::Vec3d& scale, + osg::Quat& so ) const; + + + /** Set to an orthographic projection. + * See glOrtho for further details. + */ + void makeOrtho(double left, double right, + double bottom, double top, + double zNear, double zFar); + + /** Get the orthographic settings of the orthographic projection matrix. + * Note, if matrix is not an orthographic matrix then invalid values + * will be returned. + */ + bool getOrtho(double& left, double& right, + double& bottom, double& top, + double& zNear, double& zFar) const; + + /** float version of getOrtho(..) */ + bool getOrtho(float& left, float& right, + float& bottom, float& top, + float& zNear, float& zFar) const; + + + /** Set to a 2D orthographic projection. + * See glOrtho2D for further details. + */ + inline void makeOrtho2D(double left, double right, + double bottom, double top) + { + makeOrtho(left,right,bottom,top,-1.0,1.0); + } + + + /** Set to a perspective projection. + * See glFrustum for further details. + */ + void makeFrustum(double left, double right, + double bottom, double top, + double zNear, double zFar); + + /** Get the frustum settings of a perspective projection matrix. + * Note, if matrix is not a perspective matrix then invalid values + * will be returned. + */ + bool getFrustum(double& left, double& right, + double& bottom, double& top, + double& zNear, double& zFar) const; + + /** float version of getFrustum(..) */ + bool getFrustum(float& left, float& right, + float& bottom, float& top, + float& zNear, float& zFar) const; + + /** Set to a symmetrical perspective projection. + * See gluPerspective for further details. + * Aspect ratio is defined as width/height. + */ + void makePerspective(double fovy, double aspectRatio, + double zNear, double zFar); + + /** Get the frustum settings of a symmetric perspective projection + * matrix. + * Return false if matrix is not a perspective matrix, + * where parameter values are undefined. + * Note, if matrix is not a symmetric perspective matrix then the + * shear will be lost. + * Asymmetric matrices occur when stereo, power walls, caves and + * reality center display are used. + * In these configuration one should use the AsFrustum method instead. + */ + bool getPerspective(double& fovy, double& aspectRatio, + double& zNear, double& zFar) const; + + /** float version of getPerspective(..) */ + bool getPerspective(float& fovy, float& aspectRatio, + float& zNear, float& zFar) const; + + /** Set the position and orientation to be a view matrix, + * using the same convention as gluLookAt. + */ + void makeLookAt(const Vec3d& eye,const Vec3d& center,const Vec3d& up); + + /** Get to the position and orientation of a modelview matrix, + * using the same convention as gluLookAt. + */ + void getLookAt(Vec3f& eye,Vec3f& center,Vec3f& up, + value_type lookDistance=1.0f) const; + + /** Get to the position and orientation of a modelview matrix, + * using the same convention as gluLookAt. + */ + void getLookAt(Vec3d& eye,Vec3d& center,Vec3d& up, + value_type lookDistance=1.0f) const; + + /** invert the matrix rhs, automatically select invert_4x3 or invert_4x4. */ + inline bool invert( const Matrixd& rhs) + { + bool is_4x3 = (rhs._mat[0][3]==0.0 && rhs._mat[1][3]==0.0 && rhs._mat[2][3]==0.0 && rhs._mat[3][3]==1.0); + return is_4x3 ? invert_4x3(rhs) : invert_4x4(rhs); + } + + /** 4x3 matrix invert, not right hand column is assumed to be 0,0,0,1. */ + bool invert_4x3( const Matrixd& rhs); + + /** full 4x4 matrix invert. */ + bool invert_4x4( const Matrixd& rhs); + + /** ortho-normalize the 3x3 rotation & scale matrix */ + void orthoNormalize(const Matrixd& rhs); + + // basic utility functions to create new matrices + inline static Matrixd identity( void ); + inline static Matrixd scale( const Vec3f& sv); + inline static Matrixd scale( const Vec3d& sv); + inline static Matrixd scale( value_type sx, value_type sy, value_type sz); + inline static Matrixd translate( const Vec3f& dv); + inline static Matrixd translate( const Vec3d& dv); + inline static Matrixd translate( value_type x, value_type y, value_type z); + inline static Matrixd rotate( const Vec3f& from, const Vec3f& to); + inline static Matrixd rotate( const Vec3d& from, const Vec3d& to); + inline static Matrixd rotate( value_type angle, value_type x, value_type y, value_type z); + inline static Matrixd rotate( value_type angle, const Vec3f& axis); + inline static Matrixd rotate( value_type angle, const Vec3d& axis); + inline static Matrixd rotate( value_type angle1, const Vec3f& axis1, + value_type angle2, const Vec3f& axis2, + value_type angle3, const Vec3f& axis3); + inline static Matrixd rotate( value_type angle1, const Vec3d& axis1, + value_type angle2, const Vec3d& axis2, + value_type angle3, const Vec3d& axis3); + inline static Matrixd rotate( const Quat& quat); + inline static Matrixd inverse( const Matrixd& matrix); + inline static Matrixd orthoNormal(const Matrixd& matrix); + /** Create an orthographic projection matrix. + * See glOrtho for further details. + */ + inline static Matrixd ortho(double left, double right, + double bottom, double top, + double zNear, double zFar); + + /** Create a 2D orthographic projection. + * See glOrtho for further details. + */ + inline static Matrixd ortho2D(double left, double right, + double bottom, double top); + + /** Create a perspective projection. + * See glFrustum for further details. + */ + inline static Matrixd frustum(double left, double right, + double bottom, double top, + double zNear, double zFar); + + /** Create a symmetrical perspective projection. + * See gluPerspective for further details. + * Aspect ratio is defined as width/height. + */ + inline static Matrixd perspective(double fovy, double aspectRatio, + double zNear, double zFar); + + /** Create the position and orientation as per a camera, + * using the same convention as gluLookAt. + */ + inline static Matrixd lookAt(const Vec3f& eye, + const Vec3f& center, + const Vec3f& up); + + /** Create the position and orientation as per a camera, + * using the same convention as gluLookAt. + */ + inline static Matrixd lookAt(const Vec3d& eye, + const Vec3d& center, + const Vec3d& up); + + inline Vec3f preMult( const Vec3f& v ) const; + inline Vec3d preMult( const Vec3d& v ) const; + inline Vec3f postMult( const Vec3f& v ) const; + inline Vec3d postMult( const Vec3d& v ) const; + inline Vec3f operator* ( const Vec3f& v ) const; + inline Vec3d operator* ( const Vec3d& v ) const; + inline Vec4f preMult( const Vec4f& v ) const; + inline Vec4d preMult( const Vec4d& v ) const; + inline Vec4f postMult( const Vec4f& v ) const; + inline Vec4d postMult( const Vec4d& v ) const; + inline Vec4f operator* ( const Vec4f& v ) const; + inline Vec4d operator* ( const Vec4d& v ) const; + +#ifdef USE_DEPRECATED_API + inline void set(const Quat& q) { makeRotate(q); } + inline void get(Quat& q) const { q = getRotate(); } +#endif + + void setRotate(const Quat& q); + /** Get the matrix rotation as a Quat. Note that this function + * assumes a non-scaled matrix and will return incorrect results + * for scaled matrixces. Consider decompose() instead. + */ + Quat getRotate() const; + + void setTrans( value_type tx, value_type ty, value_type tz ); + void setTrans( const Vec3f& v ); + void setTrans( const Vec3d& v ); + + inline Vec3d getTrans() const { return Vec3d(_mat[3][0],_mat[3][1],_mat[3][2]); } + + inline Vec3d getScale() const { + Vec3d x_vec(_mat[0][0],_mat[1][0],_mat[2][0]); + Vec3d y_vec(_mat[0][1],_mat[1][1],_mat[2][1]); + Vec3d z_vec(_mat[0][2],_mat[1][2],_mat[2][2]); + return Vec3d(x_vec.length(), y_vec.length(), z_vec.length()); + } + + /** apply a 3x3 transform of v*M[0..2,0..2]. */ + inline static Vec3f transform3x3(const Vec3f& v,const Matrixd& m); + + /** apply a 3x3 transform of v*M[0..2,0..2]. */ + inline static Vec3d transform3x3(const Vec3d& v,const Matrixd& m); + + /** apply a 3x3 transform of M[0..2,0..2]*v. */ + inline static Vec3f transform3x3(const Matrixd& m,const Vec3f& v); + + /** apply a 3x3 transform of M[0..2,0..2]*v. */ + inline static Vec3d transform3x3(const Matrixd& m,const Vec3d& v); + + // basic Matrixd multiplication, our workhorse methods. + void mult( const Matrixd&, const Matrixd& ); + void preMult( const Matrixd& ); + void postMult( const Matrixd& ); + + /** Optimized version of preMult(translate(v)); */ + inline void preMultTranslate( const Vec3d& v ); + inline void preMultTranslate( const Vec3f& v ); + /** Optimized version of postMult(translate(v)); */ + inline void postMultTranslate( const Vec3d& v ); + inline void postMultTranslate( const Vec3f& v ); + + /** Optimized version of preMult(scale(v)); */ + inline void preMultScale( const Vec3d& v ); + inline void preMultScale( const Vec3f& v ); + /** Optimized version of postMult(scale(v)); */ + inline void postMultScale( const Vec3d& v ); + inline void postMultScale( const Vec3f& v ); + + /** Optimized version of preMult(rotate(q)); */ + inline void preMultRotate( const Quat& q ); + /** Optimized version of postMult(rotate(q)); */ + inline void postMultRotate( const Quat& q ); + + inline void operator *= ( const Matrixd& other ) + { if( this == &other ) { + Matrixd temp(other); + postMult( temp ); + } + else postMult( other ); + } + + inline Matrixd operator * ( const Matrixd &m ) const + { + osg::Matrixd r; + r.mult(*this,m); + return r; + } + + protected: + value_type _mat[4][4]; + +}; + +class RefMatrixd : public Object, public Matrixd +{ + public: + + RefMatrixd():Object(false), Matrixd() {} + RefMatrixd( const Matrixd& other) : Object(false), Matrixd(other) {} + RefMatrixd( const Matrixf& other) : Object(false), Matrixd(other) {} + RefMatrixd( const RefMatrixd& other) : Object(other), Matrixd(other) {} + explicit RefMatrixd( Matrixd::value_type const * const def ):Object(false), Matrixd(def) {} + RefMatrixd( Matrixd::value_type a00, Matrixd::value_type a01, Matrixd::value_type a02, Matrixd::value_type a03, + Matrixd::value_type a10, Matrixd::value_type a11, Matrixd::value_type a12, Matrixd::value_type a13, + Matrixd::value_type a20, Matrixd::value_type a21, Matrixd::value_type a22, Matrixd::value_type a23, + Matrixd::value_type a30, Matrixd::value_type a31, Matrixd::value_type a32, Matrixd::value_type a33): + Object(false), + Matrixd(a00, a01, a02, a03, + a10, a11, a12, a13, + a20, a21, a22, a23, + a30, a31, a32, a33) {} + + virtual Object* cloneType() const { return new RefMatrixd(); } + virtual Object* clone(const CopyOp&) const { return new RefMatrixd(*this); } + virtual bool isSameKindAs(const Object* obj) const { return dynamic_cast(obj)!=NULL; } + virtual const char* libraryName() const { return "osg"; } + virtual const char* className() const { return "Matrix"; } + + + protected: + + virtual ~RefMatrixd() {} +}; + + +// static utility methods +inline Matrixd Matrixd::identity(void) +{ + Matrixd m; + m.makeIdentity(); + return m; +} + +inline Matrixd Matrixd::scale(value_type sx, value_type sy, value_type sz) +{ + Matrixd m; + m.makeScale(sx,sy,sz); + return m; +} + +inline Matrixd Matrixd::scale(const Vec3f& v ) +{ + return scale(v.x(), v.y(), v.z() ); +} + +inline Matrixd Matrixd::scale(const Vec3d& v ) +{ + return scale(v.x(), v.y(), v.z() ); +} + +inline Matrixd Matrixd::translate(value_type tx, value_type ty, value_type tz) +{ + Matrixd m; + m.makeTranslate(tx,ty,tz); + return m; +} + +inline Matrixd Matrixd::translate(const Vec3f& v ) +{ + return translate(v.x(), v.y(), v.z() ); +} + +inline Matrixd Matrixd::translate(const Vec3d& v ) +{ + return translate(v.x(), v.y(), v.z() ); +} + +inline Matrixd Matrixd::rotate( const Quat& q ) +{ + return Matrixd(q); +} +inline Matrixd Matrixd::rotate(value_type angle, value_type x, value_type y, value_type z ) +{ + Matrixd m; + m.makeRotate(angle,x,y,z); + return m; +} +inline Matrixd Matrixd::rotate(value_type angle, const Vec3f& axis ) +{ + Matrixd m; + m.makeRotate(angle,axis); + return m; +} +inline Matrixd Matrixd::rotate(value_type angle, const Vec3d& axis ) +{ + Matrixd m; + m.makeRotate(angle,axis); + return m; +} +inline Matrixd Matrixd::rotate( value_type angle1, const Vec3f& axis1, + value_type angle2, const Vec3f& axis2, + value_type angle3, const Vec3f& axis3) +{ + Matrixd m; + m.makeRotate(angle1,axis1,angle2,axis2,angle3,axis3); + return m; +} +inline Matrixd Matrixd::rotate( value_type angle1, const Vec3d& axis1, + value_type angle2, const Vec3d& axis2, + value_type angle3, const Vec3d& axis3) +{ + Matrixd m; + m.makeRotate(angle1,axis1,angle2,axis2,angle3,axis3); + return m; +} +inline Matrixd Matrixd::rotate(const Vec3f& from, const Vec3f& to ) +{ + Matrixd m; + m.makeRotate(from,to); + return m; +} +inline Matrixd Matrixd::rotate(const Vec3d& from, const Vec3d& to ) +{ + Matrixd m; + m.makeRotate(from,to); + return m; +} + +inline Matrixd Matrixd::inverse( const Matrixd& matrix) +{ + Matrixd m; + m.invert(matrix); + return m; +} + +inline Matrixd Matrixd::orthoNormal(const Matrixd& matrix) +{ + Matrixd m; + m.orthoNormalize(matrix); + return m; +} + +inline Matrixd Matrixd::ortho(double left, double right, + double bottom, double top, + double zNear, double zFar) +{ + Matrixd m; + m.makeOrtho(left,right,bottom,top,zNear,zFar); + return m; +} + +inline Matrixd Matrixd::ortho2D(double left, double right, + double bottom, double top) +{ + Matrixd m; + m.makeOrtho2D(left,right,bottom,top); + return m; +} + +inline Matrixd Matrixd::frustum(double left, double right, + double bottom, double top, + double zNear, double zFar) +{ + Matrixd m; + m.makeFrustum(left,right,bottom,top,zNear,zFar); + return m; +} + +inline Matrixd Matrixd::perspective(double fovy, double aspectRatio, + double zNear, double zFar) +{ + Matrixd m; + m.makePerspective(fovy,aspectRatio,zNear,zFar); + return m; +} + +inline Matrixd Matrixd::lookAt(const Vec3f& eye, + const Vec3f& center, + const Vec3f& up) +{ + Matrixd m; + m.makeLookAt(eye,center,up); + return m; +} + +inline Matrixd Matrixd::lookAt(const Vec3d& eye, + const Vec3d& center, + const Vec3d& up) +{ + Matrixd m; + m.makeLookAt(eye,center,up); + return m; +} + +inline Vec3f Matrixd::postMult( const Vec3f& v ) const +{ + value_type d = 1.0f/(_mat[3][0]*v.x()+_mat[3][1]*v.y()+_mat[3][2]*v.z()+_mat[3][3]) ; + return Vec3f( (_mat[0][0]*v.x() + _mat[0][1]*v.y() + _mat[0][2]*v.z() + _mat[0][3])*d, + (_mat[1][0]*v.x() + _mat[1][1]*v.y() + _mat[1][2]*v.z() + _mat[1][3])*d, + (_mat[2][0]*v.x() + _mat[2][1]*v.y() + _mat[2][2]*v.z() + _mat[2][3])*d) ; +} + +inline Vec3d Matrixd::postMult( const Vec3d& v ) const +{ + value_type d = 1.0f/(_mat[3][0]*v.x()+_mat[3][1]*v.y()+_mat[3][2]*v.z()+_mat[3][3]) ; + return Vec3d( (_mat[0][0]*v.x() + _mat[0][1]*v.y() + _mat[0][2]*v.z() + _mat[0][3])*d, + (_mat[1][0]*v.x() + _mat[1][1]*v.y() + _mat[1][2]*v.z() + _mat[1][3])*d, + (_mat[2][0]*v.x() + _mat[2][1]*v.y() + _mat[2][2]*v.z() + _mat[2][3])*d) ; +} + +inline Vec3f Matrixd::preMult( const Vec3f& v ) const +{ + value_type d = 1.0f/(_mat[0][3]*v.x()+_mat[1][3]*v.y()+_mat[2][3]*v.z()+_mat[3][3]) ; + return Vec3f( (_mat[0][0]*v.x() + _mat[1][0]*v.y() + _mat[2][0]*v.z() + _mat[3][0])*d, + (_mat[0][1]*v.x() + _mat[1][1]*v.y() + _mat[2][1]*v.z() + _mat[3][1])*d, + (_mat[0][2]*v.x() + _mat[1][2]*v.y() + _mat[2][2]*v.z() + _mat[3][2])*d); +} + +inline Vec3d Matrixd::preMult( const Vec3d& v ) const +{ + value_type d = 1.0f/(_mat[0][3]*v.x()+_mat[1][3]*v.y()+_mat[2][3]*v.z()+_mat[3][3]) ; + return Vec3d( (_mat[0][0]*v.x() + _mat[1][0]*v.y() + _mat[2][0]*v.z() + _mat[3][0])*d, + (_mat[0][1]*v.x() + _mat[1][1]*v.y() + _mat[2][1]*v.z() + _mat[3][1])*d, + (_mat[0][2]*v.x() + _mat[1][2]*v.y() + _mat[2][2]*v.z() + _mat[3][2])*d); +} + +inline Vec4f Matrixd::postMult( const Vec4f& v ) const +{ + return Vec4f( (_mat[0][0]*v.x() + _mat[0][1]*v.y() + _mat[0][2]*v.z() + _mat[0][3]*v.w()), + (_mat[1][0]*v.x() + _mat[1][1]*v.y() + _mat[1][2]*v.z() + _mat[1][3]*v.w()), + (_mat[2][0]*v.x() + _mat[2][1]*v.y() + _mat[2][2]*v.z() + _mat[2][3]*v.w()), + (_mat[3][0]*v.x() + _mat[3][1]*v.y() + _mat[3][2]*v.z() + _mat[3][3]*v.w())) ; +} +inline Vec4d Matrixd::postMult( const Vec4d& v ) const +{ + return Vec4d( (_mat[0][0]*v.x() + _mat[0][1]*v.y() + _mat[0][2]*v.z() + _mat[0][3]*v.w()), + (_mat[1][0]*v.x() + _mat[1][1]*v.y() + _mat[1][2]*v.z() + _mat[1][3]*v.w()), + (_mat[2][0]*v.x() + _mat[2][1]*v.y() + _mat[2][2]*v.z() + _mat[2][3]*v.w()), + (_mat[3][0]*v.x() + _mat[3][1]*v.y() + _mat[3][2]*v.z() + _mat[3][3]*v.w())) ; +} + +inline Vec4f Matrixd::preMult( const Vec4f& v ) const +{ + return Vec4f( (_mat[0][0]*v.x() + _mat[1][0]*v.y() + _mat[2][0]*v.z() + _mat[3][0]*v.w()), + (_mat[0][1]*v.x() + _mat[1][1]*v.y() + _mat[2][1]*v.z() + _mat[3][1]*v.w()), + (_mat[0][2]*v.x() + _mat[1][2]*v.y() + _mat[2][2]*v.z() + _mat[3][2]*v.w()), + (_mat[0][3]*v.x() + _mat[1][3]*v.y() + _mat[2][3]*v.z() + _mat[3][3]*v.w())); +} + +inline Vec4d Matrixd::preMult( const Vec4d& v ) const +{ + return Vec4d( (_mat[0][0]*v.x() + _mat[1][0]*v.y() + _mat[2][0]*v.z() + _mat[3][0]*v.w()), + (_mat[0][1]*v.x() + _mat[1][1]*v.y() + _mat[2][1]*v.z() + _mat[3][1]*v.w()), + (_mat[0][2]*v.x() + _mat[1][2]*v.y() + _mat[2][2]*v.z() + _mat[3][2]*v.w()), + (_mat[0][3]*v.x() + _mat[1][3]*v.y() + _mat[2][3]*v.z() + _mat[3][3]*v.w())); +} + +inline Vec3f Matrixd::transform3x3(const Vec3f& v,const Matrixd& m) +{ + return Vec3f( (m._mat[0][0]*v.x() + m._mat[1][0]*v.y() + m._mat[2][0]*v.z()), + (m._mat[0][1]*v.x() + m._mat[1][1]*v.y() + m._mat[2][1]*v.z()), + (m._mat[0][2]*v.x() + m._mat[1][2]*v.y() + m._mat[2][2]*v.z())); +} +inline Vec3d Matrixd::transform3x3(const Vec3d& v,const Matrixd& m) +{ + return Vec3d( (m._mat[0][0]*v.x() + m._mat[1][0]*v.y() + m._mat[2][0]*v.z()), + (m._mat[0][1]*v.x() + m._mat[1][1]*v.y() + m._mat[2][1]*v.z()), + (m._mat[0][2]*v.x() + m._mat[1][2]*v.y() + m._mat[2][2]*v.z())); +} + +inline Vec3f Matrixd::transform3x3(const Matrixd& m,const Vec3f& v) +{ + return Vec3f( (m._mat[0][0]*v.x() + m._mat[0][1]*v.y() + m._mat[0][2]*v.z()), + (m._mat[1][0]*v.x() + m._mat[1][1]*v.y() + m._mat[1][2]*v.z()), + (m._mat[2][0]*v.x() + m._mat[2][1]*v.y() + m._mat[2][2]*v.z()) ) ; +} +inline Vec3d Matrixd::transform3x3(const Matrixd& m,const Vec3d& v) +{ + return Vec3d( (m._mat[0][0]*v.x() + m._mat[0][1]*v.y() + m._mat[0][2]*v.z()), + (m._mat[1][0]*v.x() + m._mat[1][1]*v.y() + m._mat[1][2]*v.z()), + (m._mat[2][0]*v.x() + m._mat[2][1]*v.y() + m._mat[2][2]*v.z()) ) ; +} + +inline void Matrixd::preMultTranslate( const Vec3d& v ) +{ + for (unsigned i = 0; i < 3; ++i) + { + double tmp = v[i]; + if (tmp == 0) + continue; + _mat[3][0] += tmp*_mat[i][0]; + _mat[3][1] += tmp*_mat[i][1]; + _mat[3][2] += tmp*_mat[i][2]; + _mat[3][3] += tmp*_mat[i][3]; + } +} + +inline void Matrixd::preMultTranslate( const Vec3f& v ) +{ + for (unsigned i = 0; i < 3; ++i) + { + float tmp = v[i]; + if (tmp == 0) + continue; + _mat[3][0] += tmp*_mat[i][0]; + _mat[3][1] += tmp*_mat[i][1]; + _mat[3][2] += tmp*_mat[i][2]; + _mat[3][3] += tmp*_mat[i][3]; + } +} + +inline void Matrixd::postMultTranslate( const Vec3d& v ) +{ + for (unsigned i = 0; i < 3; ++i) + { + double tmp = v[i]; + if (tmp == 0) + continue; + _mat[0][i] += tmp*_mat[0][3]; + _mat[1][i] += tmp*_mat[1][3]; + _mat[2][i] += tmp*_mat[2][3]; + _mat[3][i] += tmp*_mat[3][3]; + } +} + +inline void Matrixd::postMultTranslate( const Vec3f& v ) +{ + for (unsigned i = 0; i < 3; ++i) + { + float tmp = v[i]; + if (tmp == 0) + continue; + _mat[0][i] += tmp*_mat[0][3]; + _mat[1][i] += tmp*_mat[1][3]; + _mat[2][i] += tmp*_mat[2][3]; + _mat[3][i] += tmp*_mat[3][3]; + } +} + +inline void Matrixd::preMultScale( const Vec3d& v ) +{ + _mat[0][0] *= v[0]; _mat[0][1] *= v[0]; _mat[0][2] *= v[0]; _mat[0][3] *= v[0]; + _mat[1][0] *= v[1]; _mat[1][1] *= v[1]; _mat[1][2] *= v[1]; _mat[1][3] *= v[1]; + _mat[2][0] *= v[2]; _mat[2][1] *= v[2]; _mat[2][2] *= v[2]; _mat[2][3] *= v[2]; +} + +inline void Matrixd::preMultScale( const Vec3f& v ) +{ + _mat[0][0] *= v[0]; _mat[0][1] *= v[0]; _mat[0][2] *= v[0]; _mat[0][3] *= v[0]; + _mat[1][0] *= v[1]; _mat[1][1] *= v[1]; _mat[1][2] *= v[1]; _mat[1][3] *= v[1]; + _mat[2][0] *= v[2]; _mat[2][1] *= v[2]; _mat[2][2] *= v[2]; _mat[2][3] *= v[2]; +} + +inline void Matrixd::postMultScale( const Vec3d& v ) +{ + _mat[0][0] *= v[0]; _mat[1][0] *= v[0]; _mat[2][0] *= v[0]; _mat[3][0] *= v[0]; + _mat[0][1] *= v[1]; _mat[1][1] *= v[1]; _mat[2][1] *= v[1]; _mat[3][1] *= v[1]; + _mat[0][2] *= v[2]; _mat[1][2] *= v[2]; _mat[2][2] *= v[2]; _mat[3][2] *= v[2]; +} + +inline void Matrixd::postMultScale( const Vec3f& v ) +{ + _mat[0][0] *= v[0]; _mat[1][0] *= v[0]; _mat[2][0] *= v[0]; _mat[3][0] *= v[0]; + _mat[0][1] *= v[1]; _mat[1][1] *= v[1]; _mat[2][1] *= v[1]; _mat[3][1] *= v[1]; + _mat[0][2] *= v[2]; _mat[1][2] *= v[2]; _mat[2][2] *= v[2]; _mat[3][2] *= v[2]; +} + +inline void Matrixd::preMultRotate( const Quat& q ) +{ + if (q.zeroRotation()) + return; + Matrixd r; + r.setRotate(q); + preMult(r); +} + +inline void Matrixd::postMultRotate( const Quat& q ) +{ + if (q.zeroRotation()) + return; + Matrixd r; + r.setRotate(q); + postMult(r); +} + +inline Vec3f operator* (const Vec3f& v, const Matrixd& m ) +{ + return m.preMult(v); +} + +inline Vec3d operator* (const Vec3d& v, const Matrixd& m ) +{ + return m.preMult(v); +} + +inline Vec4f operator* (const Vec4f& v, const Matrixd& m ) +{ + return m.preMult(v); +} + +inline Vec4d operator* (const Vec4d& v, const Matrixd& m ) +{ + return m.preMult(v); +} + +inline Vec3f Matrixd::operator* (const Vec3f& v) const +{ + return postMult(v); +} + +inline Vec3d Matrixd::operator* (const Vec3d& v) const +{ + return postMult(v); +} + +inline Vec4f Matrixd::operator* (const Vec4f& v) const +{ + return postMult(v); +} + +inline Vec4d Matrixd::operator* (const Vec4d& v) const +{ + return postMult(v); +} + + +} //namespace osg + + +#endif diff --git a/libs/include/android/osg/Matrixf b/libs/include/android/osg/Matrixf new file mode 100755 index 0000000..0d60501 --- /dev/null +++ b/libs/include/android/osg/Matrixf @@ -0,0 +1,930 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2004 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_MATRIXF +#define OSG_MATRIXF 1 + +#include +#include +#include +#include + +namespace osg { + +class Matrixf; + +class OSG_EXPORT Matrixf +{ + public: + + typedef float value_type; + typedef double other_value_type; + + inline Matrixf() { makeIdentity(); } + inline Matrixf( const Matrixf& mat) { set(mat.ptr()); } + Matrixf( const Matrixd& mat ); + inline explicit Matrixf( float const * const ptr ) { set(ptr); } + inline explicit Matrixf( double const * const ptr ) { set(ptr); } + inline explicit Matrixf( const Quat& quat ) { makeRotate(quat); } + + Matrixf( value_type a00, value_type a01, value_type a02, value_type a03, + value_type a10, value_type a11, value_type a12, value_type a13, + value_type a20, value_type a21, value_type a22, value_type a23, + value_type a30, value_type a31, value_type a32, value_type a33); + + ~Matrixf() {} + + int compare(const Matrixf& m) const; + + bool operator < (const Matrixf& m) const { return compare(m)<0; } + bool operator == (const Matrixf& m) const { return compare(m)==0; } + bool operator != (const Matrixf& m) const { return compare(m)!=0; } + + inline value_type& operator()(int row, int col) { return _mat[row][col]; } + inline value_type operator()(int row, int col) const { return _mat[row][col]; } + + inline bool valid() const { return !isNaN(); } + inline bool isNaN() const { return osg::isNaN(_mat[0][0]) || osg::isNaN(_mat[0][1]) || osg::isNaN(_mat[0][2]) || osg::isNaN(_mat[0][3]) || + osg::isNaN(_mat[1][0]) || osg::isNaN(_mat[1][1]) || osg::isNaN(_mat[1][2]) || osg::isNaN(_mat[1][3]) || + osg::isNaN(_mat[2][0]) || osg::isNaN(_mat[2][1]) || osg::isNaN(_mat[2][2]) || osg::isNaN(_mat[2][3]) || + osg::isNaN(_mat[3][0]) || osg::isNaN(_mat[3][1]) || osg::isNaN(_mat[3][2]) || osg::isNaN(_mat[3][3]); } + + inline Matrixf& operator = (const Matrixf& rhs) + { + if( &rhs == this ) return *this; + set(rhs.ptr()); + return *this; + } + + Matrixf& operator = (const Matrixd& other); + + inline void set(const Matrixf& rhs) { set(rhs.ptr()); } + + void set(const Matrixd& rhs); + + inline void set(float const * const ptr) + { + value_type* local_ptr = (value_type*)_mat; + for(int i=0;i<16;++i) local_ptr[i]=(value_type)ptr[i]; + } + + inline void set(double const * const ptr) + { + value_type* local_ptr = (value_type*)_mat; + for(int i=0;i<16;++i) local_ptr[i]=(value_type)ptr[i]; + } + + void set(value_type a00, value_type a01, value_type a02,value_type a03, + value_type a10, value_type a11, value_type a12,value_type a13, + value_type a20, value_type a21, value_type a22,value_type a23, + value_type a30, value_type a31, value_type a32,value_type a33); + + value_type * ptr() { return (value_type*)_mat; } + const value_type * ptr() const { return (const value_type *)_mat; } + + bool isIdentity() const + { + return _mat[0][0]==1.0f && _mat[0][1]==0.0f && _mat[0][2]==0.0f && _mat[0][3]==0.0f && + _mat[1][0]==0.0f && _mat[1][1]==1.0f && _mat[1][2]==0.0f && _mat[1][3]==0.0f && + _mat[2][0]==0.0f && _mat[2][1]==0.0f && _mat[2][2]==1.0f && _mat[2][3]==0.0f && + _mat[3][0]==0.0f && _mat[3][1]==0.0f && _mat[3][2]==0.0f && _mat[3][3]==1.0f; + } + + void makeIdentity(); + + void makeScale( const Vec3f& ); + void makeScale( const Vec3d& ); + void makeScale( value_type, value_type, value_type ); + + void makeTranslate( const Vec3f& ); + void makeTranslate( const Vec3d& ); + void makeTranslate( value_type, value_type, value_type ); + + void makeRotate( const Vec3f& from, const Vec3f& to ); + void makeRotate( const Vec3d& from, const Vec3d& to ); + void makeRotate( value_type angle, const Vec3f& axis ); + void makeRotate( value_type angle, const Vec3d& axis ); + void makeRotate( value_type angle, value_type x, value_type y, value_type z ); + void makeRotate( const Quat& ); + void makeRotate( value_type angle1, const Vec3f& axis1, + value_type angle2, const Vec3f& axis2, + value_type angle3, const Vec3f& axis3); + void makeRotate( value_type angle1, const Vec3d& axis1, + value_type angle2, const Vec3d& axis2, + value_type angle3, const Vec3d& axis3); + + + /** decompose the matrix into translation, rotation, scale and scale orientation.*/ + void decompose( osg::Vec3f& translation, + osg::Quat& rotation, + osg::Vec3f& scale, + osg::Quat& so ) const; + + /** decompose the matrix into translation, rotation, scale and scale orientation.*/ + void decompose( osg::Vec3d& translation, + osg::Quat& rotation, + osg::Vec3d& scale, + osg::Quat& so ) const; + + + /** Set to an orthographic projection. + * See glOrtho for further details. + */ + void makeOrtho(double left, double right, + double bottom, double top, + double zNear, double zFar); + + /** Get the orthographic settings of the orthographic projection matrix. + * Note, if matrix is not an orthographic matrix then invalid values + * will be returned. + */ + bool getOrtho(double& left, double& right, + double& bottom, double& top, + double& zNear, double& zFar) const; + + /** float version of getOrtho(..) */ + bool getOrtho(float& left, float& right, + float& bottom, float& top, + float& zNear, float& zFar) const; + + + /** Set to a 2D orthographic projection. + * See glOrtho2D for further details. + */ + inline void makeOrtho2D(double left, double right, + double bottom, double top) + { + makeOrtho(left,right,bottom,top,-1.0,1.0); + } + + + /** Set to a perspective projection. + * See glFrustum for further details. + */ + void makeFrustum(double left, double right, + double bottom, double top, + double zNear, double zFar); + + /** Get the frustum settings of a perspective projection matrix. + * Note, if matrix is not a perspective matrix then invalid values + * will be returned. + */ + bool getFrustum(double& left, double& right, + double& bottom, double& top, + double& zNear, double& zFar) const; + + /** float version of getFrustum(..) */ + bool getFrustum(float& left, float& right, + float& bottom, float& top, + float& zNear, float& zFar) const; + + /** Set to a symmetrical perspective projection. + * See gluPerspective for further details. + * Aspect ratio is defined as width/height. + */ + void makePerspective(double fovy, double aspectRatio, + double zNear, double zFar); + + /** Get the frustum settings of a symmetric perspective projection + * matrix. + * Return false if matrix is not a perspective matrix, + * where parameter values are undefined. + * Note, if matrix is not a symmetric perspective matrix then the + * shear will be lost. + * Asymmetric matrices occur when stereo, power walls, caves and + * reality center display are used. + * In these configuration one should use the AsFrustum method instead. + */ + bool getPerspective(double& fovy, double& aspectRatio, + double& zNear, double& zFar) const; + + /** float version of getPerspective(..) */ + bool getPerspective(float& fovy, float& aspectRatio, + float& zNear, float& zFar) const; + + /** Set the position and orientation to be a view matrix, + * using the same convention as gluLookAt. + */ + void makeLookAt(const Vec3d& eye,const Vec3d& center,const Vec3d& up); + + /** Get to the position and orientation of a modelview matrix, + * using the same convention as gluLookAt. + */ + void getLookAt(Vec3f& eye,Vec3f& center,Vec3f& up, + value_type lookDistance=1.0f) const; + + /** Get to the position and orientation of a modelview matrix, + * using the same convention as gluLookAt. + */ + void getLookAt(Vec3d& eye,Vec3d& center,Vec3d& up, + value_type lookDistance=1.0f) const; + + /** invert the matrix rhs, automatically select invert_4x3 or invert_4x4. */ + inline bool invert( const Matrixf& rhs) + { + bool is_4x3 = (rhs._mat[0][3]==0.0f && rhs._mat[1][3]==0.0f && rhs._mat[2][3]==0.0f && rhs._mat[3][3]==1.0f); + return is_4x3 ? invert_4x3(rhs) : invert_4x4(rhs); + } + + /** 4x3 matrix invert, not right hand column is assumed to be 0,0,0,1. */ + bool invert_4x3( const Matrixf& rhs); + + /** full 4x4 matrix invert. */ + bool invert_4x4( const Matrixf& rhs); + + /** ortho-normalize the 3x3 rotation & scale matrix */ + void orthoNormalize(const Matrixf& rhs); + + //basic utility functions to create new matrices + inline static Matrixf identity( void ); + inline static Matrixf scale( const Vec3f& sv); + inline static Matrixf scale( const Vec3d& sv); + inline static Matrixf scale( value_type sx, value_type sy, value_type sz); + inline static Matrixf translate( const Vec3f& dv); + inline static Matrixf translate( const Vec3d& dv); + inline static Matrixf translate( value_type x, value_type y, value_type z); + inline static Matrixf rotate( const Vec3f& from, const Vec3f& to); + inline static Matrixf rotate( const Vec3d& from, const Vec3d& to); + inline static Matrixf rotate( value_type angle, value_type x, value_type y, value_type z); + inline static Matrixf rotate( value_type angle, const Vec3f& axis); + inline static Matrixf rotate( value_type angle, const Vec3d& axis); + inline static Matrixf rotate( value_type angle1, const Vec3f& axis1, + value_type angle2, const Vec3f& axis2, + value_type angle3, const Vec3f& axis3); + inline static Matrixf rotate( value_type angle1, const Vec3d& axis1, + value_type angle2, const Vec3d& axis2, + value_type angle3, const Vec3d& axis3); + inline static Matrixf rotate( const Quat& quat); + inline static Matrixf inverse( const Matrixf& matrix); + inline static Matrixf orthoNormal(const Matrixf& matrix); + + /** Create an orthographic projection matrix. + * See glOrtho for further details. + */ + inline static Matrixf ortho(double left, double right, + double bottom, double top, + double zNear, double zFar); + + /** Create a 2D orthographic projection. + * See glOrtho for further details. + */ + inline static Matrixf ortho2D(double left, double right, + double bottom, double top); + + /** Create a perspective projection. + * See glFrustum for further details. + */ + inline static Matrixf frustum(double left, double right, + double bottom, double top, + double zNear, double zFar); + + /** Create a symmetrical perspective projection. + * See gluPerspective for further details. + * Aspect ratio is defined as width/height. + */ + inline static Matrixf perspective(double fovy, double aspectRatio, + double zNear, double zFar); + + /** Create the position and orientation as per a camera, + * using the same convention as gluLookAt. + */ + inline static Matrixf lookAt(const Vec3f& eye, + const Vec3f& center, + const Vec3f& up); + + /** Create the position and orientation as per a camera, + * using the same convention as gluLookAt. + */ + inline static Matrixf lookAt(const Vec3d& eye, + const Vec3d& center, + const Vec3d& up); + + inline Vec3f preMult( const Vec3f& v ) const; + inline Vec3d preMult( const Vec3d& v ) const; + inline Vec3f postMult( const Vec3f& v ) const; + inline Vec3d postMult( const Vec3d& v ) const; + inline Vec3f operator* ( const Vec3f& v ) const; + inline Vec3d operator* ( const Vec3d& v ) const; + inline Vec4f preMult( const Vec4f& v ) const; + inline Vec4d preMult( const Vec4d& v ) const; + inline Vec4f postMult( const Vec4f& v ) const; + inline Vec4d postMult( const Vec4d& v ) const; + inline Vec4f operator* ( const Vec4f& v ) const; + inline Vec4d operator* ( const Vec4d& v ) const; + +#ifdef USE_DEPRECATED_API + inline void set(const Quat& q) { makeRotate(q); } + inline void get(Quat& q) const { q = getRotate(); } +#endif + + void setRotate(const Quat& q); + /** Get the matrix rotation as a Quat. Note that this function + * assumes a non-scaled matrix and will return incorrect results + * for scaled matrixces. Consider decompose() instead. + */ + Quat getRotate() const; + + + void setTrans( value_type tx, value_type ty, value_type tz ); + void setTrans( const Vec3f& v ); + void setTrans( const Vec3d& v ); + + inline Vec3d getTrans() const { return Vec3d(_mat[3][0],_mat[3][1],_mat[3][2]); } + + inline Vec3d getScale() const { + Vec3d x_vec(_mat[0][0],_mat[1][0],_mat[2][0]); + Vec3d y_vec(_mat[0][1],_mat[1][1],_mat[2][1]); + Vec3d z_vec(_mat[0][2],_mat[1][2],_mat[2][2]); + return Vec3d(x_vec.length(), y_vec.length(), z_vec.length()); + } + + /** apply a 3x3 transform of v*M[0..2,0..2]. */ + inline static Vec3f transform3x3(const Vec3f& v,const Matrixf& m); + + /** apply a 3x3 transform of v*M[0..2,0..2]. */ + inline static Vec3d transform3x3(const Vec3d& v,const Matrixf& m); + + /** apply a 3x3 transform of M[0..2,0..2]*v. */ + inline static Vec3f transform3x3(const Matrixf& m,const Vec3f& v); + + /** apply a 3x3 transform of M[0..2,0..2]*v. */ + inline static Vec3d transform3x3(const Matrixf& m,const Vec3d& v); + + // basic Matrixf multiplication, our workhorse methods. + void mult( const Matrixf&, const Matrixf& ); + void preMult( const Matrixf& ); + void postMult( const Matrixf& ); + + /** Optimized version of preMult(translate(v)); */ + inline void preMultTranslate( const Vec3d& v ); + inline void preMultTranslate( const Vec3f& v ); + /** Optimized version of postMult(translate(v)); */ + inline void postMultTranslate( const Vec3d& v ); + inline void postMultTranslate( const Vec3f& v ); + + /** Optimized version of preMult(scale(v)); */ + inline void preMultScale( const Vec3d& v ); + inline void preMultScale( const Vec3f& v ); + /** Optimized version of postMult(scale(v)); */ + inline void postMultScale( const Vec3d& v ); + inline void postMultScale( const Vec3f& v ); + + /** Optimized version of preMult(rotate(q)); */ + inline void preMultRotate( const Quat& q ); + /** Optimized version of postMult(rotate(q)); */ + inline void postMultRotate( const Quat& q ); + + inline void operator *= ( const Matrixf& other ) + { if( this == &other ) { + Matrixf temp(other); + postMult( temp ); + } + else postMult( other ); + } + + inline Matrixf operator * ( const Matrixf &m ) const + { + osg::Matrixf r; + r.mult(*this,m); + return r; + } + + /** Multiply by scalar. */ + inline Matrixf operator * (value_type rhs) const + { + return Matrixf( + _mat[0][0]*rhs, _mat[0][1]*rhs, _mat[0][2]*rhs, _mat[0][3]*rhs, + _mat[1][0]*rhs, _mat[1][1]*rhs, _mat[1][2]*rhs, _mat[1][3]*rhs, + _mat[2][0]*rhs, _mat[2][1]*rhs, _mat[2][2]*rhs, _mat[2][3]*rhs, + _mat[3][0]*rhs, _mat[3][1]*rhs, _mat[3][2]*rhs, _mat[3][3]*rhs); + } + + /** Unary multiply by scalar. */ + inline Matrixf& operator *= (value_type rhs) + { + _mat[0][0]*=rhs; + _mat[0][1]*=rhs; + _mat[0][2]*=rhs; + _mat[0][3]*=rhs; + _mat[1][0]*=rhs; + _mat[1][1]*=rhs; + _mat[1][2]*=rhs; + _mat[1][3]*=rhs; + _mat[2][0]*=rhs; + _mat[2][1]*=rhs; + _mat[2][2]*=rhs; + _mat[2][3]*=rhs; + _mat[3][0]*=rhs; + _mat[3][1]*=rhs; + _mat[3][2]*=rhs; + _mat[3][3]*=rhs; + return *this; + } + + /** Divide by scalar. */ + inline Matrixf operator / (value_type rhs) const + { + return Matrixf( + _mat[0][0]/rhs, _mat[0][1]/rhs, _mat[0][2]/rhs, _mat[0][3]/rhs, + _mat[1][0]/rhs, _mat[1][1]/rhs, _mat[1][2]/rhs, _mat[1][3]/rhs, + _mat[2][0]/rhs, _mat[2][1]/rhs, _mat[2][2]/rhs, _mat[2][3]/rhs, + _mat[3][0]/rhs, _mat[3][1]/rhs, _mat[3][2]/rhs, _mat[3][3]/rhs); + } + + /** Unary divide by scalar. */ + inline Matrixf& operator /= (value_type rhs) + { + _mat[0][0]/=rhs; + _mat[0][1]/=rhs; + _mat[0][2]/=rhs; + _mat[0][3]/=rhs; + _mat[1][0]/=rhs; + _mat[1][1]/=rhs; + _mat[1][2]/=rhs; + _mat[1][3]/=rhs; + _mat[2][0]/=rhs; + _mat[2][1]/=rhs; + _mat[2][2]/=rhs; + _mat[2][3]/=rhs; + _mat[3][0]/=rhs; + _mat[3][1]/=rhs; + _mat[3][2]/=rhs; + _mat[3][3]/=rhs; + return *this; + } + + /** Binary vector add. */ + inline Matrixf operator + (const Matrixf& rhs) const + { + return Matrixf( + _mat[0][0] + rhs._mat[0][0], + _mat[0][1] + rhs._mat[0][1], + _mat[0][2] + rhs._mat[0][2], + _mat[0][3] + rhs._mat[0][3], + _mat[1][0] + rhs._mat[1][0], + _mat[1][1] + rhs._mat[1][1], + _mat[1][2] + rhs._mat[1][2], + _mat[1][3] + rhs._mat[1][3], + _mat[2][0] + rhs._mat[2][0], + _mat[2][1] + rhs._mat[2][1], + _mat[2][2] + rhs._mat[2][2], + _mat[2][3] + rhs._mat[2][3], + _mat[3][0] + rhs._mat[3][0], + _mat[3][1] + rhs._mat[3][1], + _mat[3][2] + rhs._mat[3][2], + _mat[3][3] + rhs._mat[3][3]); + } + + /** Unary vector add. Slightly more efficient because no temporary + * intermediate object. + */ + inline Matrixf& operator += (const Matrixf& rhs) + { + _mat[0][0] += rhs._mat[0][0]; + _mat[0][1] += rhs._mat[0][1]; + _mat[0][2] += rhs._mat[0][2]; + _mat[0][3] += rhs._mat[0][3]; + _mat[1][0] += rhs._mat[1][0]; + _mat[1][1] += rhs._mat[1][1]; + _mat[1][2] += rhs._mat[1][2]; + _mat[1][3] += rhs._mat[1][3]; + _mat[2][0] += rhs._mat[2][0]; + _mat[2][1] += rhs._mat[2][1]; + _mat[2][2] += rhs._mat[2][2]; + _mat[2][3] += rhs._mat[2][3]; + _mat[3][0] += rhs._mat[3][0]; + _mat[3][1] += rhs._mat[3][1]; + _mat[3][2] += rhs._mat[3][2]; + _mat[3][3] += rhs._mat[3][3]; + return *this; + } + + protected: + value_type _mat[4][4]; + +}; + +class RefMatrixf : public Object, public Matrixf +{ + public: + + RefMatrixf():Object(false), Matrixf() {} + RefMatrixf( const Matrixf& other) : Object(false), Matrixf(other) {} + RefMatrixf( const Matrixd& other) : Object(false), Matrixf(other) {} + RefMatrixf( const RefMatrixf& other) : Object(other), Matrixf(other) {} + explicit RefMatrixf( Matrixf::value_type const * const def ):Object(false), Matrixf(def) {} + RefMatrixf( Matrixf::value_type a00, Matrixf::value_type a01, Matrixf::value_type a02, Matrixf::value_type a03, + Matrixf::value_type a10, Matrixf::value_type a11, Matrixf::value_type a12, Matrixf::value_type a13, + Matrixf::value_type a20, Matrixf::value_type a21, Matrixf::value_type a22, Matrixf::value_type a23, + Matrixf::value_type a30, Matrixf::value_type a31, Matrixf::value_type a32, Matrixf::value_type a33): + Object(false), + Matrixf(a00, a01, a02, a03, + a10, a11, a12, a13, + a20, a21, a22, a23, + a30, a31, a32, a33) {} + + virtual Object* cloneType() const { return new RefMatrixf(); } + virtual Object* clone(const CopyOp&) const { return new RefMatrixf(*this); } + virtual bool isSameKindAs(const Object* obj) const { return dynamic_cast(obj)!=NULL; } + virtual const char* libraryName() const { return "osg"; } + virtual const char* className() const { return "Matrix"; } + + + protected: + + virtual ~RefMatrixf() {} +}; + + +//static utility methods +inline Matrixf Matrixf::identity(void) +{ + Matrixf m; + m.makeIdentity(); + return m; +} + +inline Matrixf Matrixf::scale(value_type sx, value_type sy, value_type sz) +{ + Matrixf m; + m.makeScale(sx,sy,sz); + return m; +} + +inline Matrixf Matrixf::scale(const Vec3f& v ) +{ + return scale(v.x(), v.y(), v.z() ); +} + +inline Matrixf Matrixf::scale(const Vec3d& v ) +{ + return scale(v.x(), v.y(), v.z() ); +} + +inline Matrixf Matrixf::translate(value_type tx, value_type ty, value_type tz) +{ + Matrixf m; + m.makeTranslate(tx,ty,tz); + return m; +} + +inline Matrixf Matrixf::translate(const Vec3f& v ) +{ + return translate(v.x(), v.y(), v.z() ); +} + +inline Matrixf Matrixf::translate(const Vec3d& v ) +{ + return translate(v.x(), v.y(), v.z() ); +} + +inline Matrixf Matrixf::rotate( const Quat& q ) +{ + return Matrixf(q); +} +inline Matrixf Matrixf::rotate(value_type angle, value_type x, value_type y, value_type z ) +{ + Matrixf m; + m.makeRotate(angle,x,y,z); + return m; +} +inline Matrixf Matrixf::rotate(value_type angle, const Vec3f& axis ) +{ + Matrixf m; + m.makeRotate(angle,axis); + return m; +} +inline Matrixf Matrixf::rotate(value_type angle, const Vec3d& axis ) +{ + Matrixf m; + m.makeRotate(angle,axis); + return m; +} +inline Matrixf Matrixf::rotate( value_type angle1, const Vec3f& axis1, + value_type angle2, const Vec3f& axis2, + value_type angle3, const Vec3f& axis3) +{ + Matrixf m; + m.makeRotate(angle1,axis1,angle2,axis2,angle3,axis3); + return m; +} +inline Matrixf Matrixf::rotate( value_type angle1, const Vec3d& axis1, + value_type angle2, const Vec3d& axis2, + value_type angle3, const Vec3d& axis3) +{ + Matrixf m; + m.makeRotate(angle1,axis1,angle2,axis2,angle3,axis3); + return m; +} +inline Matrixf Matrixf::rotate(const Vec3f& from, const Vec3f& to ) +{ + Matrixf m; + m.makeRotate(from,to); + return m; +} +inline Matrixf Matrixf::rotate(const Vec3d& from, const Vec3d& to ) +{ + Matrixf m; + m.makeRotate(from,to); + return m; +} + +inline Matrixf Matrixf::inverse( const Matrixf& matrix) +{ + Matrixf m; + m.invert(matrix); + return m; +} + +inline Matrixf Matrixf::orthoNormal(const Matrixf& matrix) +{ + Matrixf m; + m.orthoNormalize(matrix); + return m; +} + +inline Matrixf Matrixf::ortho(double left, double right, + double bottom, double top, + double zNear, double zFar) +{ + Matrixf m; + m.makeOrtho(left,right,bottom,top,zNear,zFar); + return m; +} + +inline Matrixf Matrixf::ortho2D(double left, double right, + double bottom, double top) +{ + Matrixf m; + m.makeOrtho2D(left,right,bottom,top); + return m; +} + +inline Matrixf Matrixf::frustum(double left, double right, + double bottom, double top, + double zNear, double zFar) +{ + Matrixf m; + m.makeFrustum(left,right,bottom,top,zNear,zFar); + return m; +} + +inline Matrixf Matrixf::perspective(double fovy,double aspectRatio, + double zNear, double zFar) +{ + Matrixf m; + m.makePerspective(fovy,aspectRatio,zNear,zFar); + return m; +} + +inline Matrixf Matrixf::lookAt(const Vec3f& eye,const Vec3f& center,const Vec3f& up) +{ + Matrixf m; + m.makeLookAt(eye,center,up); + return m; +} + +inline Matrixf Matrixf::lookAt(const Vec3d& eye,const Vec3d& center,const Vec3d& up) +{ + Matrixf m; + m.makeLookAt(eye,center,up); + return m; +} + +inline Vec3f Matrixf::postMult( const Vec3f& v ) const +{ + value_type d = 1.0f/(_mat[3][0]*v.x()+_mat[3][1]*v.y()+_mat[3][2]*v.z()+_mat[3][3]) ; + return Vec3f( (_mat[0][0]*v.x() + _mat[0][1]*v.y() + _mat[0][2]*v.z() + _mat[0][3])*d, + (_mat[1][0]*v.x() + _mat[1][1]*v.y() + _mat[1][2]*v.z() + _mat[1][3])*d, + (_mat[2][0]*v.x() + _mat[2][1]*v.y() + _mat[2][2]*v.z() + _mat[2][3])*d) ; +} +inline Vec3d Matrixf::postMult( const Vec3d& v ) const +{ + value_type d = 1.0f/(_mat[3][0]*v.x()+_mat[3][1]*v.y()+_mat[3][2]*v.z()+_mat[3][3]) ; + return Vec3d( (_mat[0][0]*v.x() + _mat[0][1]*v.y() + _mat[0][2]*v.z() + _mat[0][3])*d, + (_mat[1][0]*v.x() + _mat[1][1]*v.y() + _mat[1][2]*v.z() + _mat[1][3])*d, + (_mat[2][0]*v.x() + _mat[2][1]*v.y() + _mat[2][2]*v.z() + _mat[2][3])*d) ; +} + +inline Vec3f Matrixf::preMult( const Vec3f& v ) const +{ + value_type d = 1.0f/(_mat[0][3]*v.x()+_mat[1][3]*v.y()+_mat[2][3]*v.z()+_mat[3][3]) ; + return Vec3f( (_mat[0][0]*v.x() + _mat[1][0]*v.y() + _mat[2][0]*v.z() + _mat[3][0])*d, + (_mat[0][1]*v.x() + _mat[1][1]*v.y() + _mat[2][1]*v.z() + _mat[3][1])*d, + (_mat[0][2]*v.x() + _mat[1][2]*v.y() + _mat[2][2]*v.z() + _mat[3][2])*d); +} +inline Vec3d Matrixf::preMult( const Vec3d& v ) const +{ + value_type d = 1.0f/(_mat[0][3]*v.x()+_mat[1][3]*v.y()+_mat[2][3]*v.z()+_mat[3][3]) ; + return Vec3d( (_mat[0][0]*v.x() + _mat[1][0]*v.y() + _mat[2][0]*v.z() + _mat[3][0])*d, + (_mat[0][1]*v.x() + _mat[1][1]*v.y() + _mat[2][1]*v.z() + _mat[3][1])*d, + (_mat[0][2]*v.x() + _mat[1][2]*v.y() + _mat[2][2]*v.z() + _mat[3][2])*d); +} + +inline Vec4f Matrixf::postMult( const Vec4f& v ) const +{ + return Vec4f( (_mat[0][0]*v.x() + _mat[0][1]*v.y() + _mat[0][2]*v.z() + _mat[0][3]*v.w()), + (_mat[1][0]*v.x() + _mat[1][1]*v.y() + _mat[1][2]*v.z() + _mat[1][3]*v.w()), + (_mat[2][0]*v.x() + _mat[2][1]*v.y() + _mat[2][2]*v.z() + _mat[2][3]*v.w()), + (_mat[3][0]*v.x() + _mat[3][1]*v.y() + _mat[3][2]*v.z() + _mat[3][3]*v.w())) ; +} +inline Vec4d Matrixf::postMult( const Vec4d& v ) const +{ + return Vec4d( (_mat[0][0]*v.x() + _mat[0][1]*v.y() + _mat[0][2]*v.z() + _mat[0][3]*v.w()), + (_mat[1][0]*v.x() + _mat[1][1]*v.y() + _mat[1][2]*v.z() + _mat[1][3]*v.w()), + (_mat[2][0]*v.x() + _mat[2][1]*v.y() + _mat[2][2]*v.z() + _mat[2][3]*v.w()), + (_mat[3][0]*v.x() + _mat[3][1]*v.y() + _mat[3][2]*v.z() + _mat[3][3]*v.w())) ; +} + +inline Vec4f Matrixf::preMult( const Vec4f& v ) const +{ + return Vec4f( (_mat[0][0]*v.x() + _mat[1][0]*v.y() + _mat[2][0]*v.z() + _mat[3][0]*v.w()), + (_mat[0][1]*v.x() + _mat[1][1]*v.y() + _mat[2][1]*v.z() + _mat[3][1]*v.w()), + (_mat[0][2]*v.x() + _mat[1][2]*v.y() + _mat[2][2]*v.z() + _mat[3][2]*v.w()), + (_mat[0][3]*v.x() + _mat[1][3]*v.y() + _mat[2][3]*v.z() + _mat[3][3]*v.w())); +} +inline Vec4d Matrixf::preMult( const Vec4d& v ) const +{ + return Vec4d( (_mat[0][0]*v.x() + _mat[1][0]*v.y() + _mat[2][0]*v.z() + _mat[3][0]*v.w()), + (_mat[0][1]*v.x() + _mat[1][1]*v.y() + _mat[2][1]*v.z() + _mat[3][1]*v.w()), + (_mat[0][2]*v.x() + _mat[1][2]*v.y() + _mat[2][2]*v.z() + _mat[3][2]*v.w()), + (_mat[0][3]*v.x() + _mat[1][3]*v.y() + _mat[2][3]*v.z() + _mat[3][3]*v.w())); +} +inline Vec3f Matrixf::transform3x3(const Vec3f& v,const Matrixf& m) +{ + return Vec3f( (m._mat[0][0]*v.x() + m._mat[1][0]*v.y() + m._mat[2][0]*v.z()), + (m._mat[0][1]*v.x() + m._mat[1][1]*v.y() + m._mat[2][1]*v.z()), + (m._mat[0][2]*v.x() + m._mat[1][2]*v.y() + m._mat[2][2]*v.z())); +} +inline Vec3d Matrixf::transform3x3(const Vec3d& v,const Matrixf& m) +{ + return Vec3d( (m._mat[0][0]*v.x() + m._mat[1][0]*v.y() + m._mat[2][0]*v.z()), + (m._mat[0][1]*v.x() + m._mat[1][1]*v.y() + m._mat[2][1]*v.z()), + (m._mat[0][2]*v.x() + m._mat[1][2]*v.y() + m._mat[2][2]*v.z())); +} + +inline Vec3f Matrixf::transform3x3(const Matrixf& m,const Vec3f& v) +{ + return Vec3f( (m._mat[0][0]*v.x() + m._mat[0][1]*v.y() + m._mat[0][2]*v.z()), + (m._mat[1][0]*v.x() + m._mat[1][1]*v.y() + m._mat[1][2]*v.z()), + (m._mat[2][0]*v.x() + m._mat[2][1]*v.y() + m._mat[2][2]*v.z()) ) ; +} +inline Vec3d Matrixf::transform3x3(const Matrixf& m,const Vec3d& v) +{ + return Vec3d( (m._mat[0][0]*v.x() + m._mat[0][1]*v.y() + m._mat[0][2]*v.z()), + (m._mat[1][0]*v.x() + m._mat[1][1]*v.y() + m._mat[1][2]*v.z()), + (m._mat[2][0]*v.x() + m._mat[2][1]*v.y() + m._mat[2][2]*v.z()) ) ; +} + +inline void Matrixf::preMultTranslate( const Vec3d& v ) +{ + for (unsigned i = 0; i < 3; ++i) + { + double tmp = v[i]; + if (tmp == 0) + continue; + _mat[3][0] += tmp*_mat[i][0]; + _mat[3][1] += tmp*_mat[i][1]; + _mat[3][2] += tmp*_mat[i][2]; + _mat[3][3] += tmp*_mat[i][3]; + } +} + +inline void Matrixf::preMultTranslate( const Vec3f& v ) +{ + for (unsigned i = 0; i < 3; ++i) + { + float tmp = v[i]; + if (tmp == 0) + continue; + _mat[3][0] += tmp*_mat[i][0]; + _mat[3][1] += tmp*_mat[i][1]; + _mat[3][2] += tmp*_mat[i][2]; + _mat[3][3] += tmp*_mat[i][3]; + } +} + +inline void Matrixf::postMultTranslate( const Vec3d& v ) +{ + for (unsigned i = 0; i < 3; ++i) + { + double tmp = v[i]; + if (tmp == 0) + continue; + _mat[0][i] += tmp*_mat[0][3]; + _mat[1][i] += tmp*_mat[1][3]; + _mat[2][i] += tmp*_mat[2][3]; + _mat[3][i] += tmp*_mat[3][3]; + } +} + +inline void Matrixf::postMultTranslate( const Vec3f& v ) +{ + for (unsigned i = 0; i < 3; ++i) + { + float tmp = v[i]; + if (tmp == 0) + continue; + _mat[0][i] += tmp*_mat[0][3]; + _mat[1][i] += tmp*_mat[1][3]; + _mat[2][i] += tmp*_mat[2][3]; + _mat[3][i] += tmp*_mat[3][3]; + } +} + +inline void Matrixf::preMultScale( const Vec3d& v ) +{ + _mat[0][0] *= v[0]; _mat[0][1] *= v[0]; _mat[0][2] *= v[0]; _mat[0][3] *= v[0]; + _mat[1][0] *= v[1]; _mat[1][1] *= v[1]; _mat[1][2] *= v[1]; _mat[1][3] *= v[1]; + _mat[2][0] *= v[2]; _mat[2][1] *= v[2]; _mat[2][2] *= v[2]; _mat[2][3] *= v[2]; +} + +inline void Matrixf::preMultScale( const Vec3f& v ) +{ + _mat[0][0] *= v[0]; _mat[0][1] *= v[0]; _mat[0][2] *= v[0]; _mat[0][3] *= v[0]; + _mat[1][0] *= v[1]; _mat[1][1] *= v[1]; _mat[1][2] *= v[1]; _mat[1][3] *= v[1]; + _mat[2][0] *= v[2]; _mat[2][1] *= v[2]; _mat[2][2] *= v[2]; _mat[2][3] *= v[2]; +} + +inline void Matrixf::postMultScale( const Vec3d& v ) +{ + _mat[0][0] *= v[0]; _mat[1][0] *= v[0]; _mat[2][0] *= v[0]; _mat[3][0] *= v[0]; + _mat[0][1] *= v[1]; _mat[1][1] *= v[1]; _mat[2][1] *= v[1]; _mat[3][1] *= v[1]; + _mat[0][2] *= v[2]; _mat[1][2] *= v[2]; _mat[2][2] *= v[2]; _mat[3][2] *= v[2]; +} + +inline void Matrixf::postMultScale( const Vec3f& v ) +{ + _mat[0][0] *= v[0]; _mat[1][0] *= v[0]; _mat[2][0] *= v[0]; _mat[3][0] *= v[0]; + _mat[0][1] *= v[1]; _mat[1][1] *= v[1]; _mat[2][1] *= v[1]; _mat[3][1] *= v[1]; + _mat[0][2] *= v[2]; _mat[1][2] *= v[2]; _mat[2][2] *= v[2]; _mat[3][2] *= v[2]; +} + + +inline void Matrixf::preMultRotate( const Quat& q ) +{ + if (q.zeroRotation()) + return; + Matrixf r; + r.setRotate(q); + preMult(r); +} + +inline void Matrixf::postMultRotate( const Quat& q ) +{ + if (q.zeroRotation()) + return; + Matrixf r; + r.setRotate(q); + postMult(r); +} + +inline Vec3f operator* (const Vec3f& v, const Matrixf& m ) +{ + return m.preMult(v); +} +inline Vec3d operator* (const Vec3d& v, const Matrixf& m ) +{ + return m.preMult(v); +} +inline Vec4f operator* (const Vec4f& v, const Matrixf& m ) +{ + return m.preMult(v); +} +inline Vec4d operator* (const Vec4d& v, const Matrixf& m ) +{ + return m.preMult(v); +} + +inline Vec3f Matrixf::operator* (const Vec3f& v) const +{ + return postMult(v); +} +inline Vec3d Matrixf::operator* (const Vec3d& v) const +{ + return postMult(v); +} +inline Vec4f Matrixf::operator* (const Vec4f& v) const +{ + return postMult(v); +} +inline Vec4d Matrixf::operator* (const Vec4d& v) const +{ + return postMult(v); +} + + +} //namespace osg + + +#endif diff --git a/libs/include/android/osg/MixinVector b/libs/include/android/osg/MixinVector new file mode 100755 index 0000000..bd8b536 --- /dev/null +++ b/libs/include/android/osg/MixinVector @@ -0,0 +1,199 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_MIXIN_VECTOR +#define OSG_MIXIN_VECTOR 1 + +#include + +namespace osg { + +/** MixinVector is a base class that allows inheritance to be used to easily + * emulate derivation from std::vector but without introducing undefined + * behaviour through violation of virtual destructor rules. + * + * @author Neil Groves + */ +template +class MixinVector +{ + typedef typename std::vector vector_type; +public: + typedef typename vector_type::allocator_type allocator_type; + typedef typename vector_type::value_type value_type; + typedef typename vector_type::const_pointer const_pointer; + typedef typename vector_type::pointer pointer; + typedef typename vector_type::const_reference const_reference; + typedef typename vector_type::reference reference; + typedef typename vector_type::const_iterator const_iterator; + typedef typename vector_type::iterator iterator; + typedef typename vector_type::const_reverse_iterator const_reverse_iterator; + typedef typename vector_type::reverse_iterator reverse_iterator; + typedef typename vector_type::size_type size_type; + typedef typename vector_type::difference_type difference_type; + + explicit MixinVector() : _impl() + { + } + + explicit MixinVector(size_type initial_size, const value_type& fill_value = value_type()) + : _impl(initial_size, fill_value) + { + } + + template + MixinVector(InputIterator first, InputIterator last) + : _impl(first, last) + { + } + + MixinVector(const vector_type& other) + : _impl(other) + { + } + + MixinVector(const MixinVector& other) + : _impl(other._impl) + { + } + + MixinVector& operator=(const vector_type& other) + { + _impl = other; + return *this; + } + + MixinVector& operator=(const MixinVector& other) + { + _impl = other._impl; + return *this; + } + + virtual ~MixinVector() {} + + void clear() { _impl.clear(); } + void resize(size_type new_size, const value_type& fill_value = value_type()) { _impl.resize(new_size, fill_value); } + void reserve(size_type new_capacity) { _impl.reserve(new_capacity); } + + void swap(vector_type& other) { _impl.swap(other); } + void swap(MixinVector& other) { _impl.swap(other._impl); } + + bool empty() const { return _impl.empty(); } + size_type size() const { return _impl.size(); } + size_type capacity() const { return _impl.capacity(); } + size_type max_size() const { return _impl.max_size(); } + allocator_type get_allocator() const { return _impl.get_allocator(); } + + const_iterator begin() const { return _impl.begin(); } + iterator begin() { return _impl.begin(); } + const_iterator end() const { return _impl.end(); } + iterator end() { return _impl.end(); } + + const_reverse_iterator rbegin() const { return _impl.rbegin(); } + reverse_iterator rbegin() { return _impl.rbegin(); } + const_reverse_iterator rend() const { return _impl.rend(); } + reverse_iterator rend() { return _impl.rend(); } + + const_reference operator[](size_type index) const { return _impl[index]; } + reference operator[](size_type index) { return _impl[index]; } + + const_reference at(size_type index) const { return _impl.at(index); } + reference at(size_type index) { return _impl.at(index); } + + void assign(size_type count, const value_type& value) { _impl.assign(count, value); } + template + void assign(Iter first, Iter last) { _impl.assign(first, last); } + + void push_back(const value_type& value) { _impl.push_back(value); } + void pop_back() { _impl.pop_back(); } + + iterator erase(iterator where) { return _impl.erase(where); } + iterator erase(iterator first, iterator last) { return _impl.erase(first, last); } + + iterator insert(iterator where, const value_type& value) { return _impl.insert(where, value); } + + template + void insert(iterator where, InputIterator first, InputIterator last) + { + _impl.insert(where, first, last); + } + + void insert(iterator where, size_type count, const value_type& value) + { + _impl.insert(where, count, value); + } + + const_reference back() const { return _impl.back(); } + reference back() { return _impl.back(); } + const_reference front() const { return _impl.front(); } + reference front() { return _impl.front(); } + + vector_type& asVector() { return _impl; } + const vector_type& asVector() const { return _impl; } + + friend inline bool operator==(const MixinVector& left, const MixinVector& right) { return left._impl == right._impl; } + friend inline bool operator==(const MixinVector& left, const std::vector& right) { return left._impl == right; } + friend inline bool operator==(const std::vector& left, const MixinVector& right) { return left == right._impl; } + + friend inline bool operator!=(const MixinVector& left, const MixinVector& right) { return left._impl != right._impl; } + friend inline bool operator!=(const MixinVector& left, const std::vector& right) { return left._impl != right; } + friend inline bool operator!=(const std::vector& left, const MixinVector& right) { return left != right._impl; } + + friend inline bool operator<(const MixinVector& left, const MixinVector& right) { return left._impl < right._impl; } + friend inline bool operator<(const MixinVector& left, const std::vector& right) { return left._impl < right; } + friend inline bool operator<(const std::vector& left, const MixinVector& right) { return left < right._impl; } + + friend inline bool operator>(const MixinVector& left, const MixinVector& right) { return left._impl > right._impl; } + friend inline bool operator>(const MixinVector& left, const std::vector& right) { return left._impl > right; } + friend inline bool operator>(const std::vector& left, const MixinVector& right) { return left > right._impl; } + + friend inline bool operator<=(const MixinVector& left, const MixinVector& right) { return left._impl <= right._impl; } + friend inline bool operator<=(const MixinVector& left, const std::vector& right) { return left._impl <= right; } + friend inline bool operator<=(const std::vector& left, const MixinVector& right) { return left <= right._impl; } + + friend inline bool operator>=(const MixinVector& left, const MixinVector& right) { return left._impl >= right._impl; } + friend inline bool operator>=(const MixinVector& left, const std::vector& right) { return left._impl >= right; } + friend inline bool operator>=(const std::vector& left, const MixinVector& right) { return left >= right._impl; } + +private: + vector_type _impl; +}; + +template inline +void +swap(MixinVector& left, + MixinVector& right) +{ + std::swap(left.asVector(), right.asVector()); +} + +template inline +void +swap(MixinVector& left, + std::vector& right) +{ + std::swap(left.asVector(), right); +} + +template inline +void +swap(std::vector& left, + MixinVector& right) +{ + std::swap(left, right.asVector()); +} + +} // namespace osg + +#endif + diff --git a/libs/include/android/osg/Multisample b/libs/include/android/osg/Multisample new file mode 100755 index 0000000..60477a9 --- /dev/null +++ b/libs/include/android/osg/Multisample @@ -0,0 +1,158 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_MULTISAMPLE +#define OSG_MULTISAMPLE 1 + + +#include +#include +#include + + +#ifndef GL_ARB_multisample +#define GL_MULTISAMPLE_ARB 0x809D +#define GL_SAMPLE_ALPHA_TO_COVERAGE_ARB 0x809E +#define GL_SAMPLE_ALPHA_TO_ONE_ARB 0x809F +#define GL_SAMPLE_COVERAGE_ARB 0x80A0 +#define GL_SAMPLE_BUFFERS_ARB 0x80A8 +#define GL_SAMPLES_ARB 0x80A9 +#define GL_SAMPLE_COVERAGE_VALUE_ARB 0x80AA +#define GL_SAMPLE_COVERAGE_INVERT_ARB 0x80AB +#define GL_MULTISAMPLE_BIT_ARB 0x20000000 +#endif +#ifndef GL_NV_multisample_filter_hint +#define GL_MULTISAMPLE_FILTER_HINT_NV 0x8534 +#endif + + +namespace osg { + +/** Multisample - encapsulates the OpenGL Multisample state.*/ +class OSG_EXPORT Multisample : public StateAttribute +{ + public : + + enum Mode + { + FASTEST = GL_FASTEST, + NICEST = GL_NICEST, + DONT_CARE = GL_DONT_CARE + }; + + Multisample(); + + /** Copy constructor using CopyOp to manage deep vs shallow copy.*/ + Multisample(const Multisample& trans,const CopyOp& copyop=CopyOp::SHALLOW_COPY): + StateAttribute(trans,copyop), + _coverage(trans._coverage), + _invert(trans._invert), + _mode(trans._mode) {} + + META_StateAttribute(osg, Multisample,MULTISAMPLE); + + /** return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs.*/ + virtual int compare(const StateAttribute& sa) const + { + // check the types are equal and then create the rhs variable + // used by the COMPARE_StateAttribute_Parameter macros below. + COMPARE_StateAttribute_Types(Multisample,sa) + + // compare each parameter in turn against the rhs. + COMPARE_StateAttribute_Parameter(_coverage) + COMPARE_StateAttribute_Parameter(_invert) + COMPARE_StateAttribute_Parameter(_mode) + + return 0; // passed all the above comparison macros, must be equal. + } + + void setSampleCoverage(float coverage, bool invert) + { + _coverage = coverage; + _invert = invert; + } + inline void setCoverage(float coverage) { _coverage=coverage; } + inline float getCoverage() const { return _coverage; } + + inline void setInvert(bool invert) { _invert=invert; } + inline bool getInvert() const { return _invert; } + + inline void setHint(Mode mode) { _mode = mode; } + inline Mode getHint() const { return _mode; } + + virtual void apply(State& state) const; + + + /** Extensions class which encapsulates the querying of extensions and + * associated function pointers, and provide convenience wrappers to + * check for the extensions or use the associated functions.*/ + class OSG_EXPORT Extensions : public osg::Referenced + { + public: + Extensions(unsigned int contextID); + + Extensions(const Extensions& rhs); + + void lowestCommonDenominator(const Extensions& rhs); + + void setupGLExtensions(unsigned int contextID); + + void setMultisampleSupported(bool flag) { _isMultisampleSupported=flag; } + void setMultisampleFilterHintSupported(bool flag) { _isMultisampleFilterHintSupported=flag; } + bool isMultisampleSupported() const { return _isMultisampleSupported; } + bool isMultisampleFilterHintSupported() const { return _isMultisampleFilterHintSupported; } + + void glSampleCoverage(GLclampf value, GLboolean invert) const; + + protected: + + ~Extensions() {} + + bool _isMultisampleSupported; + bool _isMultisampleFilterHintSupported; + + typedef void (GL_APIENTRY * GLSampleCoverageProc) (GLclampf value, GLboolean invert); + GLSampleCoverageProc _glSampleCoverage; + + }; + + /** Function to call to get the extension of a specified context. + * If the Extension object for that context has not yet been created + * and the 'createIfNotInitalized' flag been set to false then returns NULL. + * If 'createIfNotInitalized' is true then the Extensions object is + * automatically created. However, in this case the extension object will + * only be created with the graphics context associated with ContextID..*/ + static Extensions* getExtensions(unsigned int contextID,bool createIfNotInitalized); + + /** setExtensions allows users to override the extensions across graphics contexts. + * Typically used when you have different extensions supported across graphics pipes + * but need to ensure that they all use the same low common denominator extensions.*/ + static void setExtensions(unsigned int contextID,Extensions* extensions); + + + + protected : + + virtual ~Multisample(); + + float _coverage; + bool _invert; + Mode _mode; +}; + +} + +#endif + + + diff --git a/libs/include/android/osg/Node b/libs/include/android/osg/Node new file mode 100755 index 0000000..9e2d727 --- /dev/null +++ b/libs/include/android/osg/Node @@ -0,0 +1,490 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + + +#ifndef OSG_NODE +#define OSG_NODE 1 + +#include +#include +#include +#include + +#include +#include + + +// forward declare osgTerrrain::Terrain to enable declaration of asTerrain() method. +namespace osgTerrain { +class Terrain; +} + +namespace osg { + +// forcing declare classes to enable declaration of as*() methods. +class NodeVisitor; +class Group; +class Transform; +class Node; +class Switch; +class Geode; +class Camera; + +/** A vector of Nodes pointers which is used to describe the path from a root node to a descendant.*/ +typedef std::vector< Node* > NodePath; + +/** A vector of NodePath, typically used to describe all the paths from a node to the potential root nodes it has.*/ +typedef std::vector< NodePath > NodePathList; + +/** A vector of NodePath, typically used to describe all the paths from a node to the potential root nodes it has.*/ +typedef std::vector< Matrix > MatrixList; + +/** META_Node macro define the standard clone, isSameKindAs, className + * and accept methods. Use when subclassing from Node to make it + * more convenient to define the required pure virtual methods.*/ +#define META_Node(library,name) \ + virtual osg::Object* cloneType() const { return new name (); } \ + virtual osg::Object* clone(const osg::CopyOp& copyop) const { return new name (*this,copyop); } \ + virtual bool isSameKindAs(const osg::Object* obj) const { return dynamic_cast(obj)!=NULL; } \ + virtual const char* className() const { return #name; } \ + virtual const char* libraryName() const { return #library; } \ + virtual void accept(osg::NodeVisitor& nv) { if (nv.validNodeMask(*this)) { nv.pushOntoNodePath(this); nv.apply(*this); nv.popFromNodePath(); } } \ + + +/** Base class for all internal nodes in the scene graph. + Provides interface for most common node operations (Composite Pattern). +*/ +class OSG_EXPORT Node : public Object +{ + public: + + /** Construct a node. + Initialize the parent list to empty, node name to "" and + bounding sphere dirty flag to true.*/ + Node(); + + /** Copy constructor using CopyOp to manage deep vs shallow copy.*/ + Node(const Node&,const CopyOp& copyop=CopyOp::SHALLOW_COPY); + + /** clone an object of the same type as the node.*/ + virtual Object* cloneType() const { return new Node(); } + + /** return a clone of a node, with Object* return type.*/ + virtual Object* clone(const CopyOp& copyop) const { return new Node(*this,copyop); } + + /** return true if this and obj are of the same kind of object.*/ + virtual bool isSameKindAs(const Object* obj) const { return dynamic_cast(obj)!=NULL; } + + /** return the name of the node's library.*/ + virtual const char* libraryName() const { return "osg"; } + + /** return the name of the node's class type.*/ + virtual const char* className() const { return "Node"; } + + /** convert 'this' into a Group pointer if Node is a Group, otherwise return 0. + * Equivalent to dynamic_cast(this).*/ + virtual Group* asGroup() { return 0; } + /** convert 'const this' into a const Group pointer if Node is a Group, otherwise return 0. + * Equivalent to dynamic_cast(this).*/ + virtual const Group* asGroup() const { return 0; } + + /** Convert 'this' into a Transform pointer if Node is a Transform, otherwise return 0. + * Equivalent to dynamic_cast(this).*/ + virtual Transform* asTransform() { return 0; } + + /** convert 'const this' into a const Transform pointer if Node is a Transform, otherwise return 0. + * Equivalent to dynamic_cast(this).*/ + virtual const Transform* asTransform() const { return 0; } + + + /** Convert 'this' into a Camera pointer if Node is a Camera, otherwise return 0. + * Equivalent to dynamic_cast(this).*/ + virtual Camera* asCamera() { return 0; } + /** convert 'const this' into a const Camera pointer if Node is a Camera, otherwise return 0. + * Equivalent to dynamic_cast(this).*/ + virtual const Camera* asCamera() const { return 0; } + + + /** Convert 'this' into a Switch pointer if Node is a Switch, otherwise return 0. + * Equivalent to dynamic_cast(this).*/ + virtual Switch* asSwitch() { return 0; } + + /** convert 'const this' into a const Switch pointer if Node is a Switch, otherwise return 0. + * Equivalent to dynamic_cast(this).*/ + virtual const Switch* asSwitch() const { return 0; } + + /** Convert 'this' into a Geode pointer if Node is a Geode, otherwise return 0. + * Equivalent to dynamic_cast(this).*/ + virtual Geode* asGeode() { return 0; } + + /** convert 'const this' into a const Geode pointer if Node is a Geode, otherwise return 0. + * Equivalent to dynamic_cast(this).*/ + virtual const Geode* asGeode() const { return 0; } + + /** Convert 'this' into a Transform pointer if Node is a Terrain, otherwise return 0. + * Equivalent to dynamic_cast(this).*/ + virtual osgTerrain::Terrain* asTerrain() { return 0; } + + /** convert 'const this' into a const Terrain pointer if Node is a Terrain, otherwise return 0. + * Equivalent to dynamic_cast(this).*/ + virtual const osgTerrain::Terrain* asTerrain() const { return 0; } + + + /** Visitor Pattern : calls the apply method of a NodeVisitor with this node's type.*/ + virtual void accept(NodeVisitor& nv); + /** Traverse upwards : calls parents' accept method with NodeVisitor.*/ + virtual void ascend(NodeVisitor& nv); + /** Traverse downwards : calls children's accept method with NodeVisitor.*/ + virtual void traverse(NodeVisitor& /*nv*/) {} + + /** A vector of osg::Group pointers which is used to store the parent(s) of node.*/ + typedef std::vector ParentList; + + /** Get the parent list of node. */ + inline const ParentList& getParents() const { return _parents; } + + /** Get the a copy of parent list of node. A copy is returned to + * prevent modification of the parent list.*/ + inline ParentList getParents() { return _parents; } + + inline Group* getParent(unsigned int i) { return _parents[i]; } + + /** + * Get a single const parent of node. + * @param i index of the parent to get. + * @return the parent i. + */ + inline const Group* getParent(unsigned int i) const { return _parents[i]; } + + /** + * Get the number of parents of node. + * @return the number of parents of this node. + */ + inline unsigned int getNumParents() const { return static_cast(_parents.size()); } + + /** Get the list of node paths parent paths. + * The optional Node* haltTraversalAtNode allows the user to prevent traversal beyond a specifed node. */ + NodePathList getParentalNodePaths(osg::Node* haltTraversalAtNode=0) const; + + /** Get the list of matrices that transform this node from local coordinates to world coordinates. + * The optional Node* haltTraversalAtNode allows the user to prevent traversal beyond a specifed node. */ + MatrixList getWorldMatrices(const osg::Node* haltTraversalAtNode=0) const; + + + /** Set update node callback, called during update traversal. */ + void setUpdateCallback(NodeCallback* nc); + + /** Get update node callback, called during update traversal. */ + inline NodeCallback* getUpdateCallback() { return _updateCallback.get(); } + + /** Get const update node callback, called during update traversal. */ + inline const NodeCallback* getUpdateCallback() const { return _updateCallback.get(); } + + /** Convenience method that sets the update callback of the node if it doesn't exist, or nest it into the existing one. */ + inline void addUpdateCallback(NodeCallback* nc) { + if (nc != NULL) { + if (_updateCallback.valid()) _updateCallback->addNestedCallback(nc); + else setUpdateCallback(nc); + } + } + + /** Convenience method that removes a given callback from a node, even if that callback is nested. There is no error return in case the given callback is not found. */ + inline void removeUpdateCallback(NodeCallback* nc) { + if (nc != NULL && _updateCallback.valid()) { + if (_updateCallback == nc) + { + ref_ptr new_nested_callback = nc->getNestedCallback(); + nc->setNestedCallback(0); + setUpdateCallback(new_nested_callback.get()); + } + else _updateCallback->removeNestedCallback(nc); + } + } + + /** Get the number of Children of this node which require Update traversal, + * since they have an Update Callback attached to them or their children.*/ + inline unsigned int getNumChildrenRequiringUpdateTraversal() const { return _numChildrenRequiringUpdateTraversal; } + + + /** Set event node callback, called during event traversal. */ + void setEventCallback(NodeCallback* nc); + + /** Get event node callback, called during event traversal. */ + inline NodeCallback* getEventCallback() { return _eventCallback.get(); } + + /** Get const event node callback, called during event traversal. */ + inline const NodeCallback* getEventCallback() const { return _eventCallback.get(); } + + /** Convenience method that sets the event callback of the node if it doesn't exist, or nest it into the existing one. */ + inline void addEventCallback(NodeCallback* nc) { + if (nc != NULL) { + if (_eventCallback.valid()) _eventCallback->addNestedCallback(nc); + else setEventCallback(nc); + } + } + + /** Convenience method that removes a given callback from a node, even if that callback is nested. There is no error return in case the given callback is not found. */ + inline void removeEventCallback(NodeCallback* nc) { + if (nc != NULL && _eventCallback.valid()) { + if (_eventCallback == nc) + { + ref_ptr new_nested_callback = nc->getNestedCallback(); + nc->setNestedCallback(0); + setEventCallback(new_nested_callback.get()); // replace the callback by the nested one + } + else _eventCallback->removeNestedCallback(nc); + } + } + + /** Get the number of Children of this node which require Event traversal, + * since they have an Event Callback attached to them or their children.*/ + inline unsigned int getNumChildrenRequiringEventTraversal() const { return _numChildrenRequiringEventTraversal; } + + + /** Set cull node callback, called during cull traversal. */ + void setCullCallback(NodeCallback* nc) { _cullCallback = nc; } + + /** Get cull node callback, called during cull traversal. */ + inline NodeCallback* getCullCallback() { return _cullCallback.get(); } + + /** Get const cull node callback, called during cull traversal. */ + inline const NodeCallback* getCullCallback() const { return _cullCallback.get(); } + + /** Convenience method that sets the cull callback of the node if it doesn't exist, or nest it into the existing one. */ + inline void addCullCallback(NodeCallback* nc) { + if (nc != NULL) { + if (_cullCallback.valid()) _cullCallback->addNestedCallback(nc); + else setCullCallback(nc); + } + } + + /** Convenience method that removes a given callback from a node, even if that callback is nested. There is no error return in case the given callback is not found. */ + inline void removeCullCallback(NodeCallback* nc) { + if (nc != NULL && _cullCallback.valid()) { + if (_cullCallback == nc) + { + ref_ptr new_nested_callback = nc->getNestedCallback(); + nc->setNestedCallback(0); + setCullCallback(new_nested_callback.get()); // replace the callback by the nested one + } + else _cullCallback->removeNestedCallback(nc); + } + } + + /** Set the view frustum/small feature culling of this node to be active or inactive. + * The default value is true for _cullingActive. Used as a guide + * to the cull traversal.*/ + void setCullingActive(bool active); + + /** Get the view frustum/small feature _cullingActive flag for this node. Used as a guide + * to the cull traversal.*/ + inline bool getCullingActive() const { return _cullingActive; } + + /** Get the number of Children of this node which have culling disabled.*/ + inline unsigned int getNumChildrenWithCullingDisabled() const { return _numChildrenWithCullingDisabled; } + + /** Return true if this node can be culled by view frustum, occlusion or small feature culling during the cull traversal. + * Note, returns true only if no children have culling disabled, and the local _cullingActive flag is true.*/ + inline bool isCullingActive() const { return _numChildrenWithCullingDisabled==0 && _cullingActive && getBound().valid(); } + + /** Get the number of Children of this node which are or have OccluderNode's.*/ + inline unsigned int getNumChildrenWithOccluderNodes() const { return _numChildrenWithOccluderNodes; } + + + /** return true if this node is an OccluderNode or the subgraph below this node are OccluderNodes.*/ + bool containsOccluderNodes() const; + + + /** + * This is a set of bits (flags) that represent the Node. + * The default value is 0xffffffff (all bits set). + * + * The most common use of these is during traversal of the scene graph. + * For instance, when traversing the scene graph the osg::NodeVisitor does a bitwise + * AND of its TraversalMask with the Node's NodeMask to + * determine if the Node should be processed/traversed. + * + * For example, if a Node has a NodeMask value of 0x02 (only 2nd bit set) + * and the osg::Camera has a CullMask of 0x4 (2nd bit not set) then during cull traversal, + * which takes it's TraversalMask from the Camera's CullMask, the node and any children + * would be ignored and thereby treated as "culled" and thus not rendered. + * Conversely, if the osg::Camera CullMask were 0x3 (2nd bit set) then the node + * would be processed and child Nodes would be examined. + */ + typedef unsigned int NodeMask; + /** Set the node mask.*/ + inline void setNodeMask(NodeMask nm) { _nodeMask = nm; } + /** Get the node Mask.*/ + inline NodeMask getNodeMask() const { return _nodeMask; } + + + + /** Set the node's StateSet.*/ + void setStateSet(osg::StateSet* stateset); + + /** return the node's StateSet, if one does not already exist create it + * set the node and return the newly created StateSet. This ensures + * that a valid StateSet is always returned and can be used directly.*/ + osg::StateSet* getOrCreateStateSet(); + + /** Return the node's StateSet. returns NULL if a stateset is not attached.*/ + inline osg::StateSet* getStateSet() { return _stateset.get(); } + + /** Return the node's const StateSet. Returns NULL if a stateset is not attached.*/ + inline const osg::StateSet* getStateSet() const { return _stateset.get(); } + + + /** A vector of std::string's which are used to describe the object.*/ + typedef std::vector DescriptionList; + + /** Set the list of string descriptions.*/ + void setDescriptions(const DescriptionList& descriptions); + + /** Get the description list of the node.*/ + DescriptionList& getDescriptions(); + + /** Get the const description list of the const node.*/ + const DescriptionList& getDescriptions() const; + + + /** Get a single const description of the const node.*/ + const std::string& getDescription(unsigned int i) const; + + /** Get a single description of the node.*/ + std::string& getDescription(unsigned int i); + + /** Get the number of descriptions of the node.*/ + unsigned int getNumDescriptions() const; + + /** Add a description string to the node.*/ + void addDescription(const std::string& desc); + + + /** Set the initial bounding volume to use when computing the overall bounding volume.*/ + void setInitialBound(const osg::BoundingSphere& bsphere) { _initialBound = bsphere; dirtyBound(); } + + /** Set the initial bounding volume to use when computing the overall bounding volume.*/ + const BoundingSphere& getInitialBound() const { return _initialBound; } + + /** Mark this node's bounding sphere dirty. + Forcing it to be computed on the next call to getBound().*/ + void dirtyBound(); + + /** Get the bounding sphere of node. + Using lazy evaluation computes the bounding sphere if it is 'dirty'.*/ + inline const BoundingSphere& getBound() const + { + if(!_boundingSphereComputed) + { + _boundingSphere = _initialBound; + if (_computeBoundCallback.valid()) + _boundingSphere.expandBy(_computeBoundCallback->computeBound(*this)); + else + _boundingSphere.expandBy(computeBound()); + + _boundingSphereComputed = true; + } + return _boundingSphere; + } + + + /** Compute the bounding sphere around Node's geometry or children. + This method is automatically called by getBound() when the bounding + sphere has been marked dirty via dirtyBound().*/ + virtual BoundingSphere computeBound() const; + + /** Callback to allow users to override the default computation of bounding volume.*/ + struct ComputeBoundingSphereCallback : public osg::Object + { + ComputeBoundingSphereCallback() {} + + ComputeBoundingSphereCallback(const ComputeBoundingSphereCallback&,const CopyOp&) {} + + META_Object(osg,ComputeBoundingSphereCallback); + + virtual BoundingSphere computeBound(const osg::Node&) const { return BoundingSphere(); } + }; + + /** Set the compute bound callback to override the default computeBound.*/ + void setComputeBoundingSphereCallback(ComputeBoundingSphereCallback* callback) { _computeBoundCallback = callback; } + + /** Get the compute bound callback.*/ + ComputeBoundingSphereCallback* getComputeBoundingSphereCallback() { return _computeBoundCallback.get(); } + + /** Get the const compute bound callback.*/ + const ComputeBoundingSphereCallback* getComputeBoundingSphereCallback() const { return _computeBoundCallback.get(); } + + /** Set whether to use a mutex to ensure ref() and unref() are thread safe.*/ + virtual void setThreadSafeRefUnref(bool threadSafe); + + /** Resize any per context GLObject buffers to specified size. */ + virtual void resizeGLObjectBuffers(unsigned int /*maxSize*/); + + /** If State is non-zero, this function releases any associated OpenGL objects for + * the specified graphics context. Otherwise, releases OpenGL objects + * for all graphics contexts. */ + virtual void releaseGLObjects(osg::State* = 0) const; + + + protected: + + /** Node destructor. Note, is protected so that Nodes cannot + be deleted other than by being dereferenced and the reference + count being zero (see osg::Referenced), preventing the deletion + of nodes which are still in use. This also means that + Nodes cannot be created on stack i.e Node node will not compile, + forcing all nodes to be created on the heap i.e Node* node + = new Node().*/ + virtual ~Node(); + + + + BoundingSphere _initialBound; + ref_ptr _computeBoundCallback; + mutable BoundingSphere _boundingSphere; + mutable bool _boundingSphereComputed; + + void addParent(osg::Group* node); + void removeParent(osg::Group* node); + + ParentList _parents; + friend class osg::Group; + friend class osg::Drawable; + friend class osg::StateSet; + + ref_ptr _updateCallback; + unsigned int _numChildrenRequiringUpdateTraversal; + void setNumChildrenRequiringUpdateTraversal(unsigned int num); + + ref_ptr _eventCallback; + unsigned int _numChildrenRequiringEventTraversal; + void setNumChildrenRequiringEventTraversal(unsigned int num); + + ref_ptr _cullCallback; + + bool _cullingActive; + unsigned int _numChildrenWithCullingDisabled; + void setNumChildrenWithCullingDisabled(unsigned int num); + + unsigned int _numChildrenWithOccluderNodes; + void setNumChildrenWithOccluderNodes(unsigned int num); + + NodeMask _nodeMask; + + ref_ptr _stateset; + +}; + +} + +#endif diff --git a/libs/include/android/osg/NodeCallback b/libs/include/android/osg/NodeCallback new file mode 100755 index 0000000..4676746 --- /dev/null +++ b/libs/include/android/osg/NodeCallback @@ -0,0 +1,99 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_NODECALLBACK +#define OSG_NODECALLBACK 1 + +#include +#include + +namespace osg { + +class Node; +class NodeVisitor; + +class OSG_EXPORT NodeCallback : public virtual Object { + + public : + + + NodeCallback(){} + + NodeCallback(const NodeCallback& nc,const CopyOp&): + _nestedCallback(nc._nestedCallback) {} + + + META_Object(osg,NodeCallback); + + + /** Callback method called by the NodeVisitor when visiting a node.*/ + virtual void operator()(Node* node, NodeVisitor* nv) + { + // note, callback is responsible for scenegraph traversal so + // they must call traverse(node,nv) to ensure that the + // scene graph subtree (and associated callbacks) are traversed. + traverse(node,nv); + } + + /** Call any nested callbacks and then traverse the scene graph. */ + void traverse(Node* node,NodeVisitor* nv); + + void setNestedCallback(NodeCallback* nc) { _nestedCallback = nc; } + NodeCallback* getNestedCallback() { return _nestedCallback.get(); } + const NodeCallback* getNestedCallback() const { return _nestedCallback.get(); } + + inline void addNestedCallback(NodeCallback* nc) + { + if (nc) + { + if (_nestedCallback.valid()) + { + _nestedCallback->addNestedCallback(nc); + } + else + { + _nestedCallback = nc; + } + } + } + + inline void removeNestedCallback(NodeCallback* nc) + { + if (nc) + { + if (_nestedCallback==nc) + { + ref_ptr new_nested_callback = _nestedCallback->getNestedCallback(); + _nestedCallback->setNestedCallback(0); + _nestedCallback = new_nested_callback; + } + else if (_nestedCallback.valid()) + { + _nestedCallback->removeNestedCallback(nc); + } + } + } + + public: + + ref_ptr _nestedCallback; + + protected: + + virtual ~NodeCallback() {} +}; + +} // namespace + +#endif + diff --git a/libs/include/android/osg/NodeTrackerCallback b/libs/include/android/osg/NodeTrackerCallback new file mode 100755 index 0000000..ed35229 --- /dev/null +++ b/libs/include/android/osg/NodeTrackerCallback @@ -0,0 +1,54 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_NODETRACKERCALLBACK +#define OSG_NODETRACKERCALLBACK 1 + +#include + +#include +#include +#include + +namespace osg +{ + +class OSG_EXPORT NodeTrackerCallback : public NodeCallback +{ + public: + + void setTrackNodePath(const osg::NodePath& nodePath) { _trackNodePath.setNodePath(nodePath); } + + void setTrackNodePath(const ObserverNodePath& nodePath) { _trackNodePath = nodePath; } + + ObserverNodePath& getTrackNodePath() { return _trackNodePath; } + + void setTrackNode(osg::Node* node); + osg::Node* getTrackNode(); + const osg::Node* getTrackNode() const; + + /** Implements the callback. */ + virtual void operator()(Node* node, NodeVisitor* nv); + + /** Update the node to track the nodepath.*/ + void update(osg::Node& node); + + protected: + + ObserverNodePath _trackNodePath; + +}; + +} + +#endif diff --git a/libs/include/android/osg/NodeVisitor b/libs/include/android/osg/NodeVisitor new file mode 100755 index 0000000..d0b7e8f --- /dev/null +++ b/libs/include/android/osg/NodeVisitor @@ -0,0 +1,369 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_NODEVISITOR +#define OSG_NODEVISITOR 1 + +#include +#include +#include + +namespace osg { + +class Billboard; +class ClearNode; +class ClipNode; +class CoordinateSystemNode; +class Geode; +class Group; +class LightSource; +class LOD; +class MatrixTransform; +class OccluderNode; +class OcclusionQueryNode; +class PagedLOD; +class PositionAttitudeTransform; +class Projection; +class ProxyNode; +class Sequence; +class Switch; +class TexGenNode; +class Transform; +class Camera; +class CameraView; + +const unsigned int UNINITIALIZED_FRAME_NUMBER=0xffffffff; + +#define META_NodeVisitor(library, name) \ + virtual const char* libraryName() const { return #library; }\ + virtual const char* className() const { return #name; } + +/** Visitor for type safe operations on osg::Nodes. + Based on GOF's Visitor pattern. The NodeVisitor + is useful for developing type safe operations to nodes + in the scene graph (as per Visitor pattern), and adds to this + support for optional scene graph traversal to allow + operations to be applied to whole scenes at once. The Visitor + pattern uses a technique of double dispatch as a mechanism to + call the appropriate apply(..) method of the NodeVisitor. To + use this feature one must use the Node::accept(NodeVisitor) which + is extended in each Node subclass, rather than the NodeVisitor + apply directly. So use root->accept(myVisitor); instead of + myVisitor.apply(*root). The later method will bypass the double + dispatch and the appropriate NodeVisitor::apply(..) method will + not be called. */ +class OSG_EXPORT NodeVisitor : public virtual Referenced +{ + public: + + enum TraversalMode + { + TRAVERSE_NONE, + TRAVERSE_PARENTS, + TRAVERSE_ALL_CHILDREN, + TRAVERSE_ACTIVE_CHILDREN + }; + + enum VisitorType + { + NODE_VISITOR = 0, + UPDATE_VISITOR, + EVENT_VISITOR, + COLLECT_OCCLUDER_VISITOR, + CULL_VISITOR + }; + + NodeVisitor(TraversalMode tm=TRAVERSE_NONE); + + NodeVisitor(VisitorType type,TraversalMode tm=TRAVERSE_NONE); + + virtual ~NodeVisitor(); + + /** return the library name/namespapce of the visitor's. Should be defined by derived classes.*/ + virtual const char* libraryName() const { return "osg"; } + + /** return the name of the visitor's class type. Should be defined by derived classes.*/ + virtual const char* className() const { return "NodeVisitor"; } + + /** Method to call to reset visitor. Useful if your visitor accumulates + state during a traversal, and you plan to reuse the visitor. + To flush that state for the next traversal: call reset() prior + to each traversal.*/ + virtual void reset() {} + + + /** Set the VisitorType, used to distinguish different visitors during + * traversal of the scene, typically used in the Node::traverse() method + * to select which behaviour to use for different types of traversal/visitors.*/ + inline void setVisitorType(VisitorType type) { _visitorType = type; } + + /** Get the VisitorType.*/ + inline VisitorType getVisitorType() const { return _visitorType; } + + /** Set the traversal number. Typically used to denote the frame count.*/ + inline void setTraversalNumber(unsigned int fn) { _traversalNumber = fn; } + + /** Get the traversal number. Typically used to denote the frame count.*/ + inline unsigned int getTraversalNumber() const { return _traversalNumber; } + + /** Set the FrameStamp that this traversal is associated with.*/ + inline void setFrameStamp(FrameStamp* fs) { _frameStamp = fs; } + + /** Get the FrameStamp that this traversal is associated with.*/ + inline const FrameStamp* getFrameStamp() const { return _frameStamp.get(); } + + + /** Set the TraversalMask of this NodeVisitor. + * The TraversalMask is used by the NodeVisitor::validNodeMask() method + * to determine whether to operate on a node and its subgraph. + * validNodeMask() is called automatically in the Node::accept() method before + * any call to NodeVisitor::apply(), apply() is only ever called if validNodeMask + * returns true. Note, if NodeVisitor::_traversalMask is 0 then all operations + * will be switched off for all nodes. Whereas setting both _traversalMask and + * _nodeMaskOverride to 0xffffffff will allow a visitor to work on all nodes + * regardless of their own Node::_nodeMask state.*/ + inline void setTraversalMask(Node::NodeMask mask) { _traversalMask = mask; } + + /** Get the TraversalMask.*/ + inline Node::NodeMask getTraversalMask() const { return _traversalMask; } + + /** Set the NodeMaskOverride mask. + * Used in validNodeMask() to determine whether to operate on a node or its + * subgraph, by OR'ing NodeVisitor::_nodeMaskOverride with the Node's own Node::_nodeMask. + * Typically used to force on nodes which may have + * been switched off by their own Node::_nodeMask.*/ + inline void setNodeMaskOverride(Node::NodeMask mask) { _nodeMaskOverride = mask; } + + /** Get the NodeMaskOverride mask.*/ + inline Node::NodeMask getNodeMaskOverride() const { return _nodeMaskOverride; } + + /** Method to called by Node and its subclass' Node::accept() method, if the result is true + * it is used to cull operations of nodes and their subgraphs. + * Return true if the result of a bit wise and of the NodeVisitor::_traversalMask + * with the bit or between NodeVistor::_nodeMaskOverride and the Node::_nodeMask. + * default values for _traversalMask is 0xffffffff, _nodeMaskOverride is 0x0, + * and osg::Node::_nodeMask is 0xffffffff. */ + inline bool validNodeMask(const osg::Node& node) const + { + return (getTraversalMask() & (getNodeMaskOverride() | node.getNodeMask()))!=0; + } + + /** Set the traversal mode for Node::traverse() to use when + deciding which children of a node to traverse. If a + NodeVisitor has been attached via setTraverseVisitor() + and the new mode is not TRAVERSE_VISITOR then the attached + visitor is detached. Default mode is TRAVERSE_NONE.*/ + inline void setTraversalMode(TraversalMode mode) { _traversalMode = mode; } + + /** Get the traversal mode.*/ + inline TraversalMode getTraversalMode() const { return _traversalMode; } + + /** + * Set user data, data must be subclassed from Referenced to allow + * automatic memory handling. If your own data isn't directly + * subclassed from Referenced then create an adapter object + * which points to your own objects and handles the memory addressing. + */ + inline void setUserData(Referenced* obj) { _userData = obj; } + + /** Get user data.*/ + inline Referenced* getUserData() { return _userData.get(); } + + /** Get const user data.*/ + inline const Referenced* getUserData() const { return _userData.get(); } + + + /** Method for handling traversal of a nodes. + If you intend to use the visitor for actively traversing + the scene graph then make sure the accept() methods call + this method unless they handle traversal directly.*/ + inline void traverse(Node& node) + { + if (_traversalMode==TRAVERSE_PARENTS) node.ascend(*this); + else if (_traversalMode!=TRAVERSE_NONE) node.traverse(*this); + } + + /** Method called by osg::Node::accept() method before + * a call to the NodeVisitor::apply(..). The back of the list will, + * therefore, be the current node being visited inside the apply(..), + * and the rest of the list will be the parental sequence of nodes + * from the top most node applied down the graph to the current node. + * Note, the user does not typically call pushNodeOnPath() as it + * will be called automatically by the Node::accept() method.*/ + inline void pushOntoNodePath(Node* node) { if (_traversalMode!=TRAVERSE_PARENTS) _nodePath.push_back(node); else _nodePath.insert(_nodePath.begin(),node); } + + /** Method called by osg::Node::accept() method after + * a call to NodeVisitor::apply(..). + * Note, the user does not typically call popFromNodePath() as it + * will be called automatically by the Node::accept() method.*/ + inline void popFromNodePath() { if (_traversalMode!=TRAVERSE_PARENTS) _nodePath.pop_back(); else _nodePath.erase(_nodePath.begin()); } + + /** Get the non const NodePath from the top most node applied down + * to the current Node being visited.*/ + NodePath& getNodePath() { return _nodePath; } + + /** Get the const NodePath from the top most node applied down + * to the current Node being visited.*/ + const NodePath& getNodePath() const { return _nodePath; } + + /** Get the eye point in local coordinates. + * Note, not all NodeVisitor implement this method, it is mainly cull visitors which will implement.*/ + virtual osg::Vec3 getEyePoint() const { return Vec3(0.0f,0.0f,0.0f); } + + /** Get the view point in local coordinates. + * Note, not all NodeVisitor implement this method, it is mainly cull visitors which will implement.*/ + virtual osg::Vec3 getViewPoint() const { return getEyePoint(); } + + /** Get the distance from a point to the eye point, distance value in local coordinate system. + * Note, not all NodeVisitor implement this method, it is mainly cull visitors which will implement. + * If the getDistanceFromEyePoint(pos) is not implemented then a default value of 0.0 is returned.*/ + virtual float getDistanceToEyePoint(const Vec3& /*pos*/, bool /*useLODScale*/) const { return 0.0f; } + + /** Get the distance of a point from the eye point, distance value in the eye coordinate system. + * Note, not all NodeVisitor implement this method, it is mainly cull visitors which will implement. + * If the getDistanceFromEyePoint(pos) is not implemented than a default value of 0.0 is returned.*/ + virtual float getDistanceFromEyePoint(const Vec3& /*pos*/, bool /*useLODScale*/) const { return 0.0f; } + + /** Get the distance from a point to the view point, distance value in local coordinate system. + * Note, not all NodeVisitor implement this method, it is mainly cull visitors which will implement. + * If the getDistanceToViewPoint(pos) is not implemented then a default value of 0.0 is returned.*/ + virtual float getDistanceToViewPoint(const Vec3& /*pos*/, bool /*useLODScale*/) const { return 0.0f; } + + + virtual void apply(Node& node); + + virtual void apply(Geode& node); + virtual void apply(Billboard& node); + + virtual void apply(Group& node); + + virtual void apply(ProxyNode& node); + + virtual void apply(Projection& node); + + virtual void apply(CoordinateSystemNode& node); + + virtual void apply(ClipNode& node); + virtual void apply(TexGenNode& node); + virtual void apply(LightSource& node); + + virtual void apply(Transform& node); + virtual void apply(Camera& node); + virtual void apply(CameraView& node); + virtual void apply(MatrixTransform& node); + virtual void apply(PositionAttitudeTransform& node); + + virtual void apply(Switch& node); + virtual void apply(Sequence& node); + virtual void apply(LOD& node); + virtual void apply(PagedLOD& node); + virtual void apply(ClearNode& node); + virtual void apply(OccluderNode& node); + virtual void apply(OcclusionQueryNode& node); + + + /** Callback for managing database paging, such as generated by PagedLOD nodes.*/ + class DatabaseRequestHandler : public osg::Referenced + { + public: + + DatabaseRequestHandler(): + Referenced(true) {} + + virtual void requestNodeFile(const std::string& fileName, osg::NodePath& nodePath, float priority, const FrameStamp* framestamp, osg::ref_ptr& databaseRequest, const osg::Referenced* options=0) = 0; + + protected: + virtual ~DatabaseRequestHandler() {} + }; + + /** Set the handler for database requests.*/ + void setDatabaseRequestHandler(DatabaseRequestHandler* handler) { _databaseRequestHandler = handler; } + + /** Get the handler for database requests.*/ + DatabaseRequestHandler* getDatabaseRequestHandler() { return _databaseRequestHandler.get(); } + + /** Get the const handler for database requests.*/ + const DatabaseRequestHandler* getDatabaseRequestHandler() const { return _databaseRequestHandler.get(); } + + + /** Callback for managing image paging, such as generated by PagedLOD nodes.*/ + class ImageRequestHandler : public osg::Referenced + { + public: + + ImageRequestHandler(): + Referenced(true) {} + + virtual double getPreLoadTime() const = 0; + + virtual osg::Image* readImageFile(const std::string& fileName, const osg::Referenced* options=0) = 0; + + virtual void requestImageFile(const std::string& fileName,osg::Object* attachmentPoint, int attachmentIndex, double timeToMergeBy, const FrameStamp* framestamp, osg::ref_ptr& imageRequest, const osg::Referenced* options=0) = 0; + + protected: + virtual ~ImageRequestHandler() {} + }; + + /** Set the handler for image requests.*/ + void setImageRequestHandler(ImageRequestHandler* handler) { _imageRequestHandler = handler; } + + /** Get the handler for image requests.*/ + ImageRequestHandler* getImageRequestHandler() { return _imageRequestHandler.get(); } + + /** Get the const handler for image requests.*/ + const ImageRequestHandler* getImageRequestHandler() const { return _imageRequestHandler.get(); } + + + + protected: + + VisitorType _visitorType; + unsigned int _traversalNumber; + + ref_ptr _frameStamp; + + TraversalMode _traversalMode; + Node::NodeMask _traversalMask; + Node::NodeMask _nodeMaskOverride; + + NodePath _nodePath; + + ref_ptr _userData; + + ref_ptr _databaseRequestHandler; + ref_ptr _imageRequestHandler; + +}; + + +/** Convenience functor for assisting visiting of arrays of osg::Node's.*/ +class NodeAcceptOp +{ + public: + + NodeAcceptOp(NodeVisitor& nv):_nv(nv) {} + NodeAcceptOp(const NodeAcceptOp& naop):_nv(naop._nv) {} + + void operator () (Node* node) { node->accept(_nv); } + void operator () (ref_ptr node) { node->accept(_nv); } + + protected: + + NodeAcceptOp& operator = (const NodeAcceptOp&) { return *this; } + + NodeVisitor& _nv; +}; + +} + +#endif diff --git a/libs/include/android/osg/Notify b/libs/include/android/osg/Notify new file mode 100755 index 0000000..9e21a86 --- /dev/null +++ b/libs/include/android/osg/Notify @@ -0,0 +1,145 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_NOTIFY_H +#define OSG_NOTIFY_H 1 + +#include +#include // for NotifyHandler + +#include + +namespace osg { + +/** Range of notify levels from DEBUG_FP through to FATAL, ALWAYS + * is reserved for forcing the absorption of all messages. The + * keywords are also used verbatim when specified by the environmental + * variable OSGNOTIFYLEVEL or OSG_NOTIFY_LEVEL. + * See documentation on osg::notify() for further details. + */ +enum NotifySeverity { + ALWAYS=0, + FATAL=1, + WARN=2, + NOTICE=3, + INFO=4, + DEBUG_INFO=5, + DEBUG_FP=6 +}; + +/** set the notify level, overriding the default or the value set by + * the environmental variable OSGNOTIFYLEVEL or OSG_NOTIFY_LEVEL. + */ +extern OSG_EXPORT void setNotifyLevel(NotifySeverity severity); + +/** get the notify level. */ +extern OSG_EXPORT NotifySeverity getNotifyLevel(); + +/** initialize notify level. */ +extern OSG_EXPORT bool initNotifyLevel(); + +#ifdef OSG_NOTIFY_DISABLED + inline bool isNotifyEnabled(NotifySeverity) { return false; } +#else + /** is notification enabled, given the current setNotifyLevel() setting? */ + extern OSG_EXPORT bool isNotifyEnabled(NotifySeverity severity); +#endif + +/** notify messaging function for providing fatal through to verbose + * debugging messages. Level of messages sent to the console can + * be controlled by setting the NotifyLevel either within your + * application or via the an environmental variable i.e. + * - setenv OSGNOTIFYLEVEL DEBUG (for tsh) + * - export OSGNOTIFYLEVEL=DEBUG (for bourne shell) + * - set OSGNOTIFYLEVEL=DEBUG (for Windows) + * + * All tell the osg to redirect all debugging and more important messages + * to the notification stream (useful for debugging) setting ALWAYS will force + * all messages to be absorbed, which might be appropriate for final + * applications. Default NotifyLevel is NOTICE. Check the enum + * #NotifySeverity for full range of possibilities. To use the notify + * with your code simply use the notify function as a normal file + * stream (like std::cout) i.e + * @code + * osg::notify(osg::DEBUG) << "Hello Bugs!" << std::endl; + * @endcode + * @see setNotifyLevel, setNotifyHandler + */ +extern OSG_EXPORT std::ostream& notify(const NotifySeverity severity); + +inline std::ostream& notify(void) { return notify(osg::INFO); } + +#define OSG_NOTIFY(level) if (osg::isNotifyEnabled(level)) osg::notify(level) +#define OSG_ALWAYS OSG_NOTIFY(osg::ALWAYS) +#define OSG_FATAL OSG_NOTIFY(osg::FATAL) +#define OSG_WARN OSG_NOTIFY(osg::WARN) +#define OSG_NOTICE OSG_NOTIFY(osg::NOTICE) +#define OSG_INFO OSG_NOTIFY(osg::INFO) +#define OSG_DEBUG OSG_NOTIFY(osg::DEBUG_INFO) +#define OSG_DEBUG_FP OSG_NOTIFY(osg::DEBUG_FP) + +/** Handler processing output of notification stream. It acts as a sink to + * notification messages. It is called when notification stream needs to be + * synchronized (i.e. after osg::notify() << std::endl). + * StandardNotifyHandler is used by default, it writes notifications to stderr + * (severity <= WARN) or stdout (severity > WARN). + * Notifications can be redirected to other sinks such as GUI widgets or + * windows debugger (WinDebugNotifyHandler) with custom handlers. + * Use setNotifyHandler to set custom handler. + * Note that osg notification API is not thread safe although notification + * handler is called from many threads. When incorporating handlers into GUI + * widgets you must take care of thread safety on your own. + * @see setNotifyHandler + */ +class OSG_EXPORT NotifyHandler : public osg::Referenced +{ +public: + virtual void notify(osg::NotifySeverity severity, const char *message) = 0; +}; + +/** Set notification handler, by default StandardNotifyHandler is used. + * @see NotifyHandler + */ +extern OSG_EXPORT void setNotifyHandler(NotifyHandler *handler); + +/** Get currrent notification handler. */ +extern OSG_EXPORT NotifyHandler *getNotifyHandler(); + +/** Redirects notification stream to stderr (severity <= WARN) or stdout (severity > WARN). + * The fputs() function is used to write messages to standard files. Note that + * std::out and std::cerr streams are not used. + * @see setNotifyHandler + */ +class OSG_EXPORT StandardNotifyHandler : public NotifyHandler +{ +public: + void notify(osg::NotifySeverity severity, const char *message); +}; + +#if defined(WIN32) && !defined(__CYGWIN__) + +/** Redirects notification stream to windows debugger with use of + * OuputDebugString functions. + * @see setNotifyHandler + */ +class OSG_EXPORT WinDebugNotifyHandler : public NotifyHandler +{ +public: + void notify(osg::NotifySeverity severity, const char *message); +}; + +#endif + +} + +#endif diff --git a/libs/include/android/osg/Object b/libs/include/android/osg/Object new file mode 100755 index 0000000..7a4e706 --- /dev/null +++ b/libs/include/android/osg/Object @@ -0,0 +1,270 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_OBJECT +#define OSG_OBJECT 1 + +#include +#include +#include +#include + +#include +#include + +namespace osg { + +// forward declare +class State; +class UserDataContainer; + +#define _ADDQUOTES(def) #def +#define ADDQUOTES(def) _ADDQUOTES(def) + +/** META_Object macro define the standard clone, isSameKindAs and className methods. + * Use when subclassing from Object to make it more convenient to define + * the standard pure virtual clone, isSameKindAs and className methods + * which are required for all Object subclasses.*/ +#define META_Object(library,name) \ + virtual osg::Object* cloneType() const { return new name (); } \ + virtual osg::Object* clone(const osg::CopyOp& copyop) const { return new name (*this,copyop); } \ + virtual bool isSameKindAs(const osg::Object* obj) const { return dynamic_cast(obj)!=NULL; } \ + virtual const char* libraryName() const { return #library; }\ + virtual const char* className() const { return #name; } + +/** Helper macro that creates a static proxy object to call singleton function on it's construction, ensuring that the singleton gets initialized at startup.*/ +#define OSG_INIT_SINGLETON_PROXY(ProxyName, Func) static struct ProxyName{ ProxyName() { Func; } } s_##ProxyName; + +/** Base class/standard interface for objects which require IO support, + cloning and reference counting. + Based on GOF Composite, Prototype and Template Method patterns. +*/ +class OSG_EXPORT Object : public Referenced +{ + public: + + + /** Construct an object. Note Object is a pure virtual base class + and therefore cannot be constructed on its own, only derived + classes which override the clone and className methods are + concrete classes and can be constructed.*/ + inline Object():Referenced(),_dataVariance(UNSPECIFIED), _userDataContainer(0) {} + + inline explicit Object(bool threadSafeRefUnref):Referenced(threadSafeRefUnref),_dataVariance(UNSPECIFIED),_userDataContainer(0) {} + + /** Copy constructor, optional CopyOp object can be used to control + * shallow vs deep copying of dynamic data.*/ + Object(const Object&,const CopyOp& copyop=CopyOp::SHALLOW_COPY); + + /** Clone the type of an object, with Object* return type. + Must be defined by derived classes.*/ + virtual Object* cloneType() const = 0; + + /** Clone an object, with Object* return type. + Must be defined by derived classes.*/ + virtual Object* clone(const CopyOp&) const = 0; + + virtual bool isSameKindAs(const Object*) const { return true; } + + /** return the name of the object's library. Must be defined + by derived classes. The OpenSceneGraph convention is that the + namespace of a library is the same as the library name.*/ + virtual const char* libraryName() const = 0; + + /** return the name of the object's class type. Must be defined + by derived classes.*/ + virtual const char* className() const = 0; + + + /** Set whether to use a mutex to ensure ref() and unref() are thread safe.*/ + virtual void setThreadSafeRefUnref(bool threadSafe); + + /** Set the name of object using C++ style string.*/ + virtual void setName( const std::string& name ) { _name = name; } + + /** Set the name of object using a C style string.*/ + inline void setName( const char* name ) + { + if (name) setName(std::string(name)); + else setName(std::string()); + } + + /** Get the name of object.*/ + inline const std::string& getName() const { return _name; } + + + enum DataVariance + { + DYNAMIC, + STATIC, + UNSPECIFIED + }; + + /** Set the data variance of this object. + * Can be set to either STATIC for values that do not change over the lifetime of the object, + * or DYNAMIC for values that vary over the lifetime of the object. The DataVariance value + * can be used by routines such as optimization codes that wish to share static data. + * UNSPECIFIED is used to specify that the DataVariance hasn't been set yet. */ + inline void setDataVariance(DataVariance dv) { _dataVariance = dv; } + + /** Get the data variance of this object.*/ + inline DataVariance getDataVariance() const { return _dataVariance; } + + /** Compute the DataVariance based on an assessment of callback etc.*/ + virtual void computeDataVariance() {} + + + /** set the UserDataContainer object.*/ + void setUserDataContainer(osg::UserDataContainer* udc); + + /** get the UserDataContainer attached to this object.*/ + osg::UserDataContainer* getUserDataContainer() { return _userDataContainer; } + + /** get the const UserDataContainer attached to this object.*/ + const osg::UserDataContainer* getUserDataContainer() const { return _userDataContainer; } + + /** Convinience method that returns the UserDataContainer, and if one doesn't already exist creates and assigns + * a DefaultUserDataContainer to the Object and then return this new UserDataContainer.*/ + osg::UserDataContainer* getOrCreateUserDataContainer(); + + + /** + * Set user data, data must be subclassed from Referenced to allow + * automatic memory handling. If your own data isn't directly + * subclassed from Referenced then create an adapter object + * which points to your own object and handles the memory addressing. + */ + virtual void setUserData(Referenced* obj); + + /** Get user data.*/ + virtual Referenced* getUserData(); + + /** Get const user data.*/ + virtual const Referenced* getUserData() const; + + + + /** Convinience method that casts the named UserObject to osg::TemplateValueObject and gets the value. + * To use this template method you need to include the osg/ValueObject header.*/ + template + bool getUserValue(const std::string& name, T& value) const; + + /** Convinience method that creates the osg::TemplateValueObject to store the + * specified value and adds it as a named UserObject. + * To use this template method you need to include the osg/ValueObject header. */ + template + void setUserValue(const std::string& name, const T& value); + + + /** Resize any per context GLObject buffers to specified size. */ + virtual void resizeGLObjectBuffers(unsigned int /*maxSize*/) {} + + /** If State is non-zero, this function releases any associated OpenGL objects for + * the specified graphics context. Otherwise, releases OpenGL objects + * for all graphics contexts. */ + virtual void releaseGLObjects(osg::State* = 0) const {} + + + protected: + + /** Object destructor. Note, is protected so that Objects cannot + be deleted other than by being dereferenced and the reference + count being zero (see osg::Referenced), preventing the deletion + of nodes which are still in use. This also means that + Nodes cannot be created on stack i.e Node node will not compile, + forcing all nodes to be created on the heap i.e Node* node + = new Node().*/ + virtual ~Object(); + + std::string _name; + DataVariance _dataVariance; + + osg::UserDataContainer* _userDataContainer; + + private: + + /** disallow any copy operator.*/ + Object& operator = (const Object&) { return *this; } +}; + +template +T* clone(const T* t, const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY) +{ + if (t) + { + osg::ref_ptr obj = t->clone(copyop); + + T* ptr = dynamic_cast(obj.get()); + if (ptr) + { + obj.release(); + return ptr; + } + else + { + OSG_WARN<<"Warning: osg::clone(const T*, osg::CopyOp&) cloned object not of type T, returning NULL."< +T* clone(const T* t, const std::string& name, const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY) +{ + T* newObject = osg::clone(t, copyop); + if (newObject) + { + newObject->setName(name); + return newObject; + } + else + { + OSG_WARN<<"Warning: osg::clone(const T*, const std::string&, const osg::CopyOp) passed null object to clone, returning NULL."< +T* cloneType(const T* t) +{ + if (t) + { + osg::ref_ptr obj = t->cloneType(); + + T* ptr = dynamic_cast(obj.get()); + if (ptr) + { + obj.release(); + return ptr; + } + else + { + OSG_WARN<<"Warning: osg::cloneType(const T*) cloned object not of type T, returning NULL."< +#include +#include + +namespace osg { + +/** Observer base class for tracking when objects are unreferenced (their reference count goes to 0) and are being deleted.*/ +class OSG_EXPORT Observer +{ + public: + Observer(); + virtual ~Observer(); + + /** objectDeleted is called when the observed object is about to be deleted. The observer will be automatically + * removed from the observed object's observer set so there is no need for the objectDeleted implementation + * to call removeObserver() on the observed object. */ + virtual void objectDeleted(void*) {} + +}; + +/** Class used by osg::Referenced to track the observers associated with it.*/ +class OSG_EXPORT ObserverSet : public osg::Referenced +{ + public: + + ObserverSet(const Referenced* observedObject); + + Referenced* getObserverdObject() { return _observedObject; } + const Referenced* getObserverdObject() const { return _observedObject; } + + /** "Lock" a Referenced object i.e., protect it from being deleted + * by incrementing its reference count. + * + * returns null if object doesn't exist anymore. */ + Referenced* addRefLock(); + + inline OpenThreads::Mutex* getObserverSetMutex() const { return &_mutex; } + + void addObserver(Observer* observer); + void removeObserver(Observer* observer); + + void signalObjectDeleted(void* ptr); + + typedef std::set Observers; + Observers& getObservers() { return _observers; } + const Observers& getObservers() const { return _observers; } + + protected: + + ObserverSet(const ObserverSet& rhs): osg::Referenced(rhs) {} + ObserverSet& operator = (const ObserverSet& /*rhs*/) { return *this; } + virtual ~ObserverSet(); + + mutable OpenThreads::Mutex _mutex; + Referenced* _observedObject; + Observers _observers; +}; + +} + +#endif diff --git a/libs/include/android/osg/ObserverNodePath b/libs/include/android/osg/ObserverNodePath new file mode 100755 index 0000000..a9a06bc --- /dev/null +++ b/libs/include/android/osg/ObserverNodePath @@ -0,0 +1,76 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_OBSERVERNODEPATH +#define OSG_OBSERVERNODEPATH 1 + +#include +#include +#include + +namespace osg { + +typedef std::vector< osg::ref_ptr > RefNodePath; + +/** ObserverNodePath is an observer class for tracking changes to a NodePath, + * that automatically invalidates it when nodes are deleted.*/ +class OSG_EXPORT ObserverNodePath +{ + public: + ObserverNodePath(); + + ObserverNodePath(const ObserverNodePath& rhs); + + ObserverNodePath(const osg::NodePath& nodePath); + + ~ObserverNodePath(); + + ObserverNodePath& operator = (const ObserverNodePath& rhs); + + /** get the NodePath from the first parental chain back to root, plus the specified node.*/ + void setNodePathTo(osg::Node* node); + + void setNodePath(const osg::RefNodePath& nodePath); + + void setNodePath(const osg::NodePath& nodePath); + + void clearNodePath(); + + /** Get a thread safe RefNodePath, return true if NodePath is valid.*/ + bool getRefNodePath(RefNodePath& refNodePath) const; + + /** Get a lightweight NodePath that isn't thread safe but + * may be safely used in single threaded applications, or when + * its known that the NodePath won't be invalidated during usage + * of the NodePath. return true if NodePath is valid.*/ + bool getNodePath(NodePath& nodePath) const; + + bool empty() const + { + OpenThreads::ScopedLock lock(_mutex); + return _nodePath.empty(); + } + + protected: + + void _setNodePath(const osg::NodePath& nodePath); + void _clearNodePath(); + + typedef std::vector< osg::observer_ptr > ObsNodePath; + mutable OpenThreads::Mutex _mutex; + ObsNodePath _nodePath; +}; + +} + +#endif diff --git a/libs/include/android/osg/OccluderNode b/libs/include/android/osg/OccluderNode new file mode 100755 index 0000000..40105f8 --- /dev/null +++ b/libs/include/android/osg/OccluderNode @@ -0,0 +1,59 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_OCCLUDERNODE +#define OSG_OCCLUDERNODE 1 + +#include +#include + +namespace osg { + +/** + * OccluderNode is a Group node which provides hooks for adding + * ConvexPlanarOccluders to the scene. + */ +class OSG_EXPORT OccluderNode : public Group +{ + public : + + OccluderNode(); + + /** Copy constructor using CopyOp to manage deep vs shallow copy.*/ + OccluderNode(const OccluderNode&,const CopyOp& copyop=CopyOp::SHALLOW_COPY); + + META_Node(osg, OccluderNode); + + + /** Attach a ConvexPlanarOccluder to an OccluderNode.*/ + void setOccluder(ConvexPlanarOccluder* occluder) { _occluder = occluder; } + + /** Get the ConvexPlanarOccluder* attached to a OccluderNode. */ + ConvexPlanarOccluder* getOccluder() { return _occluder.get(); } + + /** Get the const ConvexPlanarOccluder* attached to a OccluderNode.*/ + const ConvexPlanarOccluder* getOccluder() const { return _occluder.get(); } + + /** Overrides Group's computeBound.*/ + virtual BoundingSphere computeBound() const; + + protected : + + virtual ~OccluderNode() {} + + ref_ptr _occluder; +}; + +} + +#endif diff --git a/libs/include/android/osg/OcclusionQueryNode b/libs/include/android/osg/OcclusionQueryNode new file mode 100755 index 0000000..07285f8 --- /dev/null +++ b/libs/include/android/osg/OcclusionQueryNode @@ -0,0 +1,206 @@ +// +// Copyright (C) 2007 Skew Matrix Software LLC (http://www.skew-matrix.com) +// +// This library is open source and may be redistributed and/or modified under +// the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or +// (at your option) any later version. The full license is in LICENSE file +// included with this distribution, and on the openscenegraph.org website. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// OpenSceneGraph Public License for more details. +// + +#ifndef OSG_OCCLUSION_QUERY_NODE +#define OSG_OCCLUSION_QUERY_NODE 1 + +#include +#include +#include +#include + + +namespace osg { + +// Create and return a StateSet appropriate for performing an occlusion +// query test (disable lighting, texture mapping, etc). Probably some +// room for improvement here. Could disable shaders, for example. +osg::StateSet* initOQState(); + +// Create and return a StateSet for rendering a debug representation of query geometry. +osg::StateSet* initOQDebugState(); + +// TestResult -- stores (per context) results of an occlusion query +// test performed by QueryGeometry. An OcclusionQueryNode has a +// Geode owning a single QueryGeometry that +// draws the occlusion query geometry. QueryGeometry keeps a +// TestResult per context to store the result/status of each query. +// Accessed during the cull and draw traversals. +class TestResult : public osg::Referenced +{ +public: + TestResult() : _init( false ), _id( 0 ), _contextID( 0 ), _active( false ), _numPixels( 0 ) {} + ~TestResult() {} + + bool _init; + + // Query ID for this context. + GLuint _id; + // Context ID owning this query ID. + unsigned int _contextID; + + // Set to true when a query gets issued and set to + // false when the result is retrieved. + mutable bool _active; + + // Result of last query. + GLint _numPixels; +}; + +// QueryGeometry -- A Drawable that performs an occlusion query, +// using its geometric data as the query geometry. +class OSG_EXPORT QueryGeometry : public osg::Geometry +{ +public: + QueryGeometry( const std::string& oqnName=std::string("") ); + ~QueryGeometry(); + + void reset(); + + // TBD implement copy constructor + + virtual void drawImplementation( osg::RenderInfo& renderInfo ) const; + + unsigned int getNumPixels( const osg::Camera* cam ); + + virtual void releaseGLObjects( osg::State* state = 0 ) const; + + static void deleteQueryObject( unsigned int contextID, GLuint handle ); + static void flushDeletedQueryObjects( unsigned int contextID, double currentTime, double& availableTime ); + static void discardDeletedQueryObjects( unsigned int contextID ); + +protected: + typedef std::map< const osg::Camera*, TestResult > ResultMap; + mutable ResultMap _results; + mutable OpenThreads::Mutex _mapMutex; + + // Needed for debug only + std::string _oqnName; +}; + +// This Node performs occlusion query testing on its children. +// You can use it directly to occlusion query test a portion +// of your scene graph, or you can use it implicitly with an +// OcclusionQueryRoot, which places OcclusionQueryNodes where +// needed and acts as a master control. +class OSG_EXPORT OcclusionQueryNode : public osg::Group +{ +public: + OcclusionQueryNode(); + + // Copy constructor using CopyOp to manage deep vs shallow copy. + OcclusionQueryNode( const OcclusionQueryNode& oqn, const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY ); + + META_Node( osg, OcclusionQueryNode ); + + virtual osg::BoundingSphere computeBound() const; + + virtual void releaseGLObjects( osg::State* state = 0 ) const; + + + // When disabled, OQN doesn't perform occlusion queries, and simply + // renders its children. + void setQueriesEnabled( bool enable=true ); + bool getQueriesEnabled() const { return _enabled; } + + + // Sets/gets the visibility threshold. If the test indicates that + // the number of visible pixels is less than the specified + // threshold, don't draw the actual geometry. + void setVisibilityThreshold( unsigned int pixels ) { _visThreshold = pixels; } + unsigned int getVisibilityThreshold() const { return _visThreshold; } + + // Specifies how many frames to wait before issuing another query. + void setQueryFrameCount( unsigned int frames ) { _queryFrameCount = frames; } + unsigned int getQueryFrameCount() const { return _queryFrameCount; } + + // Indicate whether or not the bounding box used in the occlusion query test + // should be rendered. Handy for debugging and development. + // Should only be called outside of cull/draw. No thread issues. + void setDebugDisplay( bool enable ); + bool getDebugDisplay() const; + + + // Set and get the StateSet used by the OcclusionQueryNode + // when rendering the query geometry. OQN creates its own by + // default, but if you use many OQNs you might want to use + // this method to set all OQNs to use the same StateSet + // for more efficient processing. + void setQueryStateSet( osg::StateSet* ss ); + osg::StateSet* getQueryStateSet(); + const osg::StateSet* getQueryStateSet() const; + + // Get the QueryGeometry object used for occlusion query. Returns 0 if no QueryGeometry is created. + osg::QueryGeometry* getQueryGeometry(); + const osg::QueryGeometry* getQueryGeometry() const; + + // Set and get the StateSet used by the OcclusionQueryNode + // when rendering the debug query geometry (see setDebugDisplay). + void setDebugStateSet( osg::StateSet* ss ); + osg::StateSet* getDebugStateSet(); + const osg::StateSet* getDebugStateSet() const; + + // For statistics gathering, e.g., by a NodeVisitor. + bool getPassed() const; + + + // These methods are public so that osgUtil::CullVisitor can access them. + // Not intended for application use. + virtual bool getPassed( const osg::Camera* camera, osg::NodeVisitor& nv ); + void traverseQuery( const osg::Camera* camera, osg::NodeVisitor& nv ); + void traverseDebug( osg::NodeVisitor& nv ); + + + // Delete unused query IDs for this contextID. + static void flushDeletedQueryObjects( unsigned int contextID, double currentTime, double& availableTime ); + + // discard all the cached query objects which need to be deleted + // in the OpenGL context related to contextID. + // Note, unlike flush no OpenGL calls are made, instead the handles are all removed. + // this call is useful for when an OpenGL context has been destroyed. + static void discardDeletedQueryObjects( unsigned int contextID ); + +protected: + virtual ~OcclusionQueryNode(); + + virtual void createSupportNodes(); + + osg::ref_ptr< osg::Geode > _queryGeode; + osg::ref_ptr< osg::Geode > _debugGeode; + + bool _enabled; + + // Tracks the last frame number that we performed a query. + // User can set how many times (See setQueryFrameCount). + typedef std::map< const osg::Camera*, unsigned int > FrameCountMap; + FrameCountMap _frameCountMap; + mutable OpenThreads::Mutex _frameCountMutex; + + // For statistics gathering + bool _passed; + + // User-settable variables + unsigned int _visThreshold; + unsigned int _queryFrameCount; + bool _debugBB; + + + // Required to ensure that computeBound() is thread-safe. + mutable OpenThreads::Mutex _computeBoundMutex; +}; + +} + + +#endif diff --git a/libs/include/android/osg/OperationThread b/libs/include/android/osg/OperationThread new file mode 100755 index 0000000..c9c84cb --- /dev/null +++ b/libs/include/android/osg/OperationThread @@ -0,0 +1,227 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_OPERATIONTHREAD +#define OSG_OPERATIONTHREAD 1 + +#include +#include + +#include +#include +#include +#include + +#include +#include + +namespace osg { + +class RefBlock : virtual public osg::Referenced, public OpenThreads::Block +{ + public: + + RefBlock(): + osg::Referenced(true) {} + +}; + +class RefBlockCount : virtual public osg::Referenced, public OpenThreads::BlockCount +{ + public: + + RefBlockCount(unsigned blockCount): + osg::Referenced(true), + OpenThreads::BlockCount(blockCount) {} + +}; + +/** Base class for implementing graphics operations.*/ +class Operation : virtual public Referenced +{ + public: + + Operation(const std::string& name, bool keep): + osg::Referenced(true), + _name(name), + _keep(keep) {} + + + /** Set the human readable name of the operation.*/ + void setName(const std::string& name) { _name = name; } + + /** Get the human readable name of the operation.*/ + const std::string& getName() const { return _name; } + + /** Set whether the operation should be kept once its been applied.*/ + void setKeep(bool keep) { _keep = keep; } + + /** Get whether the operation should be kept once its been applied.*/ + bool getKeep() const { return _keep; } + + /** if this operation is a barrier then release it.*/ + virtual void release() {} + + /** Do the actual task of this operation.*/ + virtual void operator () (Object*) = 0; + + protected: + + Operation(): + Referenced(true), + _keep(false) {} + + Operation(const Operation& op): + Referenced(true), + _name(op._name), + _keep(op._keep) {} + + virtual ~Operation() {} + + std::string _name; + bool _keep; +}; + +class OperationThread; + +class OSG_EXPORT OperationQueue : public Referenced +{ + public: + + OperationQueue(); + + /** Get the next operation from the operation queue. + * Return null ref_ptr<> if no operations are left in queue. */ + osg::ref_ptr getNextOperation(bool blockIfEmpty = false); + + /** Return true if the operation queue is empty. */ + bool empty(); + + /** Return the num of pending operations that are sitting in the OperationQueue.*/ + unsigned int getNumOperationsInQueue(); + + /** Add operation to end of OperationQueue, this will be + * executed by the operation thread once this operation gets to the head of the queue.*/ + void add(Operation* operation); + + /** Remove operation from OperationQueue.*/ + void remove(Operation* operation); + + /** Remove named operation from OperationQueue.*/ + void remove(const std::string& name); + + /** Remove all operations from OperationQueue.*/ + void removeAllOperations(); + + /** Run the operations. */ + void runOperations(Object* callingObject=0); + + /** Call release on all operations. */ + void releaseAllOperations(); + + /** Release operations block that is used to block threads that are waiting on an empty operations queue.*/ + void releaseOperationsBlock(); + + typedef std::set OperationThreads; + + /** Get the set of OperationThreads that are sharing this OperationQueue. */ + const OperationThreads& getOperationThreads() const { return _operationThreads; } + + protected: + + virtual ~OperationQueue(); + + friend class OperationThread; + + void addOperationThread(OperationThread* thread); + void removeOperationThread(OperationThread* thread); + + typedef std::list< osg::ref_ptr > Operations; + + OpenThreads::Mutex _operationsMutex; + osg::ref_ptr _operationsBlock; + Operations _operations; + Operations::iterator _currentOperationIterator; + + OperationThreads _operationThreads; +}; + +/** OperationThread is a helper class for running Operation within a single thread.*/ +class OSG_EXPORT OperationThread : public Referenced, public OpenThreads::Thread +{ + public: + OperationThread(); + + void setParent(Object* parent) { _parent = parent; } + + Object* getParent() { return _parent.get(); } + + const Object* getParent() const { return _parent.get(); } + + + /** Set the OperationQueue. */ + void setOperationQueue(OperationQueue* opq); + + /** Get the OperationQueue. */ + OperationQueue* getOperationQueue() { return _operationQueue.get(); } + + /** Get the const OperationQueue. */ + const OperationQueue* getOperationQueue() const { return _operationQueue.get(); } + + + /** Add operation to end of OperationQueue, this will be + * executed by the graphics thread once this operation gets to the head of the queue.*/ + void add(Operation* operation); + + /** Remove operation from OperationQueue.*/ + void remove(Operation* operation); + + /** Remove named operation from OperationQueue.*/ + void remove(const std::string& name); + + /** Remove all operations from OperationQueue.*/ + void removeAllOperations(); + + + /** Get the operation currently being run.*/ + osg::ref_ptr getCurrentOperation() { return _currentOperation; } + + /** Run does the opertion thread run loop.*/ + virtual void run(); + + void setDone(bool done); + + bool getDone() const { return _done; } + + /** Cancel this graphics thread.*/ + virtual int cancel(); + + protected: + + virtual ~OperationThread(); + + observer_ptr _parent; + + bool _done; + + OpenThreads::Mutex _threadMutex; + osg::ref_ptr _operationQueue; + osg::ref_ptr _currentOperation; + +}; + +typedef OperationThread OperationsThread; + +} + +#endif diff --git a/libs/include/android/osg/PagedLOD b/libs/include/android/osg/PagedLOD new file mode 100755 index 0000000..b279824 --- /dev/null +++ b/libs/include/android/osg/PagedLOD @@ -0,0 +1,172 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_PagedLOD +#define OSG_PagedLOD 1 + +#include + +namespace osg { + +/** PagedLOD. +*/ +class OSG_EXPORT PagedLOD : public LOD +{ + public : + + PagedLOD(); + + /** Copy constructor using CopyOp to manage deep vs shallow copy.*/ + PagedLOD(const PagedLOD&,const CopyOp& copyop=CopyOp::SHALLOW_COPY); + + META_Node(osg, PagedLOD); + + + + virtual void traverse(NodeVisitor& nv); + + virtual bool addChild(Node *child); + + virtual bool addChild(Node *child, float min, float max); + + virtual bool addChild(Node *child, float min, float max,const std::string& filename, float priorityOffset=0.0f, float priorityScale=1.0f); + + virtual bool removeChildren(unsigned int pos,unsigned int numChildrenToRemove=1); + + + /** Set the optional database osgDB::Options object to use when reading children.*/ + void setDatabaseOptions(osg::Referenced* options) { _databaseOptions = options; } + + /** Get the optional database osgDB::Options object used when reading children.*/ + osg::Referenced* getDatabaseOptions() { return _databaseOptions.get(); } + + /** Get the optional database osgDB::Options object used when reading children.*/ + const osg::Referenced* getDatabaseOptions() const { return _databaseOptions.get(); } + + + /** Set the database path to prepend to children's filenames.*/ + void setDatabasePath(const std::string& path); + + /** Get the database path used to prepend to children's filenames.*/ + inline const std::string& getDatabasePath() const { return _databasePath; } + + + struct OSG_EXPORT PerRangeData + { + PerRangeData(); + PerRangeData(const PerRangeData& prd); + PerRangeData& operator = (const PerRangeData& prd); + + std::string _filename; + float _priorityOffset; + float _priorityScale; + double _minExpiryTime; + unsigned int _minExpiryFrames; + double _timeStamp; + unsigned int _frameNumber; + unsigned int _frameNumberOfLastReleaseGLObjects; + osg::ref_ptr _databaseRequest; + }; + + typedef std::vector PerRangeDataList; + + void setFileName(unsigned int childNo, const std::string& filename) { expandPerRangeDataTo(childNo); _perRangeDataList[childNo]._filename=filename; } + const std::string& getFileName(unsigned int childNo) const { return _perRangeDataList[childNo]._filename; } + unsigned int getNumFileNames() const { return static_cast(_perRangeDataList.size()); } + + + void setPriorityOffset(unsigned int childNo, float priorityOffset) { expandPerRangeDataTo(childNo); _perRangeDataList[childNo]._priorityOffset=priorityOffset; } + float getPriorityOffset(unsigned int childNo) const { return _perRangeDataList[childNo]._priorityOffset; } + unsigned int getNumPriorityOffsets() const { return static_cast(_perRangeDataList.size()); } + + void setPriorityScale(unsigned int childNo, float priorityScale) { expandPerRangeDataTo(childNo); _perRangeDataList[childNo]._priorityScale=priorityScale; } + float getPriorityScale(unsigned int childNo) const { return _perRangeDataList[childNo]._priorityScale; } + unsigned int getNumPriorityScales() const { return static_cast(_perRangeDataList.size()); } + + /** Sets the minimum amount of time, in seconds, that must pass without a child being traversed before it can be expired. */ + void setMinimumExpiryTime(unsigned int childNo, double minTime) { expandPerRangeDataTo(childNo); _perRangeDataList[childNo]._minExpiryTime=minTime; } + double getMinimumExpiryTime(unsigned int childNo) const { return _perRangeDataList[childNo]._minExpiryTime; } + unsigned int getNumMinimumExpiryTimes() const { return static_cast(_perRangeDataList.size()); } + + /** Sets the minimum number of frames that must be rendered without a child being traversed before it can be expired. */ + void setMinimumExpiryFrames(unsigned int childNo, unsigned int minFrames) { expandPerRangeDataTo(childNo); _perRangeDataList[childNo]._minExpiryFrames=minFrames; } + unsigned int getMinimumExpiryFrames(unsigned int childNo) const { return _perRangeDataList[childNo]._minExpiryFrames; } + unsigned int getNumMinimumExpiryFrames() const { return static_cast(_perRangeDataList.size()); } + + + void setTimeStamp(unsigned int childNo, double timeStamp) { expandPerRangeDataTo(childNo); _perRangeDataList[childNo]._timeStamp=timeStamp; } + double getTimeStamp(unsigned int childNo) const { return _perRangeDataList[childNo]._timeStamp; } + unsigned int getNumTimeStamps() const { return static_cast(_perRangeDataList.size()); } + + void setFrameNumber(unsigned int childNo, unsigned int frameNumber) { expandPerRangeDataTo(childNo); _perRangeDataList[childNo]._frameNumber=frameNumber; } + unsigned getFrameNumber(unsigned int childNo) const { return _perRangeDataList[childNo]._frameNumber; } + unsigned int getNumFrameNumbers() const { return static_cast(_perRangeDataList.size()); } + + + /** Return the DatabaseRequest object used by the DatabasePager to keep track of file load requests + * being carried on behalf of the DatabasePager. + * Note, in normal OSG usage you should not set this value yourself, as this will be managed by + * the osgDB::DatabasePager.*/ + osg::ref_ptr& getDatabaseRequest(unsigned int childNo) { return _perRangeDataList[childNo]._databaseRequest; } + + /** Return the const DatabaseRequest object.*/ + const osg::ref_ptr& getDatabaseRequest(unsigned int childNo) const { return _perRangeDataList[childNo]._databaseRequest; } + + + /** Set the frame number of the last time that this PageLOD node was traversed. + * Note, this frame number is automatically set by the traverse() method for all traversals (update, cull etc.). + */ + inline void setFrameNumberOfLastTraversal(unsigned int frameNumber) { _frameNumberOfLastTraversal=frameNumber; } + + /** Get the frame number of the last time that this PageLOD node was traversed.*/ + inline unsigned int getFrameNumberOfLastTraversal() const { return _frameNumberOfLastTraversal; } + + + /** Set the number of children that the PagedLOD must keep around, even if they are older than their expiry time.*/ + inline void setNumChildrenThatCannotBeExpired(unsigned int num) { _numChildrenThatCannotBeExpired = num; } + + /** Get the number of children that the PagedLOD must keep around, even if they are older than their expiry time.*/ + unsigned int getNumChildrenThatCannotBeExpired() const { return _numChildrenThatCannotBeExpired; } + + /** Set wether you want to disable the paging in of external nodes.*/ + void setDisableExternalChildrenPaging(bool flag) { _disableExternalChildrenPaging = flag; } + + bool getDisableExternalChildrenPaging() const { return _disableExternalChildrenPaging; } + + + + /** Remove the children from the PagedLOD which haven't been visited since specified expiry time and expiry frame number. + * The removed children are added to the removeChildren list passed into the method, + * this allows the children to be deleted later at the caller's discretion. + * Return true if children are removed, false otherwise. */ + virtual bool removeExpiredChildren(double expiryTime, unsigned int expiryFrame, NodeList& removedChildren); + + protected : + + virtual ~PagedLOD(); + + void expandPerRangeDataTo(unsigned int pos); + + ref_ptr _databaseOptions; + std::string _databasePath; + + unsigned int _frameNumberOfLastTraversal; + unsigned int _numChildrenThatCannotBeExpired; + bool _disableExternalChildrenPaging; + + PerRangeDataList _perRangeDataList; +}; + +} + +#endif diff --git a/libs/include/android/osg/PatchParameter b/libs/include/android/osg/PatchParameter new file mode 100755 index 0000000..8e9d471 --- /dev/null +++ b/libs/include/android/osg/PatchParameter @@ -0,0 +1,88 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_PATCHPARAMETER +#define OSG_PATCHPARAMETER 1 + +#include +#include +#include +#include + +namespace osg { + +/** Class which encapsulates glPatchParameter(..). +*/ +class OSG_EXPORT PatchParameter : public StateAttribute +{ + public : + + PatchParameter(GLint vertices=3); + + /** Copy constructor using CopyOp to manage deep vs shallow copy.*/ + PatchParameter(const PatchParameter& rhs,const CopyOp& copyop=CopyOp::SHALLOW_COPY): + StateAttribute(rhs,copyop), + _vertices(rhs._vertices), + _patchDefaultInnerLevel(rhs._patchDefaultInnerLevel), + _patchDefaultOuterLevel(rhs._patchDefaultOuterLevel) {} + + + META_StateAttribute(osg, PatchParameter, PATCH_PARAMETER); + + /** return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs.*/ + virtual int compare(const StateAttribute& sa) const + { + // check the types are equal and then create the rhs variable + // used by the COMPARE_StateAttribute_Parameter macros below. + COMPARE_StateAttribute_Types(PatchParameter,sa) + + // compare each parameter in turn against the rhs. + COMPARE_StateAttribute_Parameter(_vertices) + COMPARE_StateAttribute_Parameter(_patchDefaultInnerLevel) + COMPARE_StateAttribute_Parameter(_patchDefaultOuterLevel) + + return 0; // passed all the above comparison macros, must be equal. + } + + /** Set GL_PATCH_VERTICES parameter.*/ + void setVertices(GLint vertices) { _vertices = vertices; } + + /** Get GL_PATCH_VERTICES parameter.*/ + GLint getVertices() const { return _vertices; } + + /** Set GL_PATCH_DEFAULT_INNER_LEVEL parameter.*/ + void setPatchDefaultInnerLevel(const osg::Vec2& level) { _patchDefaultInnerLevel = level; } + + /** Get GL_PATCH_DEFAULT_INNER_LEVEL parameter.*/ + const osg::Vec2& getPatchDefaultInnerLevel() const { return _patchDefaultInnerLevel; } + + /** Set GL_PATCH_DEFAULT_OUTER_LEVEL parameter.*/ + void setPatchDefaultOuterLevel(const osg::Vec4& level) { _patchDefaultOuterLevel = level; } + + /** Get GL_PATCH_DEFAULT_INNER_LEVEL parameter.*/ + const osg::Vec4& getPatchDefaultOuterLevel() const { return _patchDefaultOuterLevel; } + + virtual void apply(State& state) const; + + protected: + + virtual ~PatchParameter(); + + GLint _vertices; + osg::Vec2 _patchDefaultInnerLevel; + osg::Vec4 _patchDefaultOuterLevel; +}; + +} + +#endif diff --git a/libs/include/android/osg/Plane b/libs/include/android/osg/Plane new file mode 100755 index 0000000..bb9b033 --- /dev/null +++ b/libs/include/android/osg/Plane @@ -0,0 +1,362 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_PLANE +#define OSG_PLANE 1 + +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace osg { + +/** @brief A plane class. It can be used to represent an infinite plane. + * + * The infinite plane is described by an implicit plane equation a*x+b*y+c*z+d = 0. Though it is not mandatory that + * a^2+b^2+c^2 = 1 is fulfilled in general some methods require it (@see osg::Plane::distance). */ +class OSG_EXPORT Plane +{ + + public: + +#ifdef OSG_USE_FLOAT_PLANE + /** Type of Plane class.*/ + typedef float value_type; + typedef Vec3f Vec3_type; + typedef Vec4f Vec4_type; +#else + /** Type of Plane class.*/ + typedef double value_type; + typedef Vec3d Vec3_type; + typedef Vec4d Vec4_type; +#endif + + /** Number of vector components. */ + enum { num_components = 3 }; + + + /// Default constructor + /** The default constructor initializes all values to zero. + * @warning Although the method osg::Plane::valid() will return true after the default constructors call the plane + * is mathematically invalid! Default data do not describe a valid plane. */ + inline Plane() { _fv[0]=0.0; _fv[1]=0.0; _fv[2]=0.0; _fv[3]=0.0; _lowerBBCorner = 0; _upperBBCorner = 0; } + inline Plane(const Plane& pl) { set(pl); } + /// Constructor + /** The plane is described as a*x+b*y+c*z+d = 0. + * @remark You may call osg::Plane::MakeUnitLength afterwards if the passed values are not normalized. */ + inline Plane(value_type a,value_type b,value_type c,value_type d) { set(a,b,c,d); } + + /// Constructor + /** The plane can also be described as vec*[x,y,z,1]. + * @remark You may call osg::Plane::MakeUnitLength afterwards if the passed values are not normalized. */ + inline Plane(const Vec4f& vec) { set(vec); } + /// Constructor + /** The plane can also be described as vec*[x,y,z,1]. + * @remark You may call osg::Plane::MakeUnitLength afterwards if the passed values are not normalized. */ + inline Plane(const Vec4d& vec) { set(vec); } + + /// Constructor + /** This constructor initializes the internal values directly without any checking or manipulation. + * @param norm The normal of the plane. + * @param d The negative distance from the point of origin to the plane. + * @remark You may call osg::Plane::MakeUnitLength afterwards if the passed normal was not normalized. */ + inline Plane(const Vec3_type& norm,value_type d) { set(norm,d); } + + /// Constructor + /** This constructor calculates from the three points describing an infinite plane the internal values. + * @param v1 Point in the plane. + * @param v2 Point in the plane. + * @param v3 Point in the plane. + * @remark After this constructor call the plane's normal is normalized in case the three points described a mathematically + * valid plane. + * @remark The normal is determined by building the cross product of (v2-v1) ^ (v3-v2). */ + inline Plane(const Vec3_type& v1, const Vec3_type& v2, const Vec3_type& v3) { set(v1,v2,v3); } + + /// Constructor + /** This constructor initializes the internal values directly without any checking or manipulation. + * @param norm The normal of the plane. + * @param point A point of the plane. + * @remark You may call osg::Plane::MakeUnitLength afterwards if the passed normal was not normalized. */ + inline Plane(const Vec3_type& norm, const Vec3_type& point) { set(norm,point); } + + inline Plane& operator = (const Plane& pl) + { + if (&pl==this) return *this; + set(pl); + return *this; + } + + inline void set(const Plane& pl) { _fv[0]=pl._fv[0]; _fv[1]=pl._fv[1]; _fv[2]=pl._fv[2]; _fv[3]=pl._fv[3]; calculateUpperLowerBBCorners(); } + inline void set(value_type a, value_type b, value_type c, value_type d) { _fv[0]=a; _fv[1]=b; _fv[2]=c; _fv[3]=d; calculateUpperLowerBBCorners(); } + + inline void set(const Vec4f& vec) { set(vec[0],vec[1],vec[2],vec[3]); } + inline void set(const Vec4d& vec) { set(vec[0],vec[1],vec[2],vec[3]); } + + inline void set(const Vec3_type& norm, double d) { set(norm[0],norm[1],norm[2],d); } + + inline void set(const Vec3_type& v1, const Vec3_type& v2, const Vec3_type& v3) + { + Vec3_type norm = (v2-v1)^(v3-v2); + value_type length = norm.length(); + if (length>1e-6) norm/= length; + else norm.set(0.0,0.0,0.0); + set(norm[0],norm[1],norm[2],-(v1*norm)); + } + + inline void set(const Vec3_type& norm, const Vec3_type& point) + { + value_type d = -norm[0]*point[0] - norm[1]*point[1] - norm[2]*point[2]; + set(norm[0],norm[1],norm[2],d); + } + + /** flip/reverse the orientation of the plane.*/ + inline void flip() + { + _fv[0] = -_fv[0]; + _fv[1] = -_fv[1]; + _fv[2] = -_fv[2]; + _fv[3] = -_fv[3]; + calculateUpperLowerBBCorners(); + } + + /** This method multiplies the coefficients of the plane equation with a constant factor so that the + * equation a^2+b^2+c^2 = 1 holds. */ + inline void makeUnitLength() + { + value_type inv_length = 1.0 / sqrt(_fv[0]*_fv[0] + _fv[1]*_fv[1]+ _fv[2]*_fv[2]); + _fv[0] *= inv_length; + _fv[1] *= inv_length; + _fv[2] *= inv_length; + _fv[3] *= inv_length; + } + + /** calculate the upper and lower bounding box corners to be used + * in the intersect(BoundingBox&) method for speeding calculations.*/ + inline void calculateUpperLowerBBCorners() + { + _upperBBCorner = (_fv[0]>=0.0?1:0) | + (_fv[1]>=0.0?2:0) | + (_fv[2]>=0.0?4:0); + + _lowerBBCorner = (~_upperBBCorner)&7; + + } + + /// Checks if all internal values describing the plane have valid numbers + /** @warning This method does not check if the plane is mathematically correctly described! + * @remark The only case where all elements have valid numbers and the plane description is invalid occurs if the plane's normal + * is zero. */ + inline bool valid() const { return !isNaN(); } + inline bool isNaN() const { return osg::isNaN(_fv[0]) || osg::isNaN(_fv[1]) || osg::isNaN(_fv[2]) || osg::isNaN(_fv[3]); } + + inline bool operator == (const Plane& plane) const { return _fv[0]==plane._fv[0] && _fv[1]==plane._fv[1] && _fv[2]==plane._fv[2] && _fv[3]==plane._fv[3]; } + + inline bool operator != (const Plane& plane) const { return _fv[0]!=plane._fv[0] || _fv[1]!=plane._fv[1] || _fv[2]!=plane._fv[2] || _fv[3]!=plane._fv[3]; } + + /** A plane is said to be smaller than another plane if the first non-identical element of the internal array is smaller than the + * corresponding element of the other plane. */ + inline bool operator < (const Plane& plane) const + { + if (_fv[0]plane._fv[0]) return false; + else if (_fv[1]plane._fv[1]) return false; + else if (_fv[2]plane._fv[2]) return false; + else return (_fv[3]& vertices) const + { + if (vertices.empty()) return -1; + + int noAbove = 0; + int noBelow = 0; + int noOn = 0; + for(std::vector::const_iterator itr=vertices.begin(); + itr != vertices.end(); + ++itr) + { + float d = distance(*itr); + if (d>0.0f) ++noAbove; + else if (d<0.0f) ++noBelow; + else ++noOn; + } + + if (noAbove>0) + { + if (noBelow>0) return 0; + else return 1; + } + return -1; // treat points on line as outside... + } + + /** intersection test between plane and vertex list + return 1 if the bs is completely above plane, + return 0 if the bs intersects the plane, + return -1 if the bs is completely below the plane.*/ + inline int intersect(const std::vector& vertices) const + { + if (vertices.empty()) return -1; + + int noAbove = 0; + int noBelow = 0; + int noOn = 0; + for(std::vector::const_iterator itr=vertices.begin(); + itr != vertices.end(); + ++itr) + { + double d = distance(*itr); + if (d>0.0) ++noAbove; + else if (d<0.0) ++noBelow; + else ++noOn; + } + + if (noAbove>0) + { + if (noBelow>0) return 0; + else return 1; + } + return -1; // treat points on line as outside... + } + + /** intersection test between plane and bounding sphere. + return 1 if the bs is completely above plane, + return 0 if the bs intersects the plane, + return -1 if the bs is completely below the plane.*/ + inline int intersect(const BoundingSphere& bs) const + { + float d = distance(bs.center()); + + if (d>bs.radius()) return 1; + else if (d<-bs.radius()) return -1; + else return 0; + } + + + /** intersection test between plane and bounding sphere. + return 1 if the bs is completely above plane, + return 0 if the bs intersects the plane, + return -1 if the bs is completely below the plane.*/ + inline int intersect(const BoundingBox& bb) const + { + // if lowest point above plane than all above. + if (distance(bb.corner(_lowerBBCorner))>0.0f) return 1; + + // if highest point is below plane then all below. + if (distance(bb.corner(_upperBBCorner))<0.0f) return -1; + + // d_lower<=0.0f && d_upper>=0.0f + // therefore must be crossing plane. + return 0; + + } + + /** Transform the plane by matrix. Note, this operation carries out + * the calculation of the inverse of the matrix since a plane + * must be multiplied by the inverse transposed to transform it. This + * make this operation expensive. If the inverse has been already + * calculated elsewhere then use transformProvidingInverse() instead. + * See http://www.worldserver.com/turk/computergraphics/NormalTransformations.pdf*/ + inline void transform(const osg::Matrix& matrix) + { + osg::Matrix inverse; + inverse.invert(matrix); + transformProvidingInverse(inverse); + } + + /** Transform the plane by providing a pre inverted matrix. + * see transform for details. */ + inline void transformProvidingInverse(const osg::Matrix& matrix) + { + // note pre multiplications, which effectively transposes matrix. + Vec4_type vec(_fv[0],_fv[1],_fv[2],_fv[3]); + vec = matrix * vec; + set(vec); + makeUnitLength(); + } + + protected: + + /** Vec member variable. */ + value_type _fv[4]; + + // variables cached to optimize calcs against bounding boxes. + unsigned int _upperBBCorner; + unsigned int _lowerBBCorner; + + +}; + +} // end of namespace + +#endif diff --git a/libs/include/android/osg/Point b/libs/include/android/osg/Point new file mode 100755 index 0000000..1c5f259 --- /dev/null +++ b/libs/include/android/osg/Point @@ -0,0 +1,157 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_POINT +#define OSG_POINT 1 + +#include +#include + +#ifndef GL_POINT_SMOOTH + #define GL_POINT_SMOOTH 0x0B10 +#endif + +#ifndef GL_POINT_SMOOTH_HINT + #define GL_POINT_SMOOTH_HINT 0x0C51 +#endif + +namespace osg { + +/** Point - encapsulates the OpenGL point smoothing and size state.*/ +class OSG_EXPORT Point : public StateAttribute +{ + public : + + Point(); + + Point(float size); + + /** Copy constructor using CopyOp to manage deep vs shallow copy.*/ + Point(const Point& point,const CopyOp& copyop=CopyOp::SHALLOW_COPY): + StateAttribute(point,copyop), + _size(point._size), + _fadeThresholdSize(point._fadeThresholdSize), + _distanceAttenuation(point._distanceAttenuation), + _minSize(point._minSize), + _maxSize(point._maxSize) {} + + META_StateAttribute(osg, Point, POINT); + + /** return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs.*/ + virtual int compare(const StateAttribute& sa) const + { + // check the types are equal and then create the rhs variable + // used by the COMPARE_StateAttribute_Parameter macros below. + COMPARE_StateAttribute_Types(Point,sa) + + // compare each parameter in turn against the rhs. + COMPARE_StateAttribute_Parameter(_size) + COMPARE_StateAttribute_Parameter(_fadeThresholdSize) + COMPARE_StateAttribute_Parameter(_distanceAttenuation) + COMPARE_StateAttribute_Parameter(_minSize) + COMPARE_StateAttribute_Parameter(_maxSize) + + return 0; // passed all the above comparison macros, must be equal. + } + + virtual bool getModeUsage(StateAttribute::ModeUsage& usage) const + { + usage.usesMode(GL_POINT_SMOOTH); + return true; + } + + void setSize(float size); + inline float getSize() const { return _size; } + + void setFadeThresholdSize(float fadeThresholdSize); + inline float getFadeThresholdSize() const { return _fadeThresholdSize; } + + void setDistanceAttenuation(const Vec3& distanceAttenuation); + inline const Vec3& getDistanceAttenuation() const { return _distanceAttenuation; } + + void setMinSize(float minSize); + inline float getMinSize() const {return _minSize;} + + void setMaxSize(float maxSize); + inline float getMaxSize() const {return _maxSize;} + + virtual void apply(State& state) const; + + /** Encapsulates queries of extension availability, obtains extension + * function pointers, and provides convenience wrappers for + * calling extension functions. */ + class OSG_EXPORT Extensions : public osg::Referenced + { + public: + Extensions(unsigned int contextID); + + Extensions(const Extensions& rhs); + + void lowestCommonDenominator(const Extensions& rhs); + + void setupGLExtensions(unsigned int contextID); + + void setPointParametersSupported(bool flag) { _isPointParametersSupported=flag; } + bool isPointParametersSupported() const { return _isPointParametersSupported; } + + void setPointSpriteCoordOriginSupported(bool flag) { _isPointSpriteCoordOriginSupported=flag; } + bool isPointSpriteCoordOriginSupported() const { return _isPointSpriteCoordOriginSupported; } + + void glPointParameteri(GLenum pname, GLint param) const; + void glPointParameterf(GLenum pname, GLfloat param) const; + void glPointParameterfv(GLenum pname, const GLfloat *params) const; + + protected: + + ~Extensions() {} + + bool _isPointParametersSupported; + bool _isPointSpriteCoordOriginSupported; + + typedef void (GL_APIENTRY * GLPointParameteriProc) (GLenum pname, GLint param); + typedef void (GL_APIENTRY * GLPointParameterfProc) (GLenum pname, GLfloat param); + typedef void (GL_APIENTRY * GLPointParameterfvProc) (GLenum pname, const GLfloat *params); + + GLPointParameteriProc _glPointParameteri; + GLPointParameterfProc _glPointParameterf; + GLPointParameterfvProc _glPointParameterfv; + + }; + + /** Returns the Extensions object for the given context. + * If createIfNotInitalized is true and the Extensions object doesn't + * exist, getExtensions() creates it on the given context. + * Returns NULL if createIfNotInitalized is false and the Extensions + * object doesn't exist. */ + static Extensions* getExtensions(unsigned int contextID,bool createIfNotInitalized); + + /** setExtensions() allows users to override the extensions across graphics contexts. + * Typically used when you have different extensions supported across graphics pipes, + * but need to ensure that they all use the same low common denominator extensions. */ + static void setExtensions(unsigned int contextID,Extensions* extensions); + + protected : + + virtual ~Point(); + + float _size; + float _fadeThresholdSize; + Vec3 _distanceAttenuation; + float _minSize; + float _maxSize; + +}; + +} + +#endif diff --git a/libs/include/android/osg/PointSprite b/libs/include/android/osg/PointSprite new file mode 100755 index 0000000..a127cea --- /dev/null +++ b/libs/include/android/osg/PointSprite @@ -0,0 +1,80 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. + */ + +#ifndef OSG_POINTSPRITE +#define OSG_POINTSPRITE 1 + +#include +#include + +#ifndef GL_ARB_point_sprite +#define GL_POINT_SPRITE_ARB 0x8861 +#define GL_COORD_REPLACE_ARB 0x8862 +#endif + +#ifndef GL_POINT_SPRITE_COORD_ORIGIN +#define GL_POINT_SPRITE_COORD_ORIGIN 0x8CA0 +#define GL_LOWER_LEFT 0x8CA1 +#define GL_UPPER_LEFT 0x8CA2 +#endif + +namespace osg { + +/** PointSprite base class which encapsulates enabling of point sprites .*/ +class OSG_EXPORT PointSprite : public osg::StateAttribute { +public: + + PointSprite(); + + /** Copy constructor using CopyOp to manage deep vs shallow copy.*/ + PointSprite(const PointSprite& ps,const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY): + StateAttribute(ps,copyop), + _coordOriginMode(ps._coordOriginMode) {} + + + META_StateAttribute(osg, PointSprite, POINTSPRITE); + + /** return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs.*/ + virtual int compare(const StateAttribute& sa) const; + + virtual bool getModeUsage(StateAttribute::ModeUsage& usage) const + { + usage.usesMode(GL_POINT_SPRITE_ARB); + return true; + } + + virtual bool checkValidityOfAssociatedModes(osg::State&) const; + + virtual bool isTextureAttribute() const { return true; } + + virtual void apply(osg::State& state) const; + + static bool isPointSpriteSupported(unsigned int context); + + enum CoordOriginMode { + UPPER_LEFT = GL_UPPER_LEFT, + LOWER_LEFT = GL_LOWER_LEFT + }; + + inline void setCoordOriginMode(CoordOriginMode mode) { _coordOriginMode = mode; } + inline CoordOriginMode getCoordOriginMode() const { return _coordOriginMode; } + +protected: + virtual ~PointSprite(); + + CoordOriginMode _coordOriginMode; +}; + +} + +#endif diff --git a/libs/include/android/osg/PolygonMode b/libs/include/android/osg/PolygonMode new file mode 100755 index 0000000..daa3267 --- /dev/null +++ b/libs/include/android/osg/PolygonMode @@ -0,0 +1,90 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_POLYGONMODE +#define OSG_POLYGONMODE 1 + +#include +#include + +#if defined(OSG_GLES1_AVAILABLE) || defined(OSG_GLES2_AVAILABLE) + #define GL_POINT 0x1B00 + #define GL_LINE 0x1B01 + #define GL_FILL 0x1B02 +#endif + +namespace osg { + +/** State Class for setting OpenGL's polygon culling mode. +*/ +class OSG_EXPORT PolygonMode : public StateAttribute +{ + public : + + enum Mode { + POINT = GL_POINT, + LINE = GL_LINE, + FILL = GL_FILL + }; + + enum Face { + FRONT_AND_BACK, + FRONT, + BACK + }; + + PolygonMode(); + + PolygonMode(Face face,Mode mode); + + /** Copy constructor using CopyOp to manage deep vs shallow copy.*/ + PolygonMode(const PolygonMode& pm,const CopyOp& copyop=CopyOp::SHALLOW_COPY): + StateAttribute(pm,copyop), + _modeFront(pm._modeFront), + _modeBack(pm._modeBack) {} + + META_StateAttribute(osg, PolygonMode, POLYGONMODE); + + /** return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs.*/ + virtual int compare(const StateAttribute& sa) const + { + // check the types are equal and then create the rhs variable + // used by the COMPARE_StateAttribute_Parameter macros below. + COMPARE_StateAttribute_Types(PolygonMode,sa) + + // compare each parameter in turn against the rhs. + COMPARE_StateAttribute_Parameter(_modeFront) + COMPARE_StateAttribute_Parameter(_modeBack) + + return 0; // passed all the above comparison macros, must be equal. + } + + void setMode(Face face,Mode mode); + Mode getMode(Face face) const; + + inline bool getFrontAndBack() const { return _modeFront==_modeBack; } + + virtual void apply(State& state) const; + + protected: + + virtual ~PolygonMode(); + + Mode _modeFront; + Mode _modeBack; + +}; + +} + +#endif diff --git a/libs/include/android/osg/PolygonOffset b/libs/include/android/osg/PolygonOffset new file mode 100755 index 0000000..15ad397 --- /dev/null +++ b/libs/include/android/osg/PolygonOffset @@ -0,0 +1,99 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_POLYGONOFFSET +#define OSG_POLYGONOFFSET 1 + +#include + +#ifndef GL_POLYGON_OFFSET_LINE + #define GL_POLYGON_OFFSET_LINE 0x2A02 + #define GL_POLYGON_OFFSET_POINT 0x2A01 +#endif + +namespace osg { + +/** PolygonOffset - encapsulates the OpenGL glPolygonOffset state.*/ +class OSG_EXPORT PolygonOffset : public StateAttribute +{ + public : + + PolygonOffset(); + + PolygonOffset(float factor, float units); + + /** Copy constructor using CopyOp to manage deep vs shallow copy.*/ + PolygonOffset(const PolygonOffset& po,const CopyOp& copyop=CopyOp::SHALLOW_COPY): + StateAttribute(po,copyop), + _factor(po._factor), + _units(po._units) {} + + META_StateAttribute(osg, PolygonOffset, POLYGONOFFSET); + + /** return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs.*/ + virtual int compare(const StateAttribute& sa) const + { + // check the types are equal and then create the rhs variable + // used by the COMPARE_StateAttribute_Parameter macros below. + COMPARE_StateAttribute_Types(PolygonOffset,sa) + + // compare each parameter in turn against the rhs. + COMPARE_StateAttribute_Parameter(_factor) + COMPARE_StateAttribute_Parameter(_units) + + return 0; // passed all the above comparison macros, must be equal. + } + + virtual bool getModeUsage(StateAttribute::ModeUsage& usage) const + { + usage.usesMode(GL_POLYGON_OFFSET_FILL); +#if !defined(OSG_GLES1_AVAILABLE) && !defined(OSG_GLES2_AVAILABLE) + usage.usesMode(GL_POLYGON_OFFSET_LINE); + usage.usesMode(GL_POLYGON_OFFSET_POINT); +#endif + return true; + } + + inline void setFactor(float factor) { _factor = factor; } + inline float getFactor() const { return _factor; } + + inline void setUnits(float units) { _units = units; } + inline float getUnits() const { return _units; } + + virtual void apply(State& state) const; + + + static void setFactorMultiplier(float multiplier); + static float getFactorMultiplier(); + + static void setUnitsMultiplier(float multiplier); + static float getUnitsMultiplier(); + + static bool areFactorAndUnitsMultipliersSet(); + + /** Checks with the OpenGL driver to try and pick multiplier appropriate for the hardware. + note, requires a valid graphics context to be current. */ + static void setFactorAndUnitsMultipliersUsingBestGuessForDriver(); + + protected : + + virtual ~PolygonOffset(); + + float _factor; + float _units; + +}; + +} + +#endif diff --git a/libs/include/android/osg/PolygonStipple b/libs/include/android/osg/PolygonStipple new file mode 100755 index 0000000..8018698 --- /dev/null +++ b/libs/include/android/osg/PolygonStipple @@ -0,0 +1,68 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +// -*- Mode: c++ -*- + +#ifndef OSG_POLYGONSTIPPLE +#define OSG_POLYGONSTIPPLE 1 + +#include + +#ifndef GL_POLYGON_STIPPLE + #define GL_POLYGON_STIPPLE 0x0B42 +#endif + +namespace osg +{ + +class OSG_EXPORT PolygonStipple : public StateAttribute +{ + public : + + PolygonStipple(); + + PolygonStipple(const GLubyte* mask); + + /** Copy constructor using CopyOp to manage deep vs shallow copy.*/ + PolygonStipple(const PolygonStipple& lw,const CopyOp& copyop=CopyOp::SHALLOW_COPY); + + META_StateAttribute(osg, PolygonStipple, POLYGONSTIPPLE); + + /** return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs.*/ + virtual int compare(const StateAttribute& sa) const; + + virtual bool getModeUsage(StateAttribute::ModeUsage& usage) const + { + usage.usesMode(GL_POLYGON_STIPPLE); + return true; + } + + /** set the mask up, copying 128 bytes (32x32 bitfield) from mask into the local _mask.*/ + void setMask(const GLubyte* mask); + + /** get a pointer to the mask.*/ + inline const GLubyte* getMask() const {return _mask;} + + + virtual void apply(State& state) const; + + protected : + + virtual ~PolygonStipple(); + + GLubyte _mask[128]; + +}; + +} + +#endif diff --git a/libs/include/android/osg/Polytope b/libs/include/android/osg/Polytope new file mode 100755 index 0000000..1e9c0c7 --- /dev/null +++ b/libs/include/android/osg/Polytope @@ -0,0 +1,407 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_POLYTOPE +#define OSG_POLYTOPE 1 + +#include +#include + +namespace osg { + + +/** A Polytope class for representing convex clipping volumes made up of a set of planes. + * When adding planes, their normals should point inwards (into the volume) */ +class OSG_EXPORT Polytope +{ + + public: + + typedef unsigned int ClippingMask; + typedef std::vector PlaneList; + typedef std::vector VertexList; + typedef fast_back_stack MaskStack; + + inline Polytope() {setupMask();} + + inline Polytope(const Polytope& cv) : + _maskStack(cv._maskStack), + _resultMask(cv._resultMask), + _planeList(cv._planeList), + _referenceVertexList(cv._referenceVertexList) {} + + inline Polytope(const PlaneList& pl) : _planeList(pl) {setupMask();} + + inline ~Polytope() {} + + inline void clear() { _planeList.clear(); setupMask(); } + + inline Polytope& operator = (const Polytope& cv) + { + if (&cv==this) return *this; + _maskStack = cv._maskStack; + _resultMask = cv._resultMask; + _planeList = cv._planeList; + _referenceVertexList = cv._referenceVertexList; + return *this; + } + + /** Create a Polytope which is a cube, centered at 0,0,0, with sides of 2 units.*/ + void setToUnitFrustum(bool withNear=true, bool withFar=true) + { + _planeList.clear(); + _planeList.push_back(Plane(1.0,0.0,0.0,1.0)); // left plane. + _planeList.push_back(Plane(-1.0,0.0,0.0,1.0)); // right plane. + _planeList.push_back(Plane(0.0,1.0,0.0,1.0)); // bottom plane. + _planeList.push_back(Plane(0.0,-1.0,0.0,1.0)); // top plane. + if (withNear) _planeList.push_back(Plane(0.0,0.0,1.0,1.0)); // near plane + if (withFar) _planeList.push_back(Plane(0.0,0.0,-1.0,1.0)); // far plane + setupMask(); + } + + /** Create a Polytope which is a equivalent to BoundingBox.*/ + void setToBoundingBox(const BoundingBox& bb) + { + _planeList.clear(); + _planeList.push_back(Plane(1.0,0.0,0.0,-bb.xMin())); // left plane. + _planeList.push_back(Plane(-1.0,0.0,0.0,bb.xMax())); // right plane. + _planeList.push_back(Plane(0.0,1.0,0.0,-bb.yMin())); // bottom plane. + _planeList.push_back(Plane(0.0,-1.0,0.0,bb.yMax())); // top plane. + _planeList.push_back(Plane(0.0,0.0,1.0,-bb.zMin())); // near plane + _planeList.push_back(Plane(0.0,0.0,-1.0,bb.zMax())); // far plane + setupMask(); + } + + inline void setAndTransformProvidingInverse(const Polytope& pt, const osg::Matrix& matrix) + { + _referenceVertexList = pt._referenceVertexList; + + unsigned int resultMask = pt._maskStack.back(); + if (resultMask==0) + { + _maskStack.back() = 0; + _resultMask = 0; + _planeList.clear(); + return; + } + + ClippingMask selector_mask = 0x1; + + unsigned int numActivePlanes = 0; + + // count number of active planes. + PlaneList::const_iterator itr; + for(itr=pt._planeList.begin(); + itr!=pt._planeList.end(); + ++itr) + { + if (resultMask&selector_mask) ++numActivePlanes; + selector_mask <<= 1; + } + + _planeList.resize(numActivePlanes); + _resultMask = 0; + selector_mask = 0x1; + unsigned int index = 0; + for(itr=pt._planeList.begin(); + itr!=pt._planeList.end(); + ++itr) + { + if (resultMask&selector_mask) + { + _planeList[index] = *itr; + _planeList[index++].transformProvidingInverse(matrix); + _resultMask = (_resultMask<<1) | 1; + } + selector_mask <<= 1; + } + + _maskStack.back() = _resultMask; + } + + inline void set(const PlaneList& pl) { _planeList = pl; setupMask(); } + + + inline void add(const osg::Plane& pl) { _planeList.push_back(pl); setupMask(); } + + /** flip/reverse the orientation of all the planes.*/ + inline void flip() + { + for(PlaneList::iterator itr=_planeList.begin(); + itr!=_planeList.end(); + ++itr) + { + itr->flip(); + } + } + + inline bool empty() const { return _planeList.empty(); } + + inline PlaneList& getPlaneList() { return _planeList; } + + inline const PlaneList& getPlaneList() const { return _planeList; } + + + inline void setReferenceVertexList(VertexList& vertices) { _referenceVertexList=vertices; } + + inline VertexList& getReferenceVertexList() { return _referenceVertexList; } + + inline const VertexList& getReferenceVertexList() const { return _referenceVertexList; } + + + inline void setupMask() + { + _resultMask = 0; + for(unsigned int i=0;i<_planeList.size();++i) + { + _resultMask = (_resultMask<<1) | 1; + } + _maskStack.push_back(_resultMask); + } + + inline ClippingMask& getCurrentMask() { return _maskStack.back(); } + + inline ClippingMask getCurrentMask() const { return _maskStack.back(); } + + inline void setResultMask(ClippingMask mask) { _resultMask=mask; } + + inline ClippingMask getResultMask() const { return _resultMask; } + + MaskStack& getMaskStack() { return _maskStack; } + + const MaskStack& getMaskStack() const { return _maskStack; } + + + inline void pushCurrentMask() + { + _maskStack.push_back(_resultMask); + } + + inline void popCurrentMask() + { + _maskStack.pop_back(); + } + + /** Check whether a vertex is contained within clipping set.*/ + inline bool contains(const osg::Vec3& v) const + { + if (!_maskStack.back()) return true; + + unsigned int selector_mask = 0x1; + for(PlaneList::const_iterator itr=_planeList.begin(); + itr!=_planeList.end(); + ++itr) + { + if ((_maskStack.back()&selector_mask) && (itr->distance(v)<0.0f)) return false; + selector_mask <<= 1; + } + return true; + } + + /** Check whether any part of vertex list is contained within clipping set.*/ + inline bool contains(const std::vector& vertices) + { + if (!_maskStack.back()) return true; + + _resultMask = _maskStack.back(); + + for(std::vector::const_iterator vitr = vertices.begin(); + vitr != vertices.end(); + ++vitr) + { + const osg::Vec3& v = *vitr; + bool outside = false; + ClippingMask selector_mask = 0x1; + for(PlaneList::const_iterator itr=_planeList.begin(); + itr!=_planeList.end() && !outside; + ++itr) + { + if ((_maskStack.back()&selector_mask) && (itr->distance(v)<0.0f)) outside = true; + selector_mask <<= 1; + } + + if (!outside) return true; + } + return false; + } + + /** Check whether any part of a bounding sphere is contained within clipping set. + Using a mask to determine which planes should be used for the check, and + modifying the mask to turn off planes which wouldn't contribute to clipping + of any internal objects. This feature is used in osgUtil::CullVisitor + to prevent redundant plane checking.*/ + inline bool contains(const osg::BoundingSphere& bs) + { + if (!_maskStack.back()) return true; + + _resultMask = _maskStack.back(); + ClippingMask selector_mask = 0x1; + + for(PlaneList::const_iterator itr=_planeList.begin(); + itr!=_planeList.end(); + ++itr) + { + if (_resultMask&selector_mask) + { + int res=itr->intersect(bs); + if (res<0) return false; // outside clipping set. + else if (res>0) _resultMask ^= selector_mask; // subsequent checks against this plane not required. + } + selector_mask <<= 1; + } + return true; + } + + /** Check whether any part of a bounding box is contained within clipping set. + Using a mask to determine which planes should be used for the check, and + modifying the mask to turn off planes which wouldn't contribute to clipping + of any internal objects. This feature is used in osgUtil::CullVisitor + to prevent redundant plane checking.*/ + inline bool contains(const osg::BoundingBox& bb) + { + if (!_maskStack.back()) return true; + + _resultMask = _maskStack.back(); + ClippingMask selector_mask = 0x1; + + for(PlaneList::const_iterator itr=_planeList.begin(); + itr!=_planeList.end(); + ++itr) + { + if (_resultMask&selector_mask) + { + int res=itr->intersect(bb); + if (res<0) return false; // outside clipping set. + else if (res>0) _resultMask ^= selector_mask; // subsequent checks against this plane not required. + } + selector_mask <<= 1; + } + return true; + } + + /** Check whether all of vertex list is contained with clipping set.*/ + inline bool containsAllOf(const std::vector& vertices) + { + if (!_maskStack.back()) return false; + + _resultMask = _maskStack.back(); + ClippingMask selector_mask = 0x1; + + for(PlaneList::const_iterator itr=_planeList.begin(); + itr!=_planeList.end(); + ++itr) + { + if (_resultMask&selector_mask) + { + int res=itr->intersect(vertices); + if (res<1) return false; // intersects, or is below plane. + _resultMask ^= selector_mask; // subsequent checks against this plane not required. + } + selector_mask <<= 1; + } + return true; + } + + /** Check whether the entire bounding sphere is contained within clipping set.*/ + inline bool containsAllOf(const osg::BoundingSphere& bs) + { + if (!_maskStack.back()) return false; + + _resultMask = _maskStack.back(); + ClippingMask selector_mask = 0x1; + + for(PlaneList::const_iterator itr=_planeList.begin(); + itr!=_planeList.end(); + ++itr) + { + if (_resultMask&selector_mask) + { + int res=itr->intersect(bs); + if (res<1) return false; // intersects, or is below plane. + _resultMask ^= selector_mask; // subsequent checks against this plane not required. + } + selector_mask <<= 1; + } + return true; + } + + /** Check whether the entire bounding box is contained within clipping set.*/ + inline bool containsAllOf(const osg::BoundingBox& bb) + { + if (!_maskStack.back()) return false; + + _resultMask = _maskStack.back(); + ClippingMask selector_mask = 0x1; + + for(PlaneList::const_iterator itr=_planeList.begin(); + itr!=_planeList.end(); + ++itr) + { + if (_resultMask&selector_mask) + { + int res=itr->intersect(bb); + if (res<1) return false; // intersects, or is below plane. + _resultMask ^= selector_mask; // subsequent checks against this plane not required. + } + selector_mask <<= 1; + } + return true; + } + + + /** Transform the clipping set by matrix. Note, this operations carries out + * the calculation of the inverse of the matrix since a plane must + * be multiplied by the inverse transposed to transform it. This + * makes this operation expensive. If the inverse has been already + * calculated elsewhere then use transformProvidingInverse() instead. + * See http://www.worldserver.com/turk/computergraphics/NormalTransformations.pdf*/ + inline void transform(const osg::Matrix& matrix) + { + osg::Matrix inverse; + inverse.invert(matrix); + transformProvidingInverse(inverse); + } + + /** Transform the clipping set by provide a pre inverted matrix. + * see transform for details. */ + inline void transformProvidingInverse(const osg::Matrix& matrix) + { + if (!_maskStack.back()) return; + + _resultMask = _maskStack.back(); + ClippingMask selector_mask = 0x1; + for(PlaneList::iterator itr=_planeList.begin(); + itr!=_planeList.end(); + ++itr) + { + if (_resultMask&selector_mask) + { + itr->transformProvidingInverse(matrix); + selector_mask <<= 1; + } + } + } + + protected: + + + MaskStack _maskStack; + ClippingMask _resultMask; + PlaneList _planeList; + VertexList _referenceVertexList; + +}; + +} // end of namespace + +#endif diff --git a/libs/include/android/osg/PositionAttitudeTransform b/libs/include/android/osg/PositionAttitudeTransform new file mode 100755 index 0000000..61d74c6 --- /dev/null +++ b/libs/include/android/osg/PositionAttitudeTransform @@ -0,0 +1,78 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_POSITIONATTITUDETRANSFORM +#define OSG_POSITIONATTITUDETRANSFORM 1 + +#include +#include +#include +#include +#include + +namespace osg { + +/** PositionAttitudeTransform - is a Transform. Sets the coordinate transform + via a Vec3 position and Quat attitude. +*/ +class OSG_EXPORT PositionAttitudeTransform : public Transform +{ + public : + PositionAttitudeTransform(); + + PositionAttitudeTransform(const PositionAttitudeTransform& pat,const CopyOp& copyop=CopyOp::SHALLOW_COPY): + Transform(pat,copyop), + _position(pat._position), + _attitude(pat._attitude), + _scale(pat._scale), + _pivotPoint(pat._pivotPoint) {} + + + META_Node(osg, PositionAttitudeTransform); + + virtual PositionAttitudeTransform* asPositionAttitudeTransform() { return this; } + virtual const PositionAttitudeTransform* asPositionAttitudeTransform() const { return this; } + + inline void setPosition(const Vec3d& pos) { _position = pos; dirtyBound(); } + inline const Vec3d& getPosition() const { return _position; } + + + inline void setAttitude(const Quat& quat) { _attitude = quat; dirtyBound(); } + inline const Quat& getAttitude() const { return _attitude; } + + + inline void setScale(const Vec3d& scale) { _scale = scale; dirtyBound(); } + inline const Vec3d& getScale() const { return _scale; } + + + inline void setPivotPoint(const Vec3d& pivot) { _pivotPoint = pivot; dirtyBound(); } + inline const Vec3d& getPivotPoint() const { return _pivotPoint; } + + + virtual bool computeLocalToWorldMatrix(Matrix& matrix,NodeVisitor* nv) const; + virtual bool computeWorldToLocalMatrix(Matrix& matrix,NodeVisitor* nv) const; + + + protected : + + virtual ~PositionAttitudeTransform() {} + + Vec3d _position; + Quat _attitude; + Vec3d _scale; + Vec3d _pivotPoint; +}; + +} + +#endif diff --git a/libs/include/android/osg/PrimitiveRestartIndex b/libs/include/android/osg/PrimitiveRestartIndex new file mode 100755 index 0000000..5872311 --- /dev/null +++ b/libs/include/android/osg/PrimitiveRestartIndex @@ -0,0 +1,93 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_PRIMITIVERESTARTINDEX +#define OSG_PRIMITIVERESTARTINDEX 1 + +#include + +namespace osg { + +/** + * osg::PrimitiveRestartIndex does nothing if OpenGL 3.1 is not available. +*/ +class OSG_EXPORT PrimitiveRestartIndex : public StateAttribute +{ + public : + + PrimitiveRestartIndex(); + PrimitiveRestartIndex(unsigned int restartIndex); + + /** Copy constructor using CopyOp to manage deep vs shallow copy.*/ + PrimitiveRestartIndex(const PrimitiveRestartIndex& primitiveRestartIndex,const CopyOp& copyop=CopyOp::SHALLOW_COPY); + + META_StateAttribute(osg, PrimitiveRestartIndex, PRIMITIVERESTARTINDEX) + + /** return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs.*/ + virtual int compare(const StateAttribute& sa) const; + + inline void setRestartIndex(unsigned int restartIndex ) { _restartIndex = restartIndex; } + + inline unsigned int getRestartIndex() const { return _restartIndex; } + + virtual void apply(State& state) const; + + public: + + /** Extensions class which encapsulates the querying of extensions and + * associated function pointers, and provide convenience wrappers to + * check for the extensions or use the associated functions. + */ + class OSG_EXPORT Extensions : public osg::Referenced + { + public: + Extensions(unsigned int contextID); + + Extensions(const Extensions& rhs); + + void lowestCommonDenominator(const Extensions& rhs); + + void setupGLExtensions(unsigned int contextID); + + bool isOpenGL31Supported() const { return _isOpenGL31Supported; } + bool isPrimitiveRestartIndexNVSupported() const { return _isPrimitiveRestartIndexNVSupported; } + + void glPrimitiveRestartIndex( GLuint index ) const; + + protected: + + ~Extensions() {} + + bool _isOpenGL31Supported; + bool _isPrimitiveRestartIndexNVSupported; + + typedef void (GL_APIENTRY * PrimitiveRestartIndex)( GLuint index ); + + PrimitiveRestartIndex _glPrimitiveRestartIndex; + }; + + static Extensions* getExtensions(unsigned int contextID,bool createIfNotInitalized); + + static void setExtensions(unsigned int contextID,Extensions* extensions); + + + protected: + + virtual ~PrimitiveRestartIndex(); + + unsigned int _restartIndex; +}; + +} + +#endif diff --git a/libs/include/android/osg/PrimitiveSet b/libs/include/android/osg/PrimitiveSet new file mode 100755 index 0000000..5948a86 --- /dev/null +++ b/libs/include/android/osg/PrimitiveSet @@ -0,0 +1,569 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_PRIMITIVESET +#define OSG_PRIMITIVESET 1 + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include + +namespace osg { + +typedef MixinVector VectorGLsizei; +typedef MixinVector VectorGLubyte; +typedef MixinVector VectorGLushort; +typedef MixinVector VectorGLuint; + +class State; + +/** A \c PrimitiveFunctor is used (in conjunction with + * osg::Drawable::accept (PrimitiveFunctor&)) to get access to the + * primitives that compose the things drawn by OSG. + *

If \c osg::Drawable::accept() is called with a \c PrimitiveFunctor + * parameter, the \c Drawable will "pretend" it is drawing itself, but instead + * of calling real OpenGL functions, it will call PrimitiveFunctor's + * member functions that "mimic" the OpenGL calls. + *

Concrete subclasses of \c PrimitiveFunctor must implement these methods + * so that they performs whatever they want. + */ +class PrimitiveFunctor +{ +public: + + virtual ~PrimitiveFunctor() {} + + /** Sets the array of vertices used to describe the primitives. Somehow + * mimics the OpenGL \c glVertexPointer() function. + */ + virtual void setVertexArray(unsigned int count,const Vec2* vertices) = 0; + + /** Sets the array of vertices used to describe the primitives. Somehow + * mimics the OpenGL \c glVertexPointer() function. + */ + virtual void setVertexArray(unsigned int count,const Vec3* vertices) = 0; + + /** Sets the array of vertices used to describe the primitives. Somehow + * mimics the OpenGL \c glVertexPointer() function. + */ + virtual void setVertexArray(unsigned int count,const Vec4* vertices) = 0; + + /** Sets the array of vertices used to describe the primitives. Somehow + * mimics the OpenGL \c glVertexPointer() function. + */ + virtual void setVertexArray(unsigned int count,const Vec2d* vertices) = 0; + + /** Sets the array of vertices used to describe the primitives. Somehow + * mimics the OpenGL \c glVertexPointer() function. + */ + virtual void setVertexArray(unsigned int count,const Vec3d* vertices) = 0; + + /** Sets the array of vertices used to describe the primitives. Somehow + * mimics the OpenGL \c glVertexPointer() function. + */ + virtual void setVertexArray(unsigned int count,const Vec4d* vertices) = 0; + + /// Mimics the OpenGL \c glDrawArrays() function. + virtual void drawArrays(GLenum mode,GLint first,GLsizei count) = 0; + + /// Mimics the OpenGL \c glDrawElements() function. + virtual void drawElements(GLenum mode,GLsizei count,const GLubyte* indices) = 0; + + /// Mimics the OpenGL \c glDrawElements() function. + virtual void drawElements(GLenum mode,GLsizei count,const GLushort* indices) = 0; + + /// Mimics the OpenGL \c glDrawElements() function. + virtual void drawElements(GLenum mode,GLsizei count,const GLuint* indices) = 0; + + /// Mimics the OpenGL \c glBegin() function. + virtual void begin(GLenum mode) = 0; + + /// Mimics the OpenGL \c glVertex() "family of functions". + virtual void vertex(const Vec2& vert) = 0; + + /// Mimics the OpenGL \c glVertex() "family of functions". + virtual void vertex(const Vec3& vert) = 0; + + /// Mimics the OpenGL \c glVertex() "family of functions". + virtual void vertex(const Vec4& vert) = 0; + + /// Mimics the OpenGL \c glVertex() "family of functions". + virtual void vertex(float x,float y) = 0; + + /// Mimics the OpenGL \c glVertex() "family of functions". + virtual void vertex(float x,float y,float z) = 0; + + /// Mimics the OpenGL \c glVertex() "family of functions". + virtual void vertex(float x,float y,float z,float w) = 0; + + /// Mimics the OpenGL \c glEnd() function. + virtual void end() = 0; +}; + +class PrimitiveIndexFunctor +{ +public: + + virtual ~PrimitiveIndexFunctor() {} + + virtual void setVertexArray(unsigned int count,const Vec2* vertices) = 0; + virtual void setVertexArray(unsigned int count,const Vec3* vertices) = 0; + virtual void setVertexArray(unsigned int count,const Vec4* vertices) = 0; + + virtual void setVertexArray(unsigned int count,const Vec2d* vertices) = 0; + virtual void setVertexArray(unsigned int count,const Vec3d* vertices) = 0; + virtual void setVertexArray(unsigned int count,const Vec4d* vertices) = 0; + + virtual void drawArrays(GLenum mode,GLint first,GLsizei count) = 0; + virtual void drawElements(GLenum mode,GLsizei count,const GLubyte* indices) = 0; + virtual void drawElements(GLenum mode,GLsizei count,const GLushort* indices) = 0; + virtual void drawElements(GLenum mode,GLsizei count,const GLuint* indices) = 0; + + virtual void begin(GLenum mode) = 0; + virtual void vertex(unsigned int pos) = 0; + virtual void end() = 0; +}; + +class DrawElements; + +class OSG_EXPORT PrimitiveSet : public BufferData +{ + public: + + enum Type + { + PrimitiveType, + DrawArraysPrimitiveType, + DrawArrayLengthsPrimitiveType, + DrawElementsUBytePrimitiveType, + DrawElementsUShortPrimitiveType, + DrawElementsUIntPrimitiveType + }; + + enum Mode + { + POINTS = GL_POINTS, + LINES = GL_LINES, + LINE_STRIP = GL_LINE_STRIP, + LINE_LOOP = GL_LINE_LOOP, + TRIANGLES = GL_TRIANGLES, + TRIANGLE_STRIP = GL_TRIANGLE_STRIP, + TRIANGLE_FAN = GL_TRIANGLE_FAN, + QUADS = GL_QUADS, + QUAD_STRIP = GL_QUAD_STRIP, + POLYGON = GL_POLYGON, + LINES_ADJACENCY = GL_LINES_ADJACENCY_EXT, + LINE_STRIP_ADJACENCY = GL_LINE_STRIP_ADJACENCY_EXT, + TRIANGLES_ADJACENCY = GL_TRIANGLES_ADJACENCY_EXT, + TRIANGLE_STRIP_ADJACENCY = GL_TRIANGLE_STRIP_ADJACENCY_EXT, + PATCHES = GL_PATCHES + }; + + PrimitiveSet(Type primType=PrimitiveType,GLenum mode=0, int numInstances=0): + _primitiveType(primType), + _numInstances(numInstances), + _mode(mode) {} + + PrimitiveSet(const PrimitiveSet& prim,const CopyOp& copyop=CopyOp::SHALLOW_COPY): + BufferData(prim,copyop), + _primitiveType(prim._primitiveType), + _numInstances(prim._numInstances), + _mode(prim._mode) {} + + virtual bool isSameKindAs(const Object* obj) const { return dynamic_cast(obj)!=NULL; } + virtual const char* libraryName() const { return "osg"; } + virtual const char* className() const { return "PrimitiveSet"; } + + Type getType() const { return _primitiveType; } + + virtual osg::PrimitiveSet* asPrimitiveSet() { return this; } + virtual const osg::PrimitiveSet* asPrimitiveSet() const { return this; } + + virtual const GLvoid* getDataPointer() const { return 0; } + virtual unsigned int getTotalDataSize() const { return 0; } + virtual bool supportsBufferObject() const { return false; } + + virtual DrawElements* getDrawElements() { return 0; } + virtual const DrawElements* getDrawElements() const { return 0; } + + void setNumInstances(int n) { _numInstances = n; } + int getNumInstances() const { return _numInstances; } + + void setMode(GLenum mode) { _mode = mode; } + GLenum getMode() const { return _mode; } + + virtual void draw(State& state, bool useVertexBufferObjects) const = 0; + + virtual void accept(PrimitiveFunctor& functor) const = 0; + virtual void accept(PrimitiveIndexFunctor& functor) const = 0; + + virtual unsigned int index(unsigned int pos) const = 0; + virtual unsigned int getNumIndices() const = 0; + virtual void offsetIndices(int offset) = 0; + + virtual unsigned int getNumPrimitives() const; + + virtual void computeRange() const {} + + protected: + + virtual ~PrimitiveSet() {} + + Type _primitiveType; + int _numInstances; + GLenum _mode; +}; + +class OSG_EXPORT DrawArrays : public PrimitiveSet +{ + public: + + DrawArrays(GLenum mode=0): + PrimitiveSet(DrawArraysPrimitiveType,mode), + _first(0), + _count(0) {} + + DrawArrays(GLenum mode, GLint first, GLsizei count, int numInstances=0): + PrimitiveSet(DrawArraysPrimitiveType, mode, numInstances), + _first(first), + _count(count) {} + + DrawArrays(const DrawArrays& da,const CopyOp& copyop=CopyOp::SHALLOW_COPY): + PrimitiveSet(da,copyop), + _first(da._first), + _count(da._count) {} + + virtual Object* cloneType() const { return new DrawArrays(); } + virtual Object* clone(const CopyOp& copyop) const { return new DrawArrays(*this,copyop); } + virtual bool isSameKindAs(const Object* obj) const { return dynamic_cast(obj)!=NULL; } + virtual const char* libraryName() const { return "osg"; } + virtual const char* className() const { return "DrawArrays"; } + + + void set(GLenum mode,GLint first, GLsizei count) + { + _mode = mode; + _first = first; + _count = count; + } + + void setFirst(GLint first) { _first = first; } + GLint getFirst() const { return _first; } + + void setCount(GLsizei count) { _count = count; } + GLsizei getCount() const { return _count; } + + virtual void draw(State& state, bool useVertexBufferObjects) const; + + virtual void accept(PrimitiveFunctor& functor) const; + virtual void accept(PrimitiveIndexFunctor& functor) const; + + virtual unsigned int getNumIndices() const { return static_cast(_count); } + virtual unsigned int index(unsigned int pos) const { return static_cast(_first)+pos; } + virtual void offsetIndices(int offset) { _first += offset; } + + protected: + + virtual ~DrawArrays() {} + + GLint _first; + GLsizei _count; +}; + +class OSG_EXPORT DrawArrayLengths : public PrimitiveSet, public VectorGLsizei +{ + public: + + typedef VectorGLsizei vector_type; + + DrawArrayLengths(GLenum mode=0): + PrimitiveSet(DrawArrayLengthsPrimitiveType,mode), + _first(0) {} + + DrawArrayLengths(const DrawArrayLengths& dal,const CopyOp& copyop=CopyOp::SHALLOW_COPY): + PrimitiveSet(dal,copyop), + vector_type(dal), + _first(dal._first) {} + + DrawArrayLengths(GLenum mode, GLint first, unsigned int no, GLsizei* ptr) : + PrimitiveSet(DrawArrayLengthsPrimitiveType,mode), + vector_type(ptr,ptr+no), + _first(first) {} + + DrawArrayLengths(GLenum mode,GLint first, unsigned int no) : + PrimitiveSet(DrawArrayLengthsPrimitiveType,mode), + vector_type(no), + _first(first) {} + + DrawArrayLengths(GLenum mode,GLint first) : + PrimitiveSet(DrawArrayLengthsPrimitiveType,mode), + vector_type(), + _first(first) {} + + + virtual Object* cloneType() const { return new DrawArrayLengths(); } + virtual Object* clone(const CopyOp& copyop) const { return new DrawArrayLengths(*this,copyop); } + virtual bool isSameKindAs(const Object* obj) const { return dynamic_cast(obj)!=NULL; } + virtual const char* libraryName() const { return "osg"; } + virtual const char* className() const { return "DrawArrayLengths"; } + + + void setFirst(GLint first) { _first = first; } + GLint getFirst() const { return _first; } + + virtual void draw(State& state, bool useVertexBufferObjects) const; + + virtual void accept(PrimitiveFunctor& functor) const; + virtual void accept(PrimitiveIndexFunctor& functor) const; + + virtual unsigned int getNumIndices() const; + virtual unsigned int index(unsigned int pos) const { return _first+pos; } + virtual void offsetIndices(int offset) { _first += offset; } + + virtual unsigned int getNumPrimitives() const; + + protected: + + virtual ~DrawArrayLengths() {} + + GLint _first; +}; + +class DrawElements : public PrimitiveSet +{ + public: + + DrawElements(Type primType=PrimitiveType, GLenum mode=0, int numInstances=0): + PrimitiveSet(primType,mode, numInstances) {} + + DrawElements(const DrawElements& copy,const CopyOp& copyop=CopyOp::SHALLOW_COPY): + PrimitiveSet(copy,copyop) {} + + + virtual DrawElements* getDrawElements() { return this; } + virtual const DrawElements* getDrawElements() const { return this; } + + /** Set the ElementBufferObject.*/ + inline void setElementBufferObject(osg::ElementBufferObject* ebo) { setBufferObject(ebo); } + + /** Get the ElementBufferObject. If no EBO is assigned returns NULL*/ + inline osg::ElementBufferObject* getElementBufferObject() { return dynamic_cast(_bufferObject.get()); } + + /** Get the const ElementBufferObject. If no EBO is assigned returns NULL*/ + inline const osg::ElementBufferObject* getElementBufferObject() const { return dynamic_cast(_bufferObject.get()); } + + virtual void reserveElements(unsigned int numIndices) = 0; + virtual void setElement(unsigned int, unsigned int) = 0; + virtual unsigned int getElement(unsigned int) = 0; + virtual void addElement(unsigned int) = 0; + + protected: + + virtual ~DrawElements() {} +}; + +class OSG_EXPORT DrawElementsUByte : public DrawElements, public VectorGLubyte +{ + public: + + typedef VectorGLubyte vector_type; + + DrawElementsUByte(GLenum mode=0): + DrawElements(DrawElementsUBytePrimitiveType,mode) {} + + DrawElementsUByte(const DrawElementsUByte& array, const CopyOp& copyop=CopyOp::SHALLOW_COPY): + DrawElements(array,copyop), + vector_type(array) {} + + /** + * \param no Number of intended elements. This will be the size of the underlying vector. + */ + DrawElementsUByte(GLenum mode, unsigned int no, const GLubyte* ptr, int numInstances=0) : + DrawElements(DrawElementsUBytePrimitiveType,mode,numInstances), + vector_type(ptr,ptr+no) {} + + /** + * \param no Number of intended elements. This will be the size of the underlying vector. + */ + DrawElementsUByte(GLenum mode, unsigned int no) : + DrawElements(DrawElementsUBytePrimitiveType,mode), + vector_type(no) {} + + virtual Object* cloneType() const { return new DrawElementsUByte(); } + virtual Object* clone(const CopyOp& copyop) const { return new DrawElementsUByte(*this,copyop); } + virtual bool isSameKindAs(const Object* obj) const { return dynamic_cast(obj)!=NULL; } + virtual const char* libraryName() const { return "osg"; } + virtual const char* className() const { return "DrawElementsUByte"; } + + virtual const GLvoid* getDataPointer() const { return empty()?0:&front(); } + virtual unsigned int getTotalDataSize() const { return static_cast(size()); } + virtual bool supportsBufferObject() const { return false; } + + virtual void draw(State& state, bool useVertexBufferObjects) const ; + + virtual void accept(PrimitiveFunctor& functor) const; + virtual void accept(PrimitiveIndexFunctor& functor) const; + + virtual unsigned int getNumIndices() const { return static_cast(size()); } + virtual unsigned int index(unsigned int pos) const { return (*this)[pos]; } + virtual void offsetIndices(int offset); + + virtual void reserveElements(unsigned int numIndices) { reserve(numIndices); } + virtual void setElement(unsigned int i, unsigned int v) { (*this)[i] = v; } + virtual unsigned int getElement(unsigned int i) { return (*this)[i]; } + virtual void addElement(unsigned int v) { push_back(GLubyte(v)); } + + protected: + + virtual ~DrawElementsUByte(); +}; + + +class OSG_EXPORT DrawElementsUShort : public DrawElements, public VectorGLushort +{ + public: + + typedef VectorGLushort vector_type; + + DrawElementsUShort(GLenum mode=0): + DrawElements(DrawElementsUShortPrimitiveType,mode) {} + + DrawElementsUShort(const DrawElementsUShort& array,const CopyOp& copyop=CopyOp::SHALLOW_COPY): + DrawElements(array,copyop), + vector_type(array) {} + + /** + * \param no Number of intended elements. This will be the size of the underlying vector. + */ + DrawElementsUShort(GLenum mode, unsigned int no, const GLushort* ptr, int numInstances=0) : + DrawElements(DrawElementsUShortPrimitiveType,mode,numInstances), + vector_type(ptr,ptr+no) {} + + /** + * \param no Number of intended elements. This will be the size of the underlying vector. + */ + DrawElementsUShort(GLenum mode, unsigned int no) : + DrawElements(DrawElementsUShortPrimitiveType,mode), + vector_type(no) {} + + template + DrawElementsUShort(GLenum mode, InputIterator first,InputIterator last) : + DrawElements(DrawElementsUShortPrimitiveType,mode), + vector_type(first,last) {} + + virtual Object* cloneType() const { return new DrawElementsUShort(); } + virtual Object* clone(const CopyOp& copyop) const { return new DrawElementsUShort(*this,copyop); } + virtual bool isSameKindAs(const Object* obj) const { return dynamic_cast(obj)!=NULL; } + virtual const char* libraryName() const { return "osg"; } + virtual const char* className() const { return "DrawElementsUShort"; } + + virtual const GLvoid* getDataPointer() const { return empty()?0:&front(); } + virtual unsigned int getTotalDataSize() const { return 2u*static_cast(size()); } + virtual bool supportsBufferObject() const { return false; } + + virtual void draw(State& state, bool useVertexBufferObjects) const; + + virtual void accept(PrimitiveFunctor& functor) const; + virtual void accept(PrimitiveIndexFunctor& functor) const; + + virtual unsigned int getNumIndices() const { return static_cast(size()); } + virtual unsigned int index(unsigned int pos) const { return (*this)[pos]; } + virtual void offsetIndices(int offset); + + virtual void reserveElements(unsigned int numIndices) { reserve(numIndices); } + virtual void setElement(unsigned int i, unsigned int v) { (*this)[i] = v; } + virtual unsigned int getElement(unsigned int i) { return (*this)[i]; } + virtual void addElement(unsigned int v) { push_back(GLushort(v)); } + + protected: + + virtual ~DrawElementsUShort(); +}; + +class OSG_EXPORT DrawElementsUInt : public DrawElements, public VectorGLuint +{ + public: + + typedef VectorGLuint vector_type; + + DrawElementsUInt(GLenum mode=0): + DrawElements(DrawElementsUIntPrimitiveType,mode) {} + + DrawElementsUInt(const DrawElementsUInt& array,const CopyOp& copyop=CopyOp::SHALLOW_COPY): + DrawElements(array,copyop), + vector_type(array) {} + + /** + * \param mode One of osg::PrimitiveSet::Mode. Determines the type of primitives used. + * \param no Number of intended elements. This will be the size of the underlying vector. + */ + DrawElementsUInt(GLenum mode, unsigned int no, const GLuint* ptr, int numInstances=0) : + DrawElements(DrawElementsUIntPrimitiveType,mode,numInstances), + vector_type(ptr,ptr+no) {} + + /** + * \param no Number of intended elements. This will be the size of the underlying vector. + */ + DrawElementsUInt(GLenum mode, unsigned int no) : + DrawElements(DrawElementsUIntPrimitiveType,mode), + vector_type(no) {} + + template + DrawElementsUInt(GLenum mode, InputIterator first,InputIterator last) : + DrawElements(DrawElementsUIntPrimitiveType,mode), + vector_type(first,last) {} + + virtual Object* cloneType() const { return new DrawElementsUInt(); } + virtual Object* clone(const CopyOp& copyop) const { return new DrawElementsUInt(*this,copyop); } + virtual bool isSameKindAs(const Object* obj) const { return dynamic_cast(obj)!=NULL; } + virtual const char* libraryName() const { return "osg"; } + virtual const char* className() const { return "DrawElementsUInt"; } + + virtual const GLvoid* getDataPointer() const { return empty()?0:&front(); } + virtual unsigned int getTotalDataSize() const { return 4u*static_cast(size()); } + virtual bool supportsBufferObject() const { return false; } + + virtual void draw(State& state, bool useVertexBufferObjects) const; + + virtual void accept(PrimitiveFunctor& functor) const; + virtual void accept(PrimitiveIndexFunctor& functor) const; + + virtual unsigned int getNumIndices() const { return static_cast(size()); } + virtual unsigned int index(unsigned int pos) const { return (*this)[pos]; } + virtual void offsetIndices(int offset); + + virtual void reserveElements(unsigned int numIndices) { reserve(numIndices); } + virtual void setElement(unsigned int i, unsigned int v) { (*this)[i] = v; } + virtual unsigned int getElement(unsigned int i) { return (*this)[i]; } + virtual void addElement(unsigned int v) { push_back(GLuint(v)); } + + protected: + + virtual ~DrawElementsUInt(); +}; + +} + +#endif diff --git a/libs/include/android/osg/Program b/libs/include/android/osg/Program new file mode 100755 index 0000000..d899e05 --- /dev/null +++ b/libs/include/android/osg/Program @@ -0,0 +1,403 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * Copyright (C) 2003-2005 3Dlabs Inc. Ltd. + * Copyright (C) 2004-2005 Nathan Cournia + * Copyright (C) 2008 Zebra Imaging + * Copyright (C) 2010 Vires Simulationstechnologie GmbH + * + * This application is open source and may be redistributed and/or modified + * freely and without restriction, both in commercial and non commercial + * applications, as long as this copyright notice is maintained. + * + * This application is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. +*/ + +/* file: include/osg/Program + * author: Mike Weiblen 2008-01-02 + * Holger Helmich 2010-10-21 +*/ + +#ifndef OSG_PROGRAM +#define OSG_PROGRAM 1 + +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace osg { + +class State; + + +/////////////////////////////////////////////////////////////////////////// +/** osg::Program is an application-level abstraction of an OpenGL glProgram. + * It is an osg::StateAttribute that, when applied, will activate a + * glProgram for subsequent rendering. + * osg::Shaders containing the actual shader source code are + * attached to a Program, which will then manage the compilation, + * linking, and activation of the GLSL program. + * osg::Program will automatically manage per-context instancing of the + * OpenGL glPrograms, if that is necessary for a particular display + * configuration. + */ + +class OSG_EXPORT Program : public osg::StateAttribute +{ + public: + Program(); + + /** Copy constructor using CopyOp to manage deep vs shallow copy.*/ + Program(const Program& rhs, const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY); + + META_StateAttribute(osg, Program, PROGRAM); + + /** return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs.*/ + virtual int compare(const osg::StateAttribute& sa) const; + + /** If enabled, activate our program in the GL pipeline, + * performing any rebuild operations that might be pending. */ + virtual void apply(osg::State& state) const; + + /** Set whether to use a mutex to ensure ref() and unref() are thread safe.*/ + virtual void setThreadSafeRefUnref(bool threadSafe); + + /** Compile program and associated shaders.*/ + virtual void compileGLObjects(osg::State& state) const; + + /** Resize any per context GLObject buffers to specified size. */ + virtual void resizeGLObjectBuffers(unsigned int maxSize); + + /** release OpenGL objects in specified graphics context if State + object is passed, otherwise release OpenGL objects for all graphics context if + State object pointer NULL.*/ + virtual void releaseGLObjects(osg::State* state=0) const; + + /** Mark our PCSOs as needing relink */ + void dirtyProgram(); + + /** Attach an osg::Shader to this osg::Program. + * Mark Program as needing relink. Return true for success */ + bool addShader( Shader* shader ); + + unsigned int getNumShaders() const { return static_cast(_shaderList.size()); } + + Shader* getShader( unsigned int i ) { return _shaderList[i].get(); } + const Shader* getShader( unsigned int i ) const { return _shaderList[i].get(); } + + /** Remove osg::Shader from this osg::Program. + * Mark Program as needing relink. Return true for success */ + bool removeShader( Shader* shader ); + + /** Set/get GL program parameters */ + void setParameter( GLenum pname, GLint value ); + GLint getParameter( GLenum pname ) const; + + /** Set/get compute shader work groups */ + void setComputeGroups( GLint numGroupsX, GLint numGroupsY, GLint numGroupsZ ); + void getComputeGroups( GLint& numGroupsX, GLint& numGroupsY, GLint& numGroupsZ ) const; + + /** Add an attribute location binding. */ + void addBindAttribLocation( const std::string& name, GLuint index ); + + /** Remove an attribute location binding. */ + void removeBindAttribLocation( const std::string& name ); + + /** Add an frag data location binding. See EXT_gpu_shader4 for BindFragDataLocationEXT */ + void addBindFragDataLocation( const std::string& name, GLuint index ); + + /** Remove an frag data location binding. */ + void removeBindFragDataLocation( const std::string& name ); + + /** Add a uniform block binding to an index target. XXX This + * should not be an attribute of the program. It should be a + * pseudo-uniform that can live in StateSet objects because + * it is cheap to set. */ + void addBindUniformBlock(const std::string& name, GLuint index); + + /** Remove a uniform block binding. */ + void removeBindUniformBlock(const std::string& name); + + /** Simple class for wrapping up the data used in glProgramBinary and glGetProgramBinary. + * On the first run of your application Programs should be assigned an empty ProgramBinary. + * Before your application exits it should retrieve the program binary via + * Program::PerContextProgram::compileProgramBinary and save it to disk. + * When your application is run subsequently, load your binary from disk and use it to set + * the data of a ProgramBinary, and set the ProgramBinary on the associated Program. + * This will typically result in Program::compileGLObjects executing much faster.*/ + class OSG_EXPORT ProgramBinary : public osg::Object + { + public: + + ProgramBinary(); + + /** Copy constructor using CopyOp to manage deep vs shallow copy.*/ + ProgramBinary(const ProgramBinary& rhs, const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY); + + META_Object(osg, ProgramBinary); + + /** Allocated a data buffer of specified size/*/ + void allocate(unsigned int size); + + /** Assign program binary data, copying the specified data into locally stored data buffer, the original data can then be deleted.*/ + void assign(unsigned int size, const unsigned char* data); + + /** Set the format of the program binary data.*/ + void setFormat(GLenum format) {_format = format;} + + /** Get the format of the program binary data.*/ + GLenum getFormat() const {return _format;} + + /** Get the size of the program binary data.*/ + unsigned int getSize() const { return static_cast(_data.size()); } + + /** Get a ptr to the program binary data.*/ + unsigned char* getData() { return _data.empty() ? 0 : &(_data.front()); } + + /** Get a const ptr to the program binary data.*/ + const unsigned char* getData() const { return _data.empty() ? 0 : &(_data.front()); } + + protected: + std::vector _data; + GLenum _format; + }; + + + /** Set the Program using a ProgramBinary. If a ProgramBinary is not yet + * available then setting an empty one signals that compileProgramBinary + * will be called later.*/ + void setProgramBinary(ProgramBinary* programBinary) { _programBinary = programBinary; } + + /** Get the Program's ProgramBinary, return NULL if none is assigned. */ + ProgramBinary* getProgramBinary() { return _programBinary.get(); } + + /** Get the const Program's ProgramBinary, return NULL if none is assigned. */ + const ProgramBinary* getProgramBinary() const { return _programBinary.get(); } + + typedef std::map AttribBindingList; + typedef std::map FragDataBindingList; + typedef std::map UniformBlockBindingList; + + const AttribBindingList& getAttribBindingList() const { return _attribBindingList; } + const FragDataBindingList& getFragDataBindingList() const { return _fragDataBindingList; } + const UniformBlockBindingList& getUniformBlockBindingList() const { return _uniformBlockBindingList; } + + /** Return true if this Program represents "fixed-functionality" rendering */ + bool isFixedFunction() const; + + /** Query InfoLog from a glProgram */ + bool getGlProgramInfoLog(unsigned int contextID, std::string& log) const; + + /** Mark internal glProgram for deletion. + * Deletion requests are queued until they can be executed + * in the proper GL context. */ + static void deleteGlProgram(unsigned int contextID, GLuint program); + + /** flush all the cached glPrograms which need to be deleted + * in the OpenGL context related to contextID.*/ + static void flushDeletedGlPrograms(unsigned int contextID,double currentTime, double& availableTime); + + /** discard all the cached glPrograms which need to be deleted + * in the OpenGL context related to contextID. + * Note, unlike flush no OpenGL calls are made, instead the handles are all removed. + * this call is useful for when an OpenGL context has been destroyed. */ + static void discardDeletedGlPrograms(unsigned int contextID); + + struct ActiveVarInfo { + ActiveVarInfo() : _location(-1), _type(Uniform::UNDEFINED), _size(-1) {} + ActiveVarInfo( GLint loc, GLenum type, GLint size ) : _location(loc), _type(type), _size(size) {} + GLint _location; + GLenum _type; + GLint _size; + }; + typedef std::map< unsigned int, ActiveVarInfo > ActiveUniformMap; + typedef std::map< std::string, ActiveVarInfo > ActiveVarInfoMap; + const ActiveUniformMap& getActiveUniforms(unsigned int contextID) const; + const ActiveVarInfoMap& getActiveAttribs(unsigned int contextID) const; + struct UniformBlockInfo + { + UniformBlockInfo() : _index(GL_INVALID_INDEX), _size(0) {} + UniformBlockInfo(GLuint index, GLsizei size) + : _index(index), _size(size) + { + } + GLuint _index; + GLsizei _size; + }; + typedef std::map UniformBlockMap; + const UniformBlockMap& getUniformBlocks(unsigned contextID) const; + public: + + // make PerContextProgram a friend to allow it access Program's protected + // methods and member variables. + class PerContextProgram; + friend class PerContextProgram; + + /** PerContextProgram (PCP) is an OSG-internal encapsulation of glPrograms per-GL context. */ + class OSG_EXPORT PerContextProgram : public osg::Referenced + { + public: + /** Use "0" as programHandle to let the PeContextProgram execute "glCreateProgram"and "glDeleteProgram" */ + PerContextProgram(const Program* program, unsigned int contextID, GLuint programHandle=0); + + GLuint getHandle() const {return _glProgramHandle;} + + void requestLink(); + virtual void linkProgram(osg::State& state); + virtual bool validateProgram(); + bool needsLink() const {return _needsLink;} + bool isLinked() const {return _isLinked;} + virtual bool getInfoLog( std::string& infoLog ) const; + + /** Was glProgramBinary called successfully? */ + bool loadedBinary() const {return _loadedBinary;} + + /** Compile a program binary. For this to work setProgramBinary must have + * been called on the osg::Program with an empty ProgramBinary prior to + * compileGLObjects being called. + * compileProgramBinary should be called after the program has been + * "exercised" by rendering with it. The ProgramBinary can then be saved + * to disk for faster subsequent compiling. */ + virtual ProgramBinary* compileProgramBinary(osg::State& state); + + virtual void useProgram() const; + + void resetAppliedUniforms() const + { + _lastAppliedUniformList.clear(); + } + + + inline void apply(const Uniform& uniform) const + { + GLint location = getUniformLocation(uniform.getNameID()); + if (location>=0) + { + const Uniform* lastAppliedUniform = _lastAppliedUniformList[location].first.get(); + if (lastAppliedUniform != &uniform) + { + // new attribute + uniform.apply(_extensions.get(),location); + _lastAppliedUniformList[location].first = &uniform; + _lastAppliedUniformList[location].second = uniform.getModifiedCount(); + } + else if (_lastAppliedUniformList[location].second != uniform.getModifiedCount()) + { + // existing attribute has been modified + uniform.apply(_extensions.get(),location); + _lastAppliedUniformList[location].first = &uniform; + _lastAppliedUniformList[location].second = uniform.getModifiedCount(); + } + } + } + + const ActiveUniformMap& getActiveUniforms() const {return _uniformInfoMap;} + const ActiveVarInfoMap& getActiveAttribs() const {return _attribInfoMap;} + const UniformBlockMap& getUniformBlocks() const {return _uniformBlockMap; } + inline GLint getUniformLocation( unsigned int uniformNameID ) const { ActiveUniformMap::const_iterator itr = _uniformInfoMap.find(uniformNameID); return (itr!=_uniformInfoMap.end()) ? itr->second._location : -1; } + + /** + * Alternative version of getUniformLocation( unsigned int uniformNameID ) + * retrofited into OSG for backward compatibility with osgCal, + * after uniform ids were refactored from std::strings to GLints in OSG version 2.9.10. + * + * Drawbacks: This method is not particularly fast. It has to access mutexed static + * map of uniform ids. So don't overuse it or your app performance will suffer. + */ + inline GLint getUniformLocation( const std::string & uniformName ) const { return getUniformLocation( Uniform::getNameID( uniformName ) ); } + + inline GLint getAttribLocation( const std::string& name ) const { ActiveVarInfoMap::const_iterator itr = _attribInfoMap.find(name); return (itr!=_attribInfoMap.end()) ? itr->second._location : -1; } + + inline void addShaderToAttach(Shader *shader) + { + _shadersToAttach.push_back(shader); + } + + inline void addShaderToDetach(Shader *shader) + { + _shadersToDetach.push_back(shader); + } + + protected: /*methods*/ + virtual ~PerContextProgram(); + + protected: /*data*/ + /** Pointer to our parent Program */ + const Program* _program; + /** Pointer to this context's extension functions */ + osg::ref_ptr _extensions; + /** Handle to the actual OpenGL glProgram */ + GLuint _glProgramHandle; + /** Does our glProgram need to be linked? */ + bool _needsLink; + /** Is our glProgram successfully linked? */ + bool _isLinked; + /** Was glProgramBinary called successfully? */ + bool _loadedBinary; + + const unsigned int _contextID; + + /** Does the glProgram handle belongs to this class? */ + bool _ownsProgramHandle; + + ActiveUniformMap _uniformInfoMap; + ActiveVarInfoMap _attribInfoMap; + UniformBlockMap _uniformBlockMap; + + typedef std::pair, unsigned int> UniformModifiedCountPair; + typedef std::map LastAppliedUniformList; + mutable LastAppliedUniformList _lastAppliedUniformList; + + typedef std::vector< ref_ptr > ShaderList; + ShaderList _shadersToDetach; + ShaderList _shadersToAttach; + + private: + PerContextProgram(); // disallowed + PerContextProgram(const PerContextProgram&); // disallowed + PerContextProgram& operator=(const PerContextProgram&); // disallowed + }; + + /** Get the PCP for a particular GL context */ + PerContextProgram* getPCP(unsigned int contextID) const; + + protected: /*methods*/ + virtual ~Program(); + + protected: /*data*/ + + mutable osg::buffered_value< osg::ref_ptr > _pcpList; + AttribBindingList _attribBindingList; + FragDataBindingList _fragDataBindingList; + UniformBlockBindingList _uniformBlockBindingList; + + typedef std::vector< ref_ptr > ShaderList; + ShaderList _shaderList; + + osg::ref_ptr _programBinary; + + /** Parameters maintained with glProgramParameteriEXT */ + GLint _geometryVerticesOut; + GLint _geometryInputType; + GLint _geometryOutputType; + + + /** Parameter maintained with glDispatchCompute */ + GLint _numGroupsX; + GLint _numGroupsY; + GLint _numGroupsZ; + + private: + Program& operator=(const Program&); // disallowed + +}; + +} + +#endif diff --git a/libs/include/android/osg/Projection b/libs/include/android/osg/Projection new file mode 100755 index 0000000..4624399 --- /dev/null +++ b/libs/include/android/osg/Projection @@ -0,0 +1,61 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_PROJECTION +#define OSG_PROJECTION 1 + +#include +#include + +namespace osg { + +/** Projection nodes set up the frustum/orthographic projection used when rendering the scene. +*/ +class OSG_EXPORT Projection : public Group +{ + public : + + + Projection(); + + /** Copy constructor using CopyOp to manage deep vs shallow copy.*/ + Projection(const Projection&,const CopyOp& copyop=CopyOp::SHALLOW_COPY); + + Projection(const Matrix& matix); + + META_Node(osg, Projection); + + /** Set the transform's matrix.*/ + void setMatrix(const Matrix& mat) { _matrix = mat; } + + /** Get the transform's matrix. */ + inline const Matrix& getMatrix() const { return _matrix; } + + /** preMult transform.*/ + void preMult(const Matrix& mat) { _matrix.preMult(mat); } + + /** postMult transform.*/ + void postMult(const Matrix& mat) { _matrix.postMult(mat); } + + + protected : + + virtual ~Projection(); + + Matrix _matrix; + +}; + +} + +#endif diff --git a/libs/include/android/osg/ProxyNode b/libs/include/android/osg/ProxyNode new file mode 100755 index 0000000..797f777 --- /dev/null +++ b/libs/include/android/osg/ProxyNode @@ -0,0 +1,142 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_ProxyNode +#define OSG_ProxyNode 1 + +#include + +namespace osg { + +/** ProxyNode. +*/ +class OSG_EXPORT ProxyNode : public Group +{ + public : + + ProxyNode(); + + /** Copy constructor using CopyOp to manage deep vs shallow copy.*/ + ProxyNode(const ProxyNode&,const CopyOp& copyop=CopyOp::SHALLOW_COPY); + + META_Node(osg, ProxyNode); + + typedef osg::BoundingSphere::vec_type vec_type; + typedef osg::BoundingSphere::value_type value_type; + + virtual void traverse(NodeVisitor& nv); + + virtual bool addChild(Node *child); + virtual bool addChild(Node *child, const std::string& filename); + + virtual bool removeChildren(unsigned int pos,unsigned int numChildrenToRemove); + + + /** Set the optional database osgDB::Options object to use when loading children.*/ + void setDatabaseOptions(osg::Referenced* options) { _databaseOptions = options; } + + /** Get the optional database osgDB::Options object used when loading children.*/ + osg::Referenced* getDatabaseOptions() { return _databaseOptions.get(); } + + /** Get the optional database osgDB::Options object used when loading children.*/ + const osg::Referenced* getDatabaseOptions() const { return _databaseOptions.get(); } + + + /** Set the database path to prepend to children's filenames.*/ + void setDatabasePath(const std::string& path); + /** Get the database path used to prepend to children's filenames.*/ + inline const std::string& getDatabasePath() const { return _databasePath; } + + void setFileName(unsigned int childNo, const std::string& filename) { expandFileNameListTo(childNo); _filenameList[childNo].first=filename; } + const std::string& getFileName(unsigned int childNo) const { return _filenameList[childNo].first; } + unsigned int getNumFileNames() const { return _filenameList.size(); } + + /** Return the DatabaseRequest object used by the DatabasePager to keep track of file load requests + * being carried out on behalf of the DatabasePager. + * Note, in normal OSG usage you should not set this value yourself, as this will be managed by + * the osgDB::DatabasePager.*/ + osg::ref_ptr& getDatabaseRequest(unsigned int childNo) { return _filenameList[childNo].second; } + + /** Return the const DatabaseRequest object.*/ + const osg::ref_ptr& getDatabaseRequest(unsigned int childNo) const { return _filenameList[childNo].second; } + + + /** Modes which control how the center of object should be determined when computing which child is active.*/ + enum CenterMode + { + USE_BOUNDING_SPHERE_CENTER, + USER_DEFINED_CENTER, + UNION_OF_BOUNDING_SPHERE_AND_USER_DEFINED + }; + + /** Set how the center of object should be determined when computing which child is active.*/ + void setCenterMode(CenterMode mode) { _centerMode=mode; } + + /** Get how the center of object should be determined when computing which child is active.*/ + CenterMode getCenterMode() const { return _centerMode; } + + /** Modes which control how the proxynode external reference are loaded.*/ + enum LoadingExternalReferenceMode + { + LOAD_IMMEDIATELY, + DEFER_LOADING_TO_DATABASE_PAGER, + NO_AUTOMATIC_LOADING + }; + + /** Set how the child loading is done.*/ + void setLoadingExternalReferenceMode(LoadingExternalReferenceMode mode) { _loadingExtReference=mode; } + + /** Get the loading mode.*/ + LoadingExternalReferenceMode getLoadingExternalReferenceMode() const { return _loadingExtReference; } + + /** Sets the object-space point which defines the center of the osg::ProxyNode. + Center is affected by any transforms in the hierarchy above the osg::ProxyNode.*/ + inline void setCenter(const vec_type& center) { if (_centerMode!=UNION_OF_BOUNDING_SPHERE_AND_USER_DEFINED) { _centerMode=USER_DEFINED_CENTER; } _userDefinedCenter = center; } + + /** Return the ProxyNode center point. */ + inline const vec_type& getCenter() const { if ((_centerMode==USER_DEFINED_CENTER)||(_centerMode==UNION_OF_BOUNDING_SPHERE_AND_USER_DEFINED)) return _userDefinedCenter; else return getBound().center(); } + + + /** Set the object-space reference radius of the volume enclosed by the ProxyNode. + * Used to determine the bounding sphere of the ProxyNode in the absence of any children.*/ + inline void setRadius(value_type radius) { _radius = radius; } + + /** Get the object-space radius of the volume enclosed by the ProxyNode.*/ + inline value_type getRadius() const { return _radius; } + + virtual BoundingSphere computeBound() const; + + protected : + + virtual ~ProxyNode() {} + + void expandFileNameListTo(unsigned int pos); + + typedef std::pair< std::string, osg::ref_ptr > FileNameDatabaseRequestPair; + typedef std::vector FileNameDatabaseRequestList; + + FileNameDatabaseRequestList _filenameList; + ref_ptr _databaseOptions; + std::string _databasePath; + + LoadingExternalReferenceMode _loadingExtReference; + + CenterMode _centerMode; + vec_type _userDefinedCenter; + value_type _radius; + +}; + +} + +#endif diff --git a/libs/include/android/osg/Quat b/libs/include/android/osg/Quat new file mode 100755 index 0000000..31e1799 --- /dev/null +++ b/libs/include/android/osg/Quat @@ -0,0 +1,393 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_QUAT +#define OSG_QUAT 1 + +#include +#include +#include +#include +#include + +namespace osg { + +class Matrixf; +class Matrixd; + +/** A quaternion class. It can be used to represent an orientation in 3D space.*/ +class OSG_EXPORT Quat +{ + + public: + + typedef double value_type; + + value_type _v[4]; // a four-vector + + inline Quat() { _v[0]=0.0; _v[1]=0.0; _v[2]=0.0; _v[3]=1.0; } + + inline Quat( value_type x, value_type y, value_type z, value_type w ) + { + _v[0]=x; + _v[1]=y; + _v[2]=z; + _v[3]=w; + } + + inline Quat( const Vec4f& v ) + { + _v[0]=v.x(); + _v[1]=v.y(); + _v[2]=v.z(); + _v[3]=v.w(); + } + + inline Quat( const Vec4d& v ) + { + _v[0]=v.x(); + _v[1]=v.y(); + _v[2]=v.z(); + _v[3]=v.w(); + } + + inline Quat( value_type angle, const Vec3f& axis) + { + makeRotate(angle,axis); + } + inline Quat( value_type angle, const Vec3d& axis) + { + makeRotate(angle,axis); + } + + inline Quat( value_type angle1, const Vec3f& axis1, + value_type angle2, const Vec3f& axis2, + value_type angle3, const Vec3f& axis3) + { + makeRotate(angle1,axis1,angle2,axis2,angle3,axis3); + } + + inline Quat( value_type angle1, const Vec3d& axis1, + value_type angle2, const Vec3d& axis2, + value_type angle3, const Vec3d& axis3) + { + makeRotate(angle1,axis1,angle2,axis2,angle3,axis3); + } + + inline Quat& operator = (const Quat& v) { _v[0]=v._v[0]; _v[1]=v._v[1]; _v[2]=v._v[2]; _v[3]=v._v[3]; return *this; } + + inline bool operator == (const Quat& v) const { return _v[0]==v._v[0] && _v[1]==v._v[1] && _v[2]==v._v[2] && _v[3]==v._v[3]; } + + inline bool operator != (const Quat& v) const { return _v[0]!=v._v[0] || _v[1]!=v._v[1] || _v[2]!=v._v[2] || _v[3]!=v._v[3]; } + + inline bool operator < (const Quat& v) const + { + if (_v[0]v._v[0]) return false; + else if (_v[1]v._v[1]) return false; + else if (_v[2]v._v[2]) return false; + else return (_v[3] + +#include +#include +#include + +#if !defined(_OPENTHREADS_ATOMIC_USE_MUTEX) +# define _OSG_REFERENCED_USE_ATOMIC_OPERATIONS +#endif + +namespace osg { + +// forward declare, declared after Referenced below. +class DeleteHandler; +class Observer; +class ObserverSet; + +/** template class to help enforce static initialization order. */ +template +struct depends_on +{ + depends_on() { M(); } +}; + +/** Base class for providing reference counted objects.*/ +class OSG_EXPORT Referenced +{ + + public: + + + Referenced(); + + explicit Referenced(bool threadSafeRefUnref); + + Referenced(const Referenced&); + + inline Referenced& operator = (const Referenced&) { return *this; } + + /** Set whether to use a mutex to ensure ref() and unref() are thread safe.*/ + virtual void setThreadSafeRefUnref(bool threadSafe); + + /** Get whether a mutex is used to ensure ref() and unref() are thread safe.*/ + +#if defined(_OSG_REFERENCED_USE_ATOMIC_OPERATIONS) + bool getThreadSafeRefUnref() const { return true; } +#else + bool getThreadSafeRefUnref() const { return _refMutex!=0; } +#endif + + /** Get the mutex used to ensure thread safety of ref()/unref(). */ +#if defined(_OSG_REFERENCED_USE_ATOMIC_OPERATIONS) + OpenThreads::Mutex* getRefMutex() const { return getGlobalReferencedMutex(); } +#else + OpenThreads::Mutex* getRefMutex() const { return _refMutex; } +#endif + + /** Get the optional global Referenced mutex, this can be shared between all osg::Referenced.*/ + static OpenThreads::Mutex* getGlobalReferencedMutex(); + + /** Increment the reference count by one, indicating that + this object has another pointer which is referencing it.*/ + inline int ref() const; + + /** Decrement the reference count by one, indicating that + a pointer to this object is no longer referencing it. If the + reference count goes to zero, it is assumed that this object + is no longer referenced and is automatically deleted.*/ + inline int unref() const; + + /** Decrement the reference count by one, indicating that + a pointer to this object is no longer referencing it. However, do + not delete it, even if ref count goes to 0. Warning, unref_nodelete() + should only be called if the user knows exactly who will + be responsible for, one should prefer unref() over unref_nodelete() + as the latter can lead to memory leaks.*/ + int unref_nodelete() const; + + /** Return the number of pointers currently referencing this object. */ + inline int referenceCount() const { return _refCount; } + + + /** Get the ObserverSet if one is attached, otherwise return NULL.*/ + ObserverSet* getObserverSet() const + { + #if defined(_OSG_REFERENCED_USE_ATOMIC_OPERATIONS) + return static_cast(_observerSet.get()); + #else + return static_cast(_observerSet); + #endif + } + + /** Get the ObserverSet if one is attached, otherwise create an ObserverSet, attach it, then return this newly created ObserverSet.*/ + ObserverSet* getOrCreateObserverSet() const; + + /** Add a Observer that is observing this object, notify the Observer when this object gets deleted.*/ + void addObserver(Observer* observer) const; + + /** Remove Observer that is observing this object.*/ + void removeObserver(Observer* observer) const; + + public: + + /** Set whether reference counting should use a mutex for thread safe reference counting.*/ + static void setThreadSafeReferenceCounting(bool enableThreadSafeReferenceCounting); + + /** Get whether reference counting is active.*/ + static bool getThreadSafeReferenceCounting(); + + friend class DeleteHandler; + + /** Set a DeleteHandler to which deletion of all referenced counted objects + * will be delegated.*/ + static void setDeleteHandler(DeleteHandler* handler); + + /** Get a DeleteHandler.*/ + static DeleteHandler* getDeleteHandler(); + + + protected: + + virtual ~Referenced(); + + void signalObserversAndDelete(bool signalDelete, bool doDelete) const; + + void deleteUsingDeleteHandler() const; + +#if defined(_OSG_REFERENCED_USE_ATOMIC_OPERATIONS) + mutable OpenThreads::AtomicPtr _observerSet; + + mutable OpenThreads::Atomic _refCount; +#else + + mutable OpenThreads::Mutex* _refMutex; + + mutable int _refCount; + + mutable void* _observerSet; +#endif +}; + +inline int Referenced::ref() const +{ +#if defined(_OSG_REFERENCED_USE_ATOMIC_OPERATIONS) + return ++_refCount; +#else + if (_refMutex) + { + OpenThreads::ScopedLock lock(*_refMutex); + return ++_refCount; + } + else + { + return ++_refCount; + } +#endif +} + +inline int Referenced::unref() const +{ + int newRef; +#if defined(_OSG_REFERENCED_USE_ATOMIC_OPERATIONS) + newRef = --_refCount; + bool needDelete = (newRef == 0); +#else + bool needDelete = false; + if (_refMutex) + { + OpenThreads::ScopedLock lock(*_refMutex); + newRef = --_refCount; + needDelete = newRef==0; + } + else + { + newRef = --_refCount; + needDelete = newRef==0; + } +#endif + + if (needDelete) + { + signalObserversAndDelete(true,true); + } + return newRef; +} + +// intrusive_ptr_add_ref and intrusive_ptr_release allow +// use of osg Referenced classes with boost::intrusive_ptr +inline void intrusive_ptr_add_ref(Referenced* p) { p->ref(); } +inline void intrusive_ptr_release(Referenced* p) { p->unref(); } + +} + +#endif diff --git a/libs/include/android/osg/RenderInfo b/libs/include/android/osg/RenderInfo new file mode 100755 index 0000000..2c9c9c4 --- /dev/null +++ b/libs/include/android/osg/RenderInfo @@ -0,0 +1,79 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_RENDERINFO +#define OSG_RENDERINFO 1 + +#include +#include + +namespace osg { + +class RenderInfo +{ +public: + + RenderInfo(): + _view(0) {} + + RenderInfo(const RenderInfo& rhs): + _state(rhs._state), + _view(rhs._view), + _cameras(rhs._cameras), + _userData(rhs._userData) {} + + RenderInfo(State* state, View* view): + _state(state), + _view(view) {} + + RenderInfo& operator = (const RenderInfo& rhs) + { + _state = rhs._state; + _view = rhs._view; + _cameras = rhs._cameras; + _userData = rhs._userData; + return *this; + } + + unsigned int getContextID() const { return _state.valid() ? _state->getContextID() : 0; } + + void setState(State* state) { _state = state; } + State* getState() { return _state.get(); } + const State* getState() const { return _state.get(); } + + void setView(View* view) { _view = view; } + View* getView() { return _view; } + const View* getView() const { return _view; } + + void pushCamera(Camera* camera) { _cameras.push_back(camera); } + void popCamera() { if (!_cameras.empty()) _cameras.pop_back(); } + + Camera* getCurrentCamera() { return _cameras.empty() ? 0 : _cameras.back(); } + + void setUserData(Referenced* userData) { _userData = userData; } + Referenced* getUserData() { return _userData.get(); } + const Referenced* getUserData() const { return _userData.get(); } + +protected: + + typedef std::vector Cameras; + + ref_ptr _state; + View* _view; + Cameras _cameras; + ref_ptr _userData; +}; + +} + +#endif diff --git a/libs/include/android/osg/SampleMaski b/libs/include/android/osg/SampleMaski new file mode 100755 index 0000000..dee17bc --- /dev/null +++ b/libs/include/android/osg/SampleMaski @@ -0,0 +1,95 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_SAMPLEMASKI +#define OSG_SAMPLEMASKI 1 + +#include + +namespace osg { + +/** + * osg::SampleMaski does nothing if OpenGL 3.2 or ARB_texture_multisample are not available. +*/ +class OSG_EXPORT SampleMaski : public StateAttribute +{ + public : + + SampleMaski(); + + /** Copy constructor using CopyOp to manage deep vs shallow copy.*/ + SampleMaski(const SampleMaski& sampleMaski,const CopyOp& copyop=CopyOp::SHALLOW_COPY); + + META_StateAttribute(osg, SampleMaski, SAMPLEMASKI) + + /** return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs.*/ + virtual int compare(const StateAttribute& sa) const; + + inline void setMask(unsigned int mask, unsigned int maskNumber = 0u ) { _sampleMask[maskNumber] = mask; } + + inline unsigned int getMask(unsigned int maskNumber = 0u) const { return _sampleMask[maskNumber]; } + + virtual void apply(State& state) const; + + public: + + /** Extensions class which encapsulates the querying of extensions and + * associated function pointers, and provide convenience wrappers to + * check for the extensions or use the associated functions. + */ + class OSG_EXPORT Extensions : public osg::Referenced + { + public: + Extensions(unsigned int contextID); + + Extensions(const Extensions& rhs); + + void lowestCommonDenominator(const Extensions& rhs); + + void setupGLExtensions(unsigned int contextID); + + bool isOpenGL32upported() const { return _isOpenGL32upported; } + bool isTextureMultisampleSupported() const { return _isTextureMultisampleSupported; } + bool isSampleMaskiSupported() const { return _isSampleMaskiSupported; } + + void glSampleMaski(GLuint maskNumber, GLbitfield mask) const; + + protected: + + ~Extensions() {} + + bool _isOpenGL32upported; + bool _isTextureMultisampleSupported; + bool _isSampleMaskiSupported; + + typedef void (GL_APIENTRY * SampleMaski) ( GLuint maskNumber, GLbitfield mask ); + + SampleMaski _glSampleMaski; + }; + + static Extensions* getExtensions(unsigned int contextID,bool createIfNotInitalized); + + static void setExtensions(unsigned int contextID,Extensions* extensions); + + + protected: + + virtual ~SampleMaski(); + +//For now support only up to 64 bit mask; + unsigned int _sampleMask[2]; +}; + +} + +#endif diff --git a/libs/include/android/osg/Scissor b/libs/include/android/osg/Scissor new file mode 100755 index 0000000..e7e25e2 --- /dev/null +++ b/libs/include/android/osg/Scissor @@ -0,0 +1,110 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_Scissor +#define OSG_Scissor 1 + +#include + +namespace osg { + +/** Encapsulate OpenGL glScissor. */ +class OSG_EXPORT Scissor : public StateAttribute +{ + public : + Scissor(); + + Scissor(int x,int y,int width,int height): + _x(x), + _y(y), + _width(width), + _height(height) {} + + + /** Copy constructor using CopyOp to manage deep vs shallow copy. */ + Scissor(const Scissor& vp,const CopyOp& copyop=CopyOp::SHALLOW_COPY): + StateAttribute(vp,copyop), + _x(vp._x), + _y(vp._y), + _width(vp._width), + _height(vp._height) {} + + META_StateAttribute(osg, Scissor, SCISSOR); + + /** Return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs. */ + virtual int compare(const StateAttribute& sa) const + { + // check the types are equal and then create the rhs variable + // used by the COMPARE_StateAttribute_Parameter macros below. + COMPARE_StateAttribute_Types(Scissor,sa) + + // compare each parameter in turn against the rhs. + COMPARE_StateAttribute_Parameter(_x) + COMPARE_StateAttribute_Parameter(_y) + COMPARE_StateAttribute_Parameter(_width) + COMPARE_StateAttribute_Parameter(_height) + + return 0; // passed all the above comparison macros, must be equal. + } + + + virtual bool getModeUsage(StateAttribute::ModeUsage& usage) const + { + usage.usesMode(GL_SCISSOR_TEST); + return true; + } + + inline void setScissor(int x,int y,int width,int height) + { + _x = x; + _y = y; + _width = width; + _height = height; + } + + void getScissor(int& x,int& y,int& width,int& height) const + { + x = _x; + y = _y; + width = _width; + height = _height; + } + + inline int& x() { return _x; } + inline int x() const { return _x; } + + inline int& y() { return _y; } + inline int y() const { return _y; } + + inline int& width() { return _width; } + inline int width() const { return _width; } + + inline int& height() { return _height; } + inline int height() const { return _height; } + + virtual void apply(State& state) const; + + protected: + + virtual ~Scissor(); + + int _x; + int _y; + int _width; + int _height; + +}; + +} + +#endif diff --git a/libs/include/android/osg/Sequence b/libs/include/android/osg/Sequence new file mode 100755 index 0000000..542b81c --- /dev/null +++ b/libs/include/android/osg/Sequence @@ -0,0 +1,252 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. + */ + +#ifndef OSG_SEQUENCE +#define OSG_SEQUENCE 1 + +#include + +namespace osg +{ + +/** Sequence is a Group node which allows automatic, time based +switching between children. +*/ +class OSG_EXPORT Sequence : public Group +{ + public : + + Sequence(); + + /** Copy constructor using CopyOp to manage deep vs shallow copy.*/ + Sequence(const Sequence&, const CopyOp& copyop=CopyOp::SHALLOW_COPY); + + META_Node(osg, Sequence); + + virtual void traverse(NodeVisitor& nv); + + // the relationship between the _frameTime vector and the _children + // vector is a bit of a mess. This is how it was in previous versions, + // and there's no way out of it if upward compatibility needs to be + // maintained. New code should set defaultTime and use addChild, and + // not mess with the setTime method + + virtual bool addChild( Node *child); + + virtual bool addChild( Node *child, double t); + + virtual bool insertChild( unsigned int index, Node *child); + + virtual bool insertChild( unsigned int index, Node *child, double t); + + virtual bool removeChild( Node *child ); + + virtual bool removeChildren(unsigned int pos,unsigned int numChildrenToRemove); + + + /** value is which child node is to be displayed */ + void setValue(int value) { _value = value ; } + int getValue() const { return _value; } + + /** Set time in seconds for child. */ + void setTime(unsigned int frame, double t); + + /** Get time for child. */ + double getTime(unsigned int frame) const; + + /** Set the time list for children. */ + void setTimeList(const std::vector& timeList) { _frameTime = timeList; } + + /** Get the time list for children. */ + const std::vector& getTimeList() const { return _frameTime; } + + /** Set default time in seconds for new child. + if t<0, t=0 */ + void setDefaultTime(double t) {_defaultTime = (t<0.?0.:t);} + + /** Get default time in seconds for new child. */ + double getDefaultTime(void) const {return _defaultTime;}; + + /** Set time of last frame of last loop, in seconds. + if t<= 0, then ignored */ + void setLastFrameTime(double t) {_lastFrameTime = (t<0.?0.:t);} + + /** Get last frame time in seconds */ + double getLastFrameTime(void) const {return _lastFrameTime;}; + + /** Get number of frames */ + inline unsigned int getNumFrames() const { return _frameTime.size(); } + + /** Interval modes. 'Loop' repeats frames 1-N; 'swing' repeats 1->N, (N-1)->1. */ + enum LoopMode + { + LOOP, + SWING + }; + + /** Set sequence mode. */ + void setLoopMode(LoopMode mode) { _loopMode = mode; _value = -1; } + + /** Get sequence mode. */ + LoopMode getLoopMode() const { return _loopMode; } + + /** Set interval beginning. */ + void setBegin(int begin) { _begin = begin; _value = -1; } + + /** Get interval beginning. */ + int getBegin() const { return _begin; } + + /** Set interval ending. */ + void setEnd(int end) { _end = end; _value = -1; } + + /** Get interval ending. */ + int getEnd() const { return _end; } + + /** Set sequence mode & interval (range of children to be displayed). */ + void setInterval(LoopMode mode, int begin, int end); + + /** Get sequence mode & interval. */ + inline void getInterval(LoopMode& mode, int& begin, int& end) const + { + mode = _loopMode; + begin = _begin; + end = _end; + } + + /** Set speed. */ + void setSpeed(float speed) { _speed = speed; } + + /** Get speed. */ + float getSpeed() const { return _speed; } + + /** Set number of repeats. */ + void setNumRepeats(int nreps) { _nreps = (nreps<0?-1:nreps); _nrepsRemain = _nreps; } + + /** Get number of repeats. */ + int getNumRepeats() const { return _nreps; } + + /** Set duration: speed-up & number of repeats */ + void setDuration(float speed, int nreps = -1); + + /** Get duration & number of repeats. */ + inline void getDuration(float& speed, int& nreps) const + { + speed = _speed; + nreps = _nreps; + } + + /** Sequence modes. */ + enum SequenceMode + { + START, + STOP, + PAUSE, + RESUME + }; + + /** Set sequence mode. Start/stop & pause/resume. */ + void setMode(SequenceMode mode); + + /** Get sequence mode. */ + inline SequenceMode getMode() const { return _mode; } + + /** If false (default), frames will not be sync'd to frameTime. If + true, frames will be sync'd to frameTime. */ + void setSync(bool sync) { _sync = sync; } + + /** Get sync value */ + bool getSync() const { return _sync; } + + /** If true, show no child nodes after stopping */ + void setClearOnStop(bool clearOnStop) { _clearOnStop = clearOnStop; } + + /** Get whether to show no child nodes after stopping */ + bool getClearOnStop() const { return _clearOnStop; } + + protected : + + virtual ~Sequence() {} + + // get next _value in sequence + int _getNextValue(void) ; + + // update local variables + void _update(void) ; + + // init to -1 to mean "restart" + int _value; + + // current time, set by traverse + double _now ; + + // time this frame started. init to -1.0f- means get current time + double _start; + + // a vector of frame times, one per value + std::vector _frameTime; + + // the total time for one sequence, from BEGIN to END + double _totalTime ; + + // true if _totalTime needs to be recalculated because setTime or + // setInterval was invoked, or a new child was added + bool _resetTotalTime ; + + // store "loop mde", either LOOP or SWING + // init to LOOP- set by setInterval + LoopMode _loopMode; + + // first and last "values" to sequence through + // begin inits to 0 + // end inits to -1- means to init to number of values + int _begin, _end; + + // multiplier of real-time clock- set to N to go N times faster + // init to 0- going nowhere + float _speed; + + // _nreps: how many times to repeat- default param is -1, repeat forever + // init to 0, no repetitions + // _nrepsRemain: set to nreps and counts down every traversal, + // stopping when it gets to zero. init to 0 + int _nreps, _nrepsRemain; + + // frame step (are we stepping forward or backward?) + int _step; + + // default frame time for newly created frames or children- default is 1. + // set by setDefaultTime + double _defaultTime ; + + // special time to display last frame of last loop + // <= zero means to not do anything special + double _lastFrameTime ; + + // save the actual time of the last frame, and what value was stored + double _saveRealLastFrameTime ; + unsigned int _saveRealLastFrameValue ; + + // the current mode + SequenceMode _mode; + + // the current sync value + bool _sync ; + + // the current clearOnStop value + bool _clearOnStop ; + +}; + +} + +#endif diff --git a/libs/include/android/osg/ShadeModel b/libs/include/android/osg/ShadeModel new file mode 100755 index 0000000..248b26c --- /dev/null +++ b/libs/include/android/osg/ShadeModel @@ -0,0 +1,77 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_SHADEMODEL +#define OSG_SHADEMODEL 1 + +#include +#include + +namespace osg { + +#ifndef OSG_GL_FIXED_FUNCTION_AVAILABLE + #define GL_FLAT 0x1D00 + #define GL_SMOOTH 0x1D01 +#endif + +/** Class which encapsulates glShadeModel(..). +*/ +class OSG_EXPORT ShadeModel : public StateAttribute +{ + public : + + enum Mode { + FLAT = GL_FLAT, + SMOOTH = GL_SMOOTH + }; + + ShadeModel(Mode mode=SMOOTH); + + /** Copy constructor using CopyOp to manage deep vs shallow copy.*/ + ShadeModel(const ShadeModel& sm,const CopyOp& copyop=CopyOp::SHALLOW_COPY): + StateAttribute(sm,copyop), + _mode(sm._mode) {} + + + META_StateAttribute(osg, ShadeModel, SHADEMODEL); + + /** return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs.*/ + virtual int compare(const StateAttribute& sa) const + { + // check the types are equal and then create the rhs variable + // used by the COMPARE_StateAttribute_Parameter macros below. + COMPARE_StateAttribute_Types(ShadeModel,sa) + + // compare each parameter in turn against the rhs. + COMPARE_StateAttribute_Parameter(_mode) + + return 0; // passed all the above comparison macros, must be equal. + } + + inline void setMode(Mode mode) { _mode = mode; } + + inline Mode getMode() const { return _mode; } + + virtual void apply(State& state) const; + + protected: + + virtual ~ShadeModel(); + + Mode _mode; + +}; + +} + +#endif diff --git a/libs/include/android/osg/Shader b/libs/include/android/osg/Shader new file mode 100755 index 0000000..295d4c0 --- /dev/null +++ b/libs/include/android/osg/Shader @@ -0,0 +1,312 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * Copyright (C) 2003-2005 3Dlabs Inc. Ltd. + * Copyright (C) 2004-2005 Nathan Cournia + * Copyright (C) 2008 Zebra Imaging + * Copyright (C) 2010 VIRES Simulationstechnologie GmbH + * + * This application is open source and may be redistributed and/or modified + * freely and without restriction, both in commercial and non commercial + * applications, as long as this copyright notice is maintained. + * + * This application is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. +*/ + +/* file: include/osg/Shader + * author: Mike Weiblen 2008-01-02 + * Holger Helmich 2010-10-21 +*/ + +#ifndef OSG_SHADER +#define OSG_SHADER 1 + + +#include +#include +#include + +#include +#include + +namespace osg { + +class Program; + +/** Simple class for wrapping up the data used in OpenGL ES 2's glShaderBinary calls. + * ShaderBinary is set up with the binary data then assigned to one or more osg::Shader. */ +class OSG_EXPORT ShaderBinary : public osg::Object +{ + public: + + ShaderBinary(); + + /** Copy constructor using CopyOp to manage deep vs shallow copy.*/ + ShaderBinary(const ShaderBinary& rhs, const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY); + + META_Object(osg, ShaderBinary); + + /** Allocated a data buffer of specified size/*/ + void allocate(unsigned int size); + + /** Assign shader binary data, copying the specified data into locally stored data buffer, the original data can then be deleted.*/ + void assign(unsigned int size, const unsigned char* data); + + /** Get the size of the shader binary data.*/ + unsigned int getSize() const { return static_cast(_data.size()); } + + /** Get a ptr to the shader binary data.*/ + unsigned char* getData() { return _data.empty() ? 0 : &(_data.front()); } + + /** Get a const ptr to the shader binary data.*/ + const unsigned char* getData() const { return _data.empty() ? 0 : &(_data.front()); } + + /** Read shader binary from file. + * Return the resulting Shader or 0 if no valid shader binary could be read.*/ + static ShaderBinary* readShaderBinaryFile(const std::string& fileName); + + protected: + + typedef std::vector Data; + Data _data; +}; + + +/////////////////////////////////////////////////////////////////////////// +/** osg::Shader is an application-level abstraction of an OpenGL glShader. + * It is a container to load the shader source code text and manage its + * compilation. + * An osg::Shader may be attached to more than one osg::Program. + * Shader will automatically manage per-context instancing of the + * internal objects, if that is necessary for a particular display + * configuration. + */ + +class OSG_EXPORT Shader : public osg::Object +{ + public: + + enum Type { + VERTEX = GL_VERTEX_SHADER, + TESSCONTROL = GL_TESS_CONTROL_SHADER, + TESSEVALUATION = GL_TESS_EVALUATION_SHADER, + GEOMETRY = GL_GEOMETRY_SHADER_EXT, + FRAGMENT = GL_FRAGMENT_SHADER, + COMPUTE = GL_COMPUTE_SHADER, + UNDEFINED = -1 + }; + + Shader(Type type = UNDEFINED); + Shader(Type type, const std::string& source ); + Shader(Type type, ShaderBinary* shaderBinary ); + + /** Copy constructor using CopyOp to manage deep vs shallow copy.*/ + Shader(const Shader& rhs, const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY); + + META_Object(osg, Shader); + + int compare(const Shader& rhs) const; + + /** Set the Shader type as an enum. */ + bool setType(Type t); + + /** Get the Shader type as an enum. */ + inline Type getType() const { return _type; } + + /** Get the Shader type as a descriptive string. */ + const char* getTypename() const; + + + /** Set file name for the shader source code. */ + inline void setFileName(const std::string& fileName) { _shaderFileName = fileName; } + + /** Get filename to which the shader source code belongs. */ + inline const std::string& getFileName() const { return _shaderFileName; } + + + /** Set the Shader's source code text from a string. */ + void setShaderSource(const std::string& sourceText); + + /** Query the shader's source code text */ + inline const std::string& getShaderSource() const { return _shaderSource; } + + + /** Set the Shader using a ShaderBinary. */ + void setShaderBinary(ShaderBinary* shaderBinary) { _shaderBinary = shaderBinary; } + + /** Get the Shader's ShaderBinary, return NULL if none is assigned. */ + ShaderBinary* getShaderBinary() { return _shaderBinary.get(); } + + /** Get the const Shader's ShaderBinary, return NULL if none is assigned. */ + const ShaderBinary* getShaderBinary() const { return _shaderBinary.get(); } + + + /** Read shader source from file and then constructor shader of specified type. + * Return the resulting Shader or 0 if no valid shader source could be read.*/ + static Shader* readShaderFile( Type type, const std::string& fileName ); + + /** Load the Shader's source code text from a file. */ + bool loadShaderSourceFromFile( const std::string& fileName ); + + + /** The code injection map used when generating the main shader during main shader composition.*/ + typedef std::multimap CodeInjectionMap; + + /** Add code injection that will be placed in the main shader to enable support for this shader. + * The position is set up so that code to be inserted before the main() will have a negative value, + * a position between 0 and 1.0 will be inserted in main() and a position greater than 1.0 will + * be placed after the main(). + * During shader composition all the code injections are sorted in ascending order and then + * placed in the appropriate section of the main shader. */ + void addCodeInjection(float position, const std::string& code) { _codeInjectionMap.insert(CodeInjectionMap::value_type(position, code)); } + + /** Get the code injection map.*/ + CodeInjectionMap& getCodeInjectionMap() { return _codeInjectionMap; } + + /** Get the const code injection map.*/ + const CodeInjectionMap& getCodeInjectionMap() const { return _codeInjectionMap; } + + + + /** Resize any per context GLObject buffers to specified size. */ + virtual void resizeGLObjectBuffers(unsigned int maxSize); + + /** release OpenGL objects in specified graphics context if State + object is passed, otherwise release OpenGL objects for all graphics context if + State object pointer NULL.*/ + void releaseGLObjects(osg::State* state=0) const; + + /** Mark our PCSs as needing recompilation. + * Also mark Programs that depend on us as needing relink */ + void dirtyShader(); + + /** If needed, compile the PCS's glShader */ + void compileShader(osg::State& state) const; + + /** For a given GL context, attach a glShader to a glProgram */ + void attachShader(unsigned int contextID, GLuint program) const; + + /** For a given GL context, detach a glShader to a glProgram */ + void detachShader(unsigned int contextID, GLuint program) const; + + /** Query InfoLog from a glShader */ + bool getGlShaderInfoLog(unsigned int contextID, std::string& log) const; + + /** Mark internal glShader for deletion. + * Deletion requests are queued until they can be executed + * in the proper GL context. */ + static void deleteGlShader(unsigned int contextID, GLuint shader); + + /** flush all the cached glShaders which need to be deleted + * in the OpenGL context related to contextID.*/ + static void flushDeletedGlShaders(unsigned int contextID,double currentTime, double& availableTime); + + /** discard all the cached glShaders which need to be deleted in the OpenGL context related to contextID. + * Note, unlike flush no OpenGL calls are made, instead the handles are all removed. + * this call is useful for when an OpenGL context has been destroyed. */ + static void discardDeletedGlShaders(unsigned int contextID); + + static Shader::Type getTypeId( const std::string& tname ); + + public: + /** PerContextShader (PCS) is an OSG-internal encapsulation of glShader per-GL context. */ + class OSG_EXPORT PerContextShader : public osg::Referenced + { + public: + PerContextShader(const Shader* shader, unsigned int contextID); + + GLuint getHandle() const {return _glShaderHandle;} + + void requestCompile(); + void compileShader(osg::State& state); + bool needsCompile() const {return _needsCompile;} + bool isCompiled() const {return _isCompiled;} + bool getInfoLog( std::string& infoLog ) const; + + /** Attach our glShader to a glProgram */ + void attachShader(GLuint program) const; + + /** Detach our glShader from a glProgram */ + void detachShader(GLuint program) const; + + protected: /*methods*/ + ~PerContextShader(); + + protected: /*data*/ + /** Pointer to our parent osg::Shader */ + const Shader* _shader; + /** Pointer to this context's extension functions. */ + osg::ref_ptr _extensions; + /** Handle to the actual glShader. */ + GLuint _glShaderHandle; + /** Does our glShader need to be recompiled? */ + bool _needsCompile; + /** Is our glShader successfully compiled? */ + bool _isCompiled; + const unsigned int _contextID; + + private: + PerContextShader(); // disallowed + PerContextShader(const PerContextShader&); // disallowed + PerContextShader& operator=(const PerContextShader&); // disallowed + }; + + PerContextShader* getPCS(unsigned int contextID) const; + + protected: /*methods*/ + virtual ~Shader(); + + + friend class osg::Program; + bool addProgramRef( osg::Program* program ); + bool removeProgramRef( osg::Program* program ); + + protected: /*data*/ + Type _type; + std::string _shaderFileName; + std::string _shaderSource; + osg::ref_ptr _shaderBinary; + + CodeInjectionMap _codeInjectionMap; + + /** osg::Programs that this osg::Shader is attached to */ + typedef std::set< osg::Program* > ProgramSet; + ProgramSet _programSet; + mutable osg::buffered_value< osg::ref_ptr > _pcsList; + + private: + Shader& operator=(const Shader&); // disallowed +}; + + +class OSG_EXPORT ShaderComponent : public osg::Object +{ + public: + + ShaderComponent(); + ShaderComponent(const ShaderComponent& sc,const CopyOp& copyop=CopyOp::SHALLOW_COPY); + + META_Object(osg, ShaderComponent) + + unsigned int addShader(osg::Shader* shader); + void removeShader(unsigned int i); + + osg::Shader* getShader(unsigned int i) { return _shaders[i].get(); } + const osg::Shader* getShader(unsigned int i) const { return _shaders[i].get(); } + + unsigned int getNumShaders() const { return static_cast(_shaders.size()); } + + virtual void compileGLObjects(State& state) const; + virtual void resizeGLObjectBuffers(unsigned int maxSize); + virtual void releaseGLObjects(State* state=0) const; + + protected: + + typedef std::vector< osg::ref_ptr > Shaders; + Shaders _shaders; +}; + + +} + +#endif diff --git a/libs/include/android/osg/ShaderAttribute b/libs/include/android/osg/ShaderAttribute new file mode 100755 index 0000000..b5c7e63 --- /dev/null +++ b/libs/include/android/osg/ShaderAttribute @@ -0,0 +1,79 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2004 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_SHADERATTRIBUTE +#define OSG_SHADERATTRIBUTE 1 + +#include +#include +#include + +namespace osg { + +class OSG_EXPORT ShaderAttribute : public StateAttribute +{ + public : + + ShaderAttribute(); + + /** Copy constructor using CopyOp to manage deep vs shallow copy. */ + ShaderAttribute(const ShaderAttribute& sa,const CopyOp& copyop=CopyOp::SHALLOW_COPY); + + virtual osg::Object* cloneType() const; + virtual osg::Object* clone(const osg::CopyOp& copyop) const { return new ShaderAttribute(*this,copyop); } + virtual bool isSameKindAs(const osg::Object* obj) const { return dynamic_cast(obj)!=NULL; } + virtual const char* libraryName() const { return "osg"; } + virtual const char* className() const { return "ShaderAttribute"; } + + /** return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs. */ + virtual int compare(const StateAttribute& sa) const; + + + void setType(Type type); + virtual Type getType() const { return _type; } + + unsigned int addShader(Shader* shader) { return _shaderComponent->addShader(shader); } + void removeShader(unsigned int i) { _shaderComponent->removeShader(i); } + unsigned int getNumShaders() const { return _shaderComponent->getNumShaders(); } + Shader* getShader(unsigned int i) { return _shaderComponent->getShader(i); } + const Shader* getShader(unsigned int i) const { return _shaderComponent->getShader(i); } + + unsigned int addUniform(Uniform* uniform); + void removeUniform(unsigned int i); + unsigned int getNumUniforms() const { return _uniforms.size(); } + Uniform* getUniform(unsigned int i) { return _uniforms[i].get(); } + const Uniform* getUniform(unsigned int i) const { return _uniforms[i].get(); } + + virtual bool getModeUsage(StateAttribute::ModeUsage& usage) const; + + virtual void apply(State& state) const; + + virtual void compileGLObjects(State& state) const; + + virtual void resizeGLObjectBuffers(unsigned int maxSize); + + virtual void releaseGLObjects(State* state=0) const; + + protected : + + virtual ~ShaderAttribute(); + + typedef std::vector< osg::ref_ptr > Uniforms; + + Type _type; + Uniforms _uniforms; +}; + +} + +#endif diff --git a/libs/include/android/osg/ShaderComposer b/libs/include/android/osg/ShaderComposer new file mode 100755 index 0000000..97ea26c --- /dev/null +++ b/libs/include/android/osg/ShaderComposer @@ -0,0 +1,58 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_SHADERCOMPOSER +#define OSG_SHADERCOMPOSER 1 + +#include +#include +#include + +namespace osg { + +// forward declare osg::State +class State; + +typedef std::vector ShaderComponents; + +class OSG_EXPORT ShaderComposer : public osg::Object +{ + public: + + ShaderComposer(); + ShaderComposer(const ShaderComposer& sa,const CopyOp& copyop=CopyOp::SHALLOW_COPY); + META_Object(osg, ShaderComposer) + + virtual osg::Program* getOrCreateProgram(const ShaderComponents& shaderComponents); + + + typedef std::vector< const osg::Shader* > Shaders; + virtual osg::Shader* composeMain(const Shaders& shaders); + virtual void addShaderToProgram(Program* program, const Shaders& shaders); + + protected: + + virtual ~ShaderComposer(); + + + typedef std::map< ShaderComponents, ref_ptr > ProgramMap; + ProgramMap _programMap; + + typedef std::map< Shaders, ref_ptr > ShaderMainMap; + ShaderMainMap _shaderMainMap; + +}; + +} + +#endif diff --git a/libs/include/android/osg/ShadowVolumeOccluder b/libs/include/android/osg/ShadowVolumeOccluder new file mode 100755 index 0000000..87e92b7 --- /dev/null +++ b/libs/include/android/osg/ShadowVolumeOccluder @@ -0,0 +1,172 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_SHADOWVOLUMEOCCLUDER +#define OSG_SHADOWVOLUMEOCCLUDER 1 + +#include +#include +#include + +namespace osg { + +class CullStack; + +/** ShadowVolumeOccluder is a helper class for implementing shadow occlusion culling. */ +class OSG_EXPORT ShadowVolumeOccluder +{ + + public: + + + typedef std::vector HoleList; + + ShadowVolumeOccluder(const ShadowVolumeOccluder& svo): + _volume(svo._volume), + _nodePath(svo._nodePath), + _projectionMatrix(svo._projectionMatrix), + _occluderVolume(svo._occluderVolume), + _holeList(svo._holeList) {} + + ShadowVolumeOccluder(): + _volume(0.0f) {} + + + bool operator < (const ShadowVolumeOccluder& svo) const { return getVolume()>svo.getVolume(); } // not greater volume first. + + /** compute the shadow volume occluder. */ + bool computeOccluder(const NodePath& nodePath,const ConvexPlanarOccluder& occluder,CullStack& cullStack,bool createDrawables=false); + + + inline void disableResultMasks(); + + inline void pushCurrentMask(); + inline void popCurrentMask(); + + + /** return true if the matrix passed in matches the projection matrix that this ShadowVolumeOccluder is + * associated with.*/ + bool matchProjectionMatrix(const osg::Matrix& matrix) const + { + if (_projectionMatrix.valid()) return matrix==*_projectionMatrix; + else return false; + } + + + /** Set the NodePath which describes which node in the scene graph + * that this occluder is attached to. */ + inline void setNodePath(NodePath& nodePath) { _nodePath = nodePath; } + inline NodePath& getNodePath() { return _nodePath; } + inline const NodePath& getNodePath() const { return _nodePath; } + + + /** get the volume of the occluder minus its holes, in eye coords, the volume is normalized by dividing by + * the volume of the view frustum in eye coords.*/ + float getVolume() const { return _volume; } + + /** return the occluder polytope.*/ + Polytope& getOccluder() { return _occluderVolume; } + + /** return the const occluder polytope.*/ + const Polytope& getOccluder() const { return _occluderVolume; } + + /** return the list of holes.*/ + HoleList& getHoleList() { return _holeList; } + + /** return the const list of holes.*/ + const HoleList& getHoleList() const { return _holeList; } + + + /** return true if the specified vertex list is contained entirely + * within this shadow occluder volume.*/ + bool contains(const std::vector& vertices); + + /** return true if the specified bounding sphere is contained entirely + * within this shadow occluder volume.*/ + bool contains(const BoundingSphere& bound); + + /** return true if the specified bounding box is contained entirely + * within this shadow occluder volume.*/ + bool contains(const BoundingBox& bound); + + inline void transformProvidingInverse(const osg::Matrix& matrix) + { + _occluderVolume.transformProvidingInverse(matrix); + for(HoleList::iterator itr=_holeList.begin(); + itr!=_holeList.end(); + ++itr) + { + itr->transformProvidingInverse(matrix); + } + } + + + protected: + + float _volume; + NodePath _nodePath; + ref_ptr _projectionMatrix; + Polytope _occluderVolume; + HoleList _holeList; +}; + + +/** A list of ShadowVolumeOccluder, used by CollectOccluderVisitor and CullVistor's.*/ +typedef std::vector ShadowVolumeOccluderList; + + +inline void ShadowVolumeOccluder::disableResultMasks() +{ + //std::cout<<"ShadowVolumeOccluder::disableResultMasks() - _occluderVolume.getMaskStack().size()="<<_occluderVolume.getMaskStack().size()<<" "<<_occluderVolume.getCurrentMask()<setResultMask(0); + } +} + +inline void ShadowVolumeOccluder::pushCurrentMask() +{ + //std::cout<<"ShadowVolumeOccluder::pushCurrentMasks() - _occluderVolume.getMaskStack().size()="<<_occluderVolume.getMaskStack().size()<<" "<<_occluderVolume.getCurrentMask()<pushCurrentMask(); + } + } +} + +inline void ShadowVolumeOccluder::popCurrentMask() +{ + _occluderVolume.popCurrentMask(); + if (!_holeList.empty()) + { + for(HoleList::iterator itr=_holeList.begin(); + itr!=_holeList.end(); + ++itr) + { + itr->popCurrentMask(); + } + } + //std::cout<<"ShadowVolumeOccluder::popCurrentMasks() - _occluderVolume.getMaskStack().size()="<<_occluderVolume.getMaskStack().size()<<" "<<_occluderVolume.getCurrentMask()< +#include +#include +#include +#include + +namespace osg { + +// forward decare visitors. +class ShapeVisitor; +class ConstShapeVisitor; + + +/** META_StateAttribute macro define the standard clone, isSameKindAs, + * className and getType methods. + * Use when subclassing from Object to make it more convenient to define + * the standard pure virtual methods which are required for all Object + * subclasses.*/ +#define META_Shape(library,name) \ + virtual osg::Object* cloneType() const { return new name(); } \ + virtual osg::Object* clone(const osg::CopyOp& copyop) const { return new name (*this,copyop); } \ + virtual bool isSameKindAs(const osg::Object* obj) const { return dynamic_cast(obj)!=NULL; } \ + virtual const char* libraryName() const { return #library; } \ + virtual const char* className() const { return #name; } \ + virtual void accept(osg::ShapeVisitor& sv) { sv.apply(*this); } \ + virtual void accept(osg::ConstShapeVisitor& csv) const { csv.apply(*this); } + +/** Base class for all shape types. + * Shapes are used to either for culling and collision detection or + * to define the geometric shape of procedurally generate Geometry. +*/ +class OSG_EXPORT Shape : public Object +{ + public: + + Shape() {} + + Shape(const Shape& sa,const CopyOp& copyop=CopyOp::SHALLOW_COPY): + Object(sa,copyop) {} + + /** Clone the type of an attribute, with Object* return type. + Must be defined by derived classes.*/ + virtual Object* cloneType() const = 0; + + /** Clone an attribute, with Object* return type. + Must be defined by derived classes.*/ + virtual Object* clone(const CopyOp&) const = 0; + + + /** return true if this and obj are of the same kind of object.*/ + virtual bool isSameKindAs(const Object* obj) const { return dynamic_cast(obj)!=NULL; } + + /** return the name of the attribute's library.*/ + virtual const char* libraryName() const { return "osg"; } + + /** return the name of the attribute's class type.*/ + virtual const char* className() const { return "Shape"; } + + /** accept a non const shape visitor which can be used on non const shape objects. + Must be defined by derived classes.*/ + virtual void accept(ShapeVisitor&)=0; + + /** accept a const shape visitor which can be used on const shape objects. + Must be defined by derived classes.*/ + virtual void accept(ConstShapeVisitor&) const =0; + + protected: + + virtual ~Shape(); +}; + +// forward declarations of Shape types. +class Sphere; +class Box; +class Cone; +class Cylinder; +class Capsule; +class InfinitePlane; + +class TriangleMesh; +class ConvexHull; +class HeightField; + +class CompositeShape; + +class OSG_EXPORT ShapeVisitor +{ + public: + + ShapeVisitor() {} + virtual ~ShapeVisitor(); + + virtual void apply(Shape&) {} + virtual void apply(Sphere&) {} + virtual void apply(Box&) {} + virtual void apply(Cone&) {} + virtual void apply(Cylinder&) {} + virtual void apply(Capsule&) {} + virtual void apply(InfinitePlane&) {} + + virtual void apply(TriangleMesh&) {} + virtual void apply(ConvexHull&) {} + virtual void apply(HeightField&) {} + + virtual void apply(CompositeShape&) {} +}; + +class OSG_EXPORT ConstShapeVisitor +{ + public: + + ConstShapeVisitor() {} + virtual ~ConstShapeVisitor(); + + virtual void apply(const Shape&) {} + virtual void apply(const Sphere&) {} + virtual void apply(const Box&) {} + virtual void apply(const Cone&) {} + virtual void apply(const Cylinder&) {} + virtual void apply(const Capsule&) {} + virtual void apply(const InfinitePlane&) {} + + virtual void apply(const TriangleMesh&) {} + virtual void apply(const ConvexHull&) {} + virtual void apply(const HeightField&) {} + + virtual void apply(const CompositeShape&) {} +}; + +class OSG_EXPORT Sphere : public Shape +{ + public: + + Sphere(): + _center(0.0f,0.0f,0.0f), + _radius(1.0f) {} + + Sphere(const osg::Vec3& center,float radius): + _center(center), + _radius(radius) {} + + Sphere(const Sphere& sphere,const CopyOp& copyop=CopyOp::SHALLOW_COPY): + Shape(sphere,copyop), + _center(sphere._center), + _radius(sphere._radius) {} + + META_Shape(osg, Sphere); + + inline bool valid() const { return _radius>=0.0f; } + + inline void set(const Vec3& center,float radius) + { + _center = center; + _radius = radius; + } + + inline void setCenter(const Vec3& center) { _center = center; } + inline const Vec3& getCenter() const { return _center; } + + inline void setRadius(float radius) { _radius = radius; } + inline float getRadius() const { return _radius; } + + protected: + + virtual ~Sphere(); + + Vec3 _center; + float _radius; + +}; + +class OSG_EXPORT Box : public Shape +{ + public: + + Box(): + _center(0.0f,0.0f,0.0f), + _halfLengths(0.5f,0.5f,0.5f) {} + + Box(const osg::Vec3& center,float width): + _center(center), + _halfLengths(width*0.5f,width*0.5f,width*0.5f) {} + + Box(const osg::Vec3& center,float lengthX,float lengthY, float lengthZ): + _center(center), + _halfLengths(lengthX*0.5f,lengthY*0.5f,lengthZ*0.5f) {} + + Box(const Box& box,const CopyOp& copyop=CopyOp::SHALLOW_COPY): + Shape(box,copyop), + _center(box._center), + _halfLengths(box._halfLengths), + _rotation(box._rotation) {} + + META_Shape(osg, Box); + + inline bool valid() const { return _halfLengths.x()>=0.0f; } + + inline void set(const Vec3& center,const Vec3& halfLengths) + { + _center = center; + _halfLengths = halfLengths; + } + + inline void setCenter(const Vec3& center) { _center = center; } + inline const Vec3& getCenter() const { return _center; } + + inline void setHalfLengths(const Vec3& halfLengths) { _halfLengths = halfLengths; } + inline const Vec3& getHalfLengths() const { return _halfLengths; } + + inline void setRotation(const Quat& quat) { _rotation = quat; } + inline const Quat& getRotation() const { return _rotation; } + inline Matrix computeRotationMatrix() const { return Matrix(_rotation); } + inline bool zeroRotation() const { return _rotation.zeroRotation(); } + + protected: + + virtual ~Box(); + + Vec3 _center; + Vec3 _halfLengths; + Quat _rotation; + +}; + + + +class OSG_EXPORT Cone : public Shape +{ + public: + + Cone(): + _center(0.0f,0.0f,0.0f), + _radius(1.0f), + _height(1.0f) {} + + Cone(const osg::Vec3& center,float radius,float height): + _center(center), + _radius(radius), + _height(height) {} + + Cone(const Cone& cone,const CopyOp& copyop=CopyOp::SHALLOW_COPY): + Shape(cone,copyop), + _center(cone._center), + _radius(cone._radius), + _height(cone._height), + _rotation(cone._rotation) {} + + META_Shape(osg, Cone); + + inline bool valid() const { return _radius>=0.0f; } + + inline void set(const Vec3& center,float radius, float height) + { + _center = center; + _radius = radius; + _height = height; + } + + inline void setCenter(const Vec3& center) { _center = center; } + inline const Vec3& getCenter() const { return _center; } + + inline void setRadius(float radius) { _radius = radius; } + inline float getRadius() const { return _radius; } + + inline void setHeight(float height) { _height = height; } + inline float getHeight() const { return _height; } + + inline void setRotation(const Quat& quat) { _rotation = quat; } + inline const Quat& getRotation() const { return _rotation; } + inline Matrix computeRotationMatrix() const { return Matrix(_rotation); } + inline bool zeroRotation() const { return _rotation.zeroRotation(); } + + inline float getBaseOffsetFactor() const { return 0.25f; } + inline float getBaseOffset() const { return -getBaseOffsetFactor()*getHeight(); } + + protected: + + virtual ~Cone(); + + Vec3 _center; + float _radius; + float _height; + + Quat _rotation; +}; + +class OSG_EXPORT Cylinder : public Shape +{ + public: + + Cylinder(): + _center(0.0f,0.0f,0.0f), + _radius(1.0f), + _height(1.0f) {} + + Cylinder(const osg::Vec3& center,float radius,float height): + _center(center), + _radius(radius), + _height(height) {} + + Cylinder(const Cylinder& cylinder,const CopyOp& copyop=CopyOp::SHALLOW_COPY): + Shape(cylinder,copyop), + _center(cylinder._center), + _radius(cylinder._radius), + _height(cylinder._height), + _rotation(cylinder._rotation) {} + + META_Shape(osg, Cylinder); + + inline bool valid() const { return _radius>=0.0f; } + + inline void set(const Vec3& center,float radius, float height) + { + _center = center; + _radius = radius; + _height = height; + } + + inline void setCenter(const Vec3& center) { _center = center; } + inline const Vec3& getCenter() const { return _center; } + + inline void setRadius(float radius) { _radius = radius; } + inline float getRadius() const { return _radius; } + + inline void setHeight(float height) { _height = height; } + inline float getHeight() const { return _height; } + + inline void setRotation(const Quat& quat) { _rotation = quat; } + inline const Quat& getRotation() const { return _rotation; } + inline Matrix computeRotationMatrix() const { return Matrix(_rotation); } + bool zeroRotation() const { return _rotation.zeroRotation(); } + + protected: + + virtual ~Cylinder(); + + Vec3 _center; + float _radius; + float _height; + Quat _rotation; +}; + +class OSG_EXPORT Capsule : public Shape +{ + public: + + Capsule(): + _center(0.0f,0.0f,0.0f), + _radius(1.0f), + _height(1.0f) {} + + Capsule(const osg::Vec3& center,float radius,float height): + _center(center), + _radius(radius), + _height(height) {} + + Capsule(const Capsule& capsule,const CopyOp& copyop=CopyOp::SHALLOW_COPY): + Shape(capsule,copyop), + _center(capsule._center), + _radius(capsule._radius), + _height(capsule._height), + _rotation(capsule._rotation) {} + + META_Shape(osg, Capsule); + + inline bool valid() const { return _radius>=0.0f; } + + inline void set(const Vec3& center,float radius, float height) + { + _center = center; + _radius = radius; + _height = height; + } + + inline void setCenter(const Vec3& center) { _center = center; } + inline const Vec3& getCenter() const { return _center; } + + inline void setRadius(float radius) { _radius = radius; } + inline float getRadius() const { return _radius; } + + inline void setHeight(float height) { _height = height; } + inline float getHeight() const { return _height; } + + inline void setRotation(const Quat& quat) { _rotation = quat; } + inline const Quat& getRotation() const { return _rotation; } + inline Matrix computeRotationMatrix() const { return Matrix(_rotation); } + bool zeroRotation() const { return _rotation.zeroRotation(); } + + protected: + + virtual ~Capsule(); + + Vec3 _center; + float _radius; + float _height; + Quat _rotation; +}; + +class OSG_EXPORT InfinitePlane : public Shape, public Plane +{ + public: + InfinitePlane() {} + + InfinitePlane(const InfinitePlane& plane,const CopyOp& copyop=CopyOp::SHALLOW_COPY): + Shape(plane,copyop), + Plane(plane) {} + + META_Shape(osg, InfinitePlane); + + protected: + + virtual ~InfinitePlane(); +}; + +/** Exists to support collision detection engines not for doing rendering, use \ref osg::Geometry instead. + */ +class OSG_EXPORT TriangleMesh : public Shape +{ + public: + + TriangleMesh() {} + + TriangleMesh(const TriangleMesh& mesh,const CopyOp& copyop=CopyOp::SHALLOW_COPY): + Shape(mesh,copyop), + _vertices(mesh._vertices), + _indices(mesh._indices) {} + + META_Shape(osg, TriangleMesh); + + + void setVertices(Vec3Array* vertices) { _vertices = vertices; } + Vec3Array* getVertices() { return _vertices.get(); } + const Vec3Array* getVertices() const { return _vertices.get(); } + + + void setIndices(IndexArray* indices) { _indices = indices; } + IndexArray* getIndices() { return _indices.get(); } + const IndexArray* getIndices() const { return _indices.get(); } + + protected: + + virtual ~TriangleMesh(); + + ref_ptr _vertices; + ref_ptr _indices; + +}; + +class OSG_EXPORT ConvexHull : public TriangleMesh +{ + public: + + ConvexHull() {} + + ConvexHull(const ConvexHull& hull,const CopyOp& copyop=CopyOp::SHALLOW_COPY): + TriangleMesh(hull,copyop) {} + + META_Shape(osg, TriangleMesh); + + protected: + + virtual ~ConvexHull(); +}; + +class OSG_EXPORT HeightField : public Shape +{ + public: + + HeightField(); + + HeightField(const HeightField& mesh,const CopyOp& copyop=CopyOp::SHALLOW_COPY); + + META_Shape(osg, HeightField); + + typedef std::vector HeightList; + + void allocate(unsigned int numColumns,unsigned int numRows); + + inline unsigned int getNumColumns() const { return _columns; } + inline unsigned int getNumRows() const { return _rows; } + + inline void setOrigin(const osg::Vec3& origin) { _origin = origin; } + inline const osg::Vec3& getOrigin() const { return _origin; } + + inline void setXInterval(float dx) { _dx = dx; } + inline float getXInterval() const { return _dx; } + + inline void setYInterval(float dy) { _dy = dy; } + inline float getYInterval() const { return _dy; } + + /** Get the FloatArray height data.*/ + osg::FloatArray* getFloatArray() { return _heights.get(); } + + /** Get the const FloatArray height data.*/ + const osg::FloatArray* getFloatArray() const { return _heights.get(); } + + HeightList& getHeightList() { return _heights->asVector(); } + + const HeightList& getHeightList() const { return _heights->asVector(); } + + /** Set the height of the skirt to render around the edge of HeightField. + * The skirt is used as a means of disguising edge boundaries between adjacent HeightField, + * particularly of ones with different resolutions.*/ + void setSkirtHeight(float skirtHeight) { _skirtHeight = skirtHeight; } + + /** Get the height of the skirt to render around the edge of HeightField.*/ + float getSkirtHeight() const { return _skirtHeight; } + + /** Set the width in number of cells in from the edge that the height field should be rendered from. + * This exists to allow gradient and curvature continutity to be maintained between adjacent HeightField, where + * the border cells will overlap adjacent HeightField.*/ + void setBorderWidth(unsigned int borderWidth) { _borderWidth = borderWidth; } + + /** Get the width in number of cells in from the edge that the height field should be rendered from.*/ + unsigned int getBorderWidth() const { return _borderWidth; } + + inline void setRotation(const Quat& quat) { _rotation = quat; } + inline const Quat& getRotation() const { return _rotation; } + inline Matrix computeRotationMatrix() const { return Matrix(_rotation); } + inline bool zeroRotation() const { return _rotation.zeroRotation(); } + + /* set a single height point in the height field */ + inline void setHeight(unsigned int c,unsigned int r,float value) + { + (*_heights)[c+r*_columns] = value; + } + + /* Get address of single height point in the height field, allows user to change. */ + inline float& getHeight(unsigned int c,unsigned int r) + { + return (*_heights)[c+r*_columns]; + } + + /* Get value of single height point in the height field, not editable. */ + inline float getHeight(unsigned int c,unsigned int r) const + { + return (*_heights)[c+r*_columns]; + } + + inline Vec3 getVertex(unsigned int c,unsigned int r) const + { + return Vec3(_origin.x()+getXInterval()*(float)c, + _origin.y()+getYInterval()*(float)r, + _origin.z()+(*_heights)[c+r*_columns]); + } + + Vec3 getNormal(unsigned int c,unsigned int r) const; + + Vec2 getHeightDelta(unsigned int c,unsigned int r) const; + + protected: + + virtual ~HeightField(); + + unsigned int _columns,_rows; + + osg::Vec3 _origin; // _origin is the min value of the X and Y coordinates. + float _dx; + float _dy; + + float _skirtHeight; + unsigned int _borderWidth; + + Quat _rotation; + osg::ref_ptr _heights; + +}; + +typedef HeightField Grid; + + +class OSG_EXPORT CompositeShape : public Shape +{ + public: + + + + typedef std::vector< ref_ptr > ChildList; + + CompositeShape() {} + + CompositeShape(const CompositeShape& cs,const CopyOp& copyop=CopyOp::SHALLOW_COPY): + Shape(cs,copyop), + _children(cs._children) {} + + META_Shape(osg, CompositeShape); + + /** Set the shape that encloses all of the children.*/ + void setShape(Shape* shape) { _shape = shape; } + + /** Get the shape that encloses all of the children.*/ + Shape* getShape() { return _shape.get(); } + + /** Get the const shape that encloses all of the children.*/ + const Shape* getShape() const { return _shape.get(); } + + /** Get the number of children of this composite shape.*/ + unsigned int getNumChildren() const { return static_cast(_children.size()); } + + /** Get a child.*/ + Shape* getChild(unsigned int i) { return _children[i].get(); } + + /** Get a const child.*/ + const Shape* getChild(unsigned int i) const { return _children[i].get(); } + + /** Add a child to the list.*/ + void addChild(Shape* shape) { _children.push_back(shape); } + + /** remove a child from the list.*/ + void removeChild(unsigned int i) { _children.erase(_children.begin()+i); } + + /** find the index number of child, if child is not found then it returns getNumChildren(), + * so should be used in similar style to STL's result!=end().*/ + unsigned int findChildNo(Shape* shape) const + { + for (unsigned int childNo=0;childNo<_children.size();++childNo) + { + if (_children[childNo]==shape) return childNo; + } + return static_cast(_children.size()); // node not found. + + } + + protected: + + virtual ~CompositeShape(); + + ref_ptr _shape; + ChildList _children; + +}; + +} + +#endif diff --git a/libs/include/android/osg/ShapeDrawable b/libs/include/android/osg/ShapeDrawable new file mode 100755 index 0000000..9f69152 --- /dev/null +++ b/libs/include/android/osg/ShapeDrawable @@ -0,0 +1,201 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_SHAPEDRAWABLE +#define OSG_SHAPEDRAWABLE 1 + +#include +#include +#include +#include +#include +#include + +namespace osg { + +/** Describe several hints that can be passed to a Tessellator (like the one used + * by \c ShapeDrawable) as a mean to try to influence the way it works. + */ +class TessellationHints : public Object +{ + public: + + TessellationHints(): + _TessellationMode(USE_SHAPE_DEFAULTS), + _detailRatio(1.0f), + _targetNumFaces(100), + _createFrontFace(true), + _createBackFace(false), + _createNormals(true), + _createTextureCoords(false), + _createTop(true), + _createBody(true), + _createBottom(true) {} + + + TessellationHints(const TessellationHints& tess, const CopyOp& copyop=CopyOp::SHALLOW_COPY): + Object(tess,copyop), + _TessellationMode(tess._TessellationMode), + _detailRatio(tess._detailRatio), + _targetNumFaces(tess._targetNumFaces), + _createFrontFace(tess._createFrontFace), + _createBackFace(tess._createBackFace), + _createNormals(tess._createNormals), + _createTextureCoords(tess._createTextureCoords), + _createTop(tess._createTop), + _createBody(tess._createBody), + _createBottom(tess._createBottom) {} + + META_Object(osg,TessellationHints); + + + enum TessellationMode + { + USE_SHAPE_DEFAULTS, + USE_TARGET_NUM_FACES + }; + + inline void setTessellationMode(TessellationMode mode) { _TessellationMode=mode; } + inline TessellationMode getTessellationMode() const { return _TessellationMode; } + + inline void setDetailRatio(float ratio) { _detailRatio = ratio; } + inline float getDetailRatio() const { return _detailRatio; } + + inline void setTargetNumFaces(unsigned int target) { _targetNumFaces=target; } + inline unsigned int getTargetNumFaces() const { return _targetNumFaces; } + + inline void setCreateFrontFace(bool on) { _createFrontFace=on; } + inline bool getCreateFrontFace() const { return _createFrontFace; } + + inline void setCreateBackFace(bool on) { _createBackFace=on; } + inline bool getCreateBackFace() const { return _createBackFace; } + + inline void setCreateNormals(bool on) { _createNormals=on; } + inline bool getCreateNormals() const { return _createNormals; } + + inline void setCreateTextureCoords(bool on) { _createTextureCoords=on; } + inline bool getCreateTextureCoords() const { return _createTextureCoords; } + + inline void setCreateTop(bool on) { _createTop=on; } + inline bool getCreateTop() const { return _createTop; } + + inline void setCreateBody(bool on) { _createBody=on; } + inline bool getCreateBody() const { return _createBody; } + + inline void setCreateBottom(bool on) { _createBottom=on; } + inline bool getCreateBottom() const { return _createBottom; } + + protected: + + ~TessellationHints() {} + + + TessellationMode _TessellationMode; + + float _detailRatio; + unsigned int _targetNumFaces; + + bool _createFrontFace; + bool _createBackFace; + bool _createNormals; + bool _createTextureCoords; + + bool _createTop; + bool _createBody; + bool _createBottom; + +}; + + +/** Allow the use of Shapes as Drawables, so that they can + * be rendered with reduced effort. The implementation of \c ShapeDrawable is + * not geared to efficiency; it's better to think of it as a convenience to + * render Shapes easily (perhaps for test or debugging purposes) than + * as the right way to render basic shapes in some efficiency-critical section + * of code. + */ +class OSG_EXPORT ShapeDrawable : public Drawable +{ + public: + + ShapeDrawable(); + + ShapeDrawable(Shape* shape, TessellationHints* hints=0); + + /** Copy constructor using CopyOp to manage deep vs shallow copy.*/ + ShapeDrawable(const ShapeDrawable& pg,const CopyOp& copyop=CopyOp::SHALLOW_COPY); + + virtual Object* cloneType() const { return new ShapeDrawable(); } + virtual Object* clone(const CopyOp& copyop) const { return new ShapeDrawable(*this,copyop); } + virtual bool isSameKindAs(const Object* obj) const { return dynamic_cast(obj)!=NULL; } + virtual const char* libraryName() const { return "osg"; } + virtual const char* className() const { return "ShapeDrawable"; } + + /** Set the color of the shape.*/ + void setColor(const Vec4& color); + + /** Get the color of the shape.*/ + const Vec4& getColor() const { return _color; } + + void setTessellationHints(TessellationHints* hints); + + TessellationHints* getTessellationHints() { return _tessellationHints.get(); } + const TessellationHints* getTessellationHints() const { return _tessellationHints.get(); } + + + + /** Draw ShapeDrawable directly ignoring an OpenGL display list which + * could be attached. This is the internal draw method which does the + * drawing itself, and is the method to override when deriving from + * ShapeDrawable for user-drawn objects. + */ + virtual void drawImplementation(RenderInfo& renderInfo) const; + + /* Not all virtual overloads of these methods are overridden in this class, so + bring the base class implementation in to avoid hiding the non-used ones. */ + using Drawable::supports; + using Drawable::accept; + + /** Return false, osg::ShapeDrawable does not support accept(AttributeFunctor&).*/ + virtual bool supports(const AttributeFunctor&) const { return false; } + + /** Return true, osg::ShapeDrawable does support accept(Drawable::ConstAttributeFunctor&).*/ + virtual bool supports(const Drawable::ConstAttributeFunctor&) const { return true; } + + /** Accept a Drawable::ConstAttributeFunctor and call its methods to tell it about the internal attributes that this Drawable has.*/ + virtual void accept(Drawable::ConstAttributeFunctor& af) const; + + /** Return true, osg::ShapeDrawable does support accept(PrimitiveFunctor&) .*/ + virtual bool supports(const PrimitiveFunctor&) const { return true; } + + /** Accept a PrimitiveFunctor and call its methods to tell it about the internal primitives that this Drawable has.*/ + virtual void accept(PrimitiveFunctor& pf) const; + + virtual BoundingBox computeBound() const; + + protected: + + ShapeDrawable& operator = (const ShapeDrawable&) { return *this;} + + virtual ~ShapeDrawable(); + + Vec4 _color; + + ref_ptr _tessellationHints; + +}; + + +} + +#endif diff --git a/libs/include/android/osg/State b/libs/include/android/osg/State new file mode 100755 index 0000000..37d4519 --- /dev/null +++ b/libs/include/android/osg/State @@ -0,0 +1,2757 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_STATE +#define OSG_STATE 1 + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#ifndef GL_FOG_COORDINATE_ARRAY + #ifdef GL_FOG_COORDINATE_ARRAY_EXT + #define GL_FOG_COORDINATE_ARRAY GL_FOG_COORDINATE_ARRAY_EXT + #else + #define GL_FOG_COORDINATE_ARRAY 0x8457 + #endif +#endif + +#ifndef GL_SECONDARY_COLOR_ARRAY + #ifdef GL_SECONDARY_COLOR_ARRAY_EXT + #define GL_SECONDARY_COLOR_ARRAY GL_SECONDARY_COLOR_ARRAY_EXT + #else + #define GL_SECONDARY_COLOR_ARRAY 0x845E + #endif +#endif + +#if !defined(GL_EXT_timer_query) && !defined(OSG_GL3_AVAILABLE) + #ifdef _WIN32 + typedef __int64 GLint64EXT; + typedef unsigned __int64 GLuint64EXT; + #else + typedef long long int GLint64EXT; + typedef unsigned long long int GLuint64EXT; + #endif +#endif + +namespace osg { + +/** macro for use with osg::StateAttribute::apply methods for detecting and + * reporting OpenGL error messages.*/ +#define OSG_GL_DEBUG(message) \ + if (state.getFineGrainedErrorDetection()) \ + { \ + GLenum errorNo = glGetError(); \ + if (errorNo!=GL_NO_ERROR) \ + { \ + osg::notify(WARN)<<"Warning: detected OpenGL error '"<getName()]; + up.first = const_cast(uniform); + up.second = value; + } + + + /** Push stateset onto state stack.*/ + void pushStateSet(const StateSet* dstate); + + /** Pop stateset off state stack.*/ + void popStateSet(); + + /** pop all statesets off state stack, ensuring it is empty ready for the next frame. + * Note, to return OpenGL to default state, one should do any state.popAllStatSets(); state.apply().*/ + void popAllStateSets(); + + /** Insert stateset onto state stack.*/ + void insertStateSet(unsigned int pos,const StateSet* dstate); + + /** Pop stateset off state stack.*/ + void removeStateSet(unsigned int pos); + + /** Get the number of StateSet's on the StateSet stack.*/ + unsigned int getStateSetStackSize() { return static_cast(_stateStateStack.size()); } + + /** Pop StateSet's for the StateSet stack till its size equals the specified size.*/ + void popStateSetStackToSize(unsigned int size) { while (_stateStateStack.size()>size) popStateSet(); } + + typedef std::vector StateSetStack; + + /** Get the StateSet stack.*/ + StateSetStack& getStateSetStack() { return _stateStateStack; } + + + /** Copy the modes and attributes which capture the current state.*/ + void captureCurrentState(StateSet& stateset) const; + + /** reset the state object to an empty stack.*/ + void reset(); + + + inline const Viewport* getCurrentViewport() const + { + return static_cast(getLastAppliedAttribute(osg::StateAttribute::VIEWPORT)); + } + + + void setInitialViewMatrix(const osg::RefMatrix* matrix); + + inline const osg::Matrix& getInitialViewMatrix() const { return *_initialViewMatrix; } + inline const osg::Matrix& getInitialInverseViewMatrix() const { return _initialInverseViewMatrix; } + + void applyProjectionMatrix(const osg::RefMatrix* matrix); + + inline const osg::Matrix& getProjectionMatrix() const { return *_projection; } + + void applyModelViewMatrix(const osg::RefMatrix* matrix); + void applyModelViewMatrix(const osg::Matrix&); + + const osg::Matrix& getModelViewMatrix() const { return *_modelView; } + + void setUseModelViewAndProjectionUniforms(bool flag) { _useModelViewAndProjectionUniforms = flag; } + bool getUseModelViewAndProjectionUniforms() const { return _useModelViewAndProjectionUniforms; } + + void updateModelViewAndProjectionMatrixUniforms(); + + void applyModelViewAndProjectionUniformsIfRequired(); + + osg::Uniform* getModelViewMatrixUniform() { return _modelViewMatrixUniform.get(); } + osg::Uniform* getProjectionMatrixUniform() { return _projectionMatrixUniform.get(); } + osg::Uniform* getModelViewProjectionMatrixUniform() { return _modelViewProjectionMatrixUniform.get(); } + osg::Uniform* getNormalMatrixUniform() { return _normalMatrixUniform.get(); } + + + Polytope getViewFrustum() const; + + + void setUseVertexAttributeAliasing(bool flag) { _useVertexAttributeAliasing = flag; } + bool getUseVertexAttributeAliasing() const { return _useVertexAttributeAliasing ; } + + typedef std::vector VertexAttribAliasList; + + /** Reset the vertex attribute aliasing to osg's default. This method needs to be called before render anything unless you really know what you're doing !*/ + void resetVertexAttributeAlias(bool compactAliasing=true); + + /** Set the vertex attribute aliasing for "vertex". This method needs to be called before render anything unless you really know what you're doing !*/ + void setVertexAlias(const VertexAttribAlias& alias) { _vertexAlias = alias; } + const VertexAttribAlias& getVertexAlias() { return _vertexAlias; } + + /** Set the vertex attribute aliasing for "normal". This method needs to be called before render anything unless you really know what you're doing !*/ + void setNormalAlias(const VertexAttribAlias& alias) { _normalAlias = alias; } + const VertexAttribAlias& getNormalAlias() { return _normalAlias; } + + /** Set the vertex attribute aliasing for "color". This method needs to be called before render anything unless you really know what you're doing !*/ + void setColorAlias(const VertexAttribAlias& alias) { _colorAlias = alias; } + const VertexAttribAlias& getColorAlias() { return _colorAlias; } + + /** Set the vertex attribute aliasing for "secondary color". This method needs to be called before render anything unless you really know what you're doing !*/ + void setSecondaryColorAlias(const VertexAttribAlias& alias) { _secondaryColorAlias = alias; } + const VertexAttribAlias& getSecondaryColorAlias() { return _secondaryColorAlias; } + + /** Set the vertex attribute aliasing for "fog coord". This method needs to be called before render anything unless you really know what you're doing !*/ + void setFogCoordAlias(const VertexAttribAlias& alias) { _fogCoordAlias = alias; } + const VertexAttribAlias& getFogCoordAlias() { return _fogCoordAlias; } + + /** Set the vertex attribute aliasing list for texture coordinates. This method needs to be called before render anything unless you really know what you're doing !*/ + void setTexCoordAliasList(const VertexAttribAliasList& aliasList) { _texCoordAliasList = aliasList; } + const VertexAttribAliasList& getTexCoordAliasList() { return _texCoordAliasList; } + + /** Set the vertex attribute binding list. This method needs to be called before render anything unless you really know what you're doing !*/ + void setAttributeBindingList(const Program::AttribBindingList& attribBindingList) { _attributeBindingList = attribBindingList; } + const Program::AttribBindingList& getAttributeBindingList() { return _attributeBindingList; } + + bool convertVertexShaderSourceToOsgBuiltIns(std::string& source) const; + + + /** Apply stateset.*/ + void apply(const StateSet* dstate); + + /** Updates the OpenGL state so that it matches the \c StateSet at the + * top of the stack of StateSets maintained internally by a + * \c State. + */ + void apply(); + + /** Apply any shader composed state.*/ + void applyShaderComposition(); + + /** Set whether a particular OpenGL mode is valid in the current graphics context. + * Use to disable OpenGL modes that are not supported by current graphics drivers/context.*/ + inline void setModeValidity(StateAttribute::GLMode mode,bool valid) + { + ModeStack& ms = _modeMap[mode]; + ms.valid = valid; + } + + /** Get whether a particular OpenGL mode is valid in the current graphics context. + * Use to disable OpenGL modes that are not supported by current graphics drivers/context.*/ + inline bool getModeValidity(StateAttribute::GLMode mode) + { + ModeStack& ms = _modeMap[mode]; + return ms.valid; + } + + inline void setGlobalDefaultModeValue(StateAttribute::GLMode mode,bool enabled) + { + ModeStack& ms = _modeMap[mode]; + ms.global_default_value = enabled; + } + + inline bool getGlobalDefaultModeValue(StateAttribute::GLMode mode) + { + return _modeMap[mode].global_default_value; + } + + + /** Apply an OpenGL mode if required. This is a wrapper around + * \c glEnable() and \c glDisable(), that just actually calls these + * functions if the \c enabled flag is different than the current + * state. + * @return \c true if the state was actually changed. \c false + * otherwise. Notice that a \c false return does not indicate + * an error, it just means that the mode was already set to the + * same value as the \c enabled parameter. + */ + inline bool applyMode(StateAttribute::GLMode mode,bool enabled) + { + ModeStack& ms = _modeMap[mode]; + ms.changed = true; + return applyMode(mode,enabled,ms); + } + + inline void setGlobalDefaultTextureModeValue(unsigned int unit, StateAttribute::GLMode mode,bool enabled) + { + ModeMap& modeMap = getOrCreateTextureModeMap(unit); + ModeStack& ms = modeMap[mode]; + ms.global_default_value = enabled; + } + + inline bool getGlobalDefaultTextureModeValue(unsigned int unit, StateAttribute::GLMode mode) + { + ModeMap& modeMap = getOrCreateTextureModeMap(unit); + ModeStack& ms = modeMap[mode]; + return ms.global_default_value; + } + + inline bool applyTextureMode(unsigned int unit, StateAttribute::GLMode mode,bool enabled) + { + ModeMap& modeMap = getOrCreateTextureModeMap(unit); + ModeStack& ms = modeMap[mode]; + ms.changed = true; + return applyModeOnTexUnit(unit,mode,enabled,ms); + } + + inline void setGlobalDefaultAttribute(const StateAttribute* attribute) + { + AttributeStack& as = _attributeMap[attribute->getTypeMemberPair()]; + as.global_default_attribute = attribute; + } + + inline const StateAttribute* getGlobalDefaultAttribute(StateAttribute::Type type, unsigned int member=0) + { + AttributeStack& as = _attributeMap[StateAttribute::TypeMemberPair(type,member)]; + return as.global_default_attribute.get(); + } + + /** Apply an attribute if required. */ + inline bool applyAttribute(const StateAttribute* attribute) + { + AttributeStack& as = _attributeMap[attribute->getTypeMemberPair()]; + as.changed = true; + return applyAttribute(attribute,as); + } + + inline void setGlobalDefaultTextureAttribute(unsigned int unit, const StateAttribute* attribute) + { + AttributeMap& attributeMap = getOrCreateTextureAttributeMap(unit); + AttributeStack& as = attributeMap[attribute->getTypeMemberPair()]; + as.global_default_attribute = attribute; + } + + inline const StateAttribute* getGlobalDefaultTextureAttribute(unsigned int unit, StateAttribute::Type type, unsigned int member = 0) + { + AttributeMap& attributeMap = getOrCreateTextureAttributeMap(unit); + AttributeStack& as = attributeMap[StateAttribute::TypeMemberPair(type,member)]; + return as.global_default_attribute.get(); + } + + + inline bool applyTextureAttribute(unsigned int unit, const StateAttribute* attribute) + { + AttributeMap& attributeMap = getOrCreateTextureAttributeMap(unit); + AttributeStack& as = attributeMap[attribute->getTypeMemberPair()]; + as.changed = true; + return applyAttributeOnTexUnit(unit,attribute,as); + } + + /** Mode has been set externally, update state to reflect this setting.*/ + void haveAppliedMode(StateAttribute::GLMode mode,StateAttribute::GLModeValue value); + + /** Mode has been set externally, therefore dirty the associated mode in osg::State + * so it is applied on next call to osg::State::apply(..)*/ + void haveAppliedMode(StateAttribute::GLMode mode); + + /** Attribute has been applied externally, update state to reflect this setting.*/ + void haveAppliedAttribute(const StateAttribute* attribute); + + /** Attribute has been applied externally, + * and therefore this attribute type has been dirtied + * and will need to be re-applied on next osg::State.apply(..). + * note, if you have an osg::StateAttribute which you have applied externally + * then use the have_applied(attribute) method as this will cause the osg::State to + * track the current state more accurately and enable lazy state updating such + * that only changed state will be applied.*/ + void haveAppliedAttribute(StateAttribute::Type type, unsigned int member=0); + + /** Get whether the current specified mode is enabled (true) or disabled (false).*/ + bool getLastAppliedMode(StateAttribute::GLMode mode) const; + + /** Get the current specified attribute, return NULL if one has not yet been applied.*/ + const StateAttribute* getLastAppliedAttribute(StateAttribute::Type type, unsigned int member=0) const; + + /** texture Mode has been set externally, update state to reflect this setting.*/ + void haveAppliedTextureMode(unsigned int unit, StateAttribute::GLMode mode,StateAttribute::GLModeValue value); + + /** texture Mode has been set externally, therefore dirty the associated mode in osg::State + * so it is applied on next call to osg::State::apply(..)*/ + void haveAppliedTextureMode(unsigned int unit, StateAttribute::GLMode mode); + + /** texture Attribute has been applied externally, update state to reflect this setting.*/ + void haveAppliedTextureAttribute(unsigned int unit, const StateAttribute* attribute); + + /** texture Attribute has been applied externally, + * and therefore this attribute type has been dirtied + * and will need to be re-applied on next osg::State.apply(..). + * note, if you have an osg::StateAttribute which you have applied externally + * then use the have_applied(attribute) method as this will the osg::State to + * track the current state more accurately and enable lazy state updating such + * that only changed state will be applied.*/ + void haveAppliedTextureAttribute(unsigned int unit, StateAttribute::Type type, unsigned int member=0); + + /** Get whether the current specified texture mode is enabled (true) or disabled (false).*/ + bool getLastAppliedTextureMode(unsigned int unit, StateAttribute::GLMode mode) const; + + /** Get the current specified texture attribute, return NULL if one has not yet been applied.*/ + const StateAttribute* getLastAppliedTextureAttribute(unsigned int unit, StateAttribute::Type type, unsigned int member=0) const; + + + /** Dirty the modes previously applied in osg::State.*/ + void dirtyAllModes(); + + /** Dirty the modes attributes previously applied in osg::State.*/ + void dirtyAllAttributes(); + + /** disable the vertex, normal, color, tex coords, secondary color, fog coord and index arrays.*/ + void disableAllVertexArrays(); + + /** dirty the vertex, normal, color, tex coords, secondary color, fog coord and index arrays.*/ + void dirtyAllVertexArrays(); + + + void setCurrentVertexBufferObject(osg::GLBufferObject* vbo) { _currentVBO = vbo; } + const GLBufferObject* getCurrentVertexBufferObject() { return _currentVBO; } + inline void bindVertexBufferObject(osg::GLBufferObject* vbo) + { + if (vbo == _currentVBO) return; + if (vbo->isDirty()) vbo->compileBuffer(); + else vbo->bindBuffer(); + _currentVBO = vbo; + } + + inline void unbindVertexBufferObject() + { + if (!_currentVBO) return; + _glBindBuffer(GL_ARRAY_BUFFER_ARB,0); + _currentVBO = 0; + } + + void setCurrentElementBufferObject(osg::GLBufferObject* ebo) { _currentEBO = ebo; } + const GLBufferObject* getCurrentElementBufferObject() { return _currentEBO; } + + inline void bindElementBufferObject(osg::GLBufferObject* ebo) + { + if (ebo == _currentEBO) return; + if (ebo->isDirty()) ebo->compileBuffer(); + else ebo->bindBuffer(); + _currentEBO = ebo; + } + + inline void unbindElementBufferObject() + { + if (!_currentEBO) return; + _glBindBuffer(GL_ELEMENT_ARRAY_BUFFER_ARB,0); + _currentEBO = 0; + } + + void setCurrentPixelBufferObject(osg::GLBufferObject* pbo) { _currentPBO = pbo; } + const GLBufferObject* getCurrentPixelBufferObject() { return _currentPBO; } + + inline void bindPixelBufferObject(osg::GLBufferObject* pbo) + { + if (pbo == _currentPBO) return; + + if (pbo->isDirty()) pbo->compileBuffer(); + else pbo->bindBuffer(); + + _currentPBO = pbo; + } + + inline void unbindPixelBufferObject() + { + if (!_currentPBO) return; + + _glBindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB,0); + _currentPBO = 0; + } + + typedef std::vector IndicesGLushort; + IndicesGLushort _quadIndicesGLushort[4]; + + typedef std::vector IndicesGLuint; + IndicesGLuint _quadIndicesGLuint[4]; + + void drawQuads(GLint first, GLsizei count, GLsizei primCount=0); + + inline void glDrawArraysInstanced(GLenum mode, GLint first, GLsizei count, GLsizei primcount) + { + if (primcount>=1 && _glDrawArraysInstanced!=0) _glDrawArraysInstanced(mode, first, count, primcount); + else glDrawArrays(mode, first, count); + } + + inline void glDrawElementsInstanced(GLenum mode, GLsizei count, GLenum type, const GLvoid *indices, GLsizei primcount ) + { + if (primcount>=1 && _glDrawElementsInstanced!=0) _glDrawElementsInstanced(mode, count, type, indices, primcount); + else glDrawElements(mode, count, type, indices); + } + + + inline void Vertex(float x, float y, float z, float w=1.0f) + { + #if defined(OSG_GL_VERTEX_FUNCS_AVAILABLE) && !defined(OSG_GLES1_AVAILABLE) + if (_useVertexAttributeAliasing) _glVertexAttrib4f( _vertexAlias._location, x,y,z,w); + else glVertex4f(x,y,z,w); + #else + _glVertexAttrib4f( _vertexAlias._location, x,y,z,w); + #endif + } + + inline void Color(float r, float g, float b, float a=1.0f) + { + #ifdef OSG_GL_VERTEX_FUNCS_AVAILABLE + if (_useVertexAttributeAliasing) _glVertexAttrib4f( _colorAlias._location, r,g,b,a); + else glColor4f(r,g,b,a); + #else + _glVertexAttrib4f( _colorAlias._location, r,g,b,a); + #endif + } + + void Normal(float x, float y, float z) + { + #ifdef OSG_GL_VERTEX_FUNCS_AVAILABLE + if (_useVertexAttributeAliasing) _glVertexAttrib4f( _normalAlias._location, x,y,z,0.0); + else glNormal3f(x,y,z); + #else + _glVertexAttrib4f( _normalAlias._location, x,y,z,0.0); + #endif + } + + void TexCoord(float x, float y=0.0f, float z=0.0f, float w=1.0f) + { + #if !defined(OSG_GLES1_AVAILABLE) + #ifdef OSG_GL_VERTEX_FUNCS_AVAILABLE + if (_useVertexAttributeAliasing) _glVertexAttrib4f( _texCoordAliasList[0]._location, x,y,z,w); + else glTexCoord4f(x,y,z,w); + #else + _glVertexAttrib4f( _texCoordAliasList[0]._location, x,y,z,w); + #endif + #endif + } + + void MultiTexCoord(unsigned int unit, float x, float y=0.0f, float z=0.0f, float w=1.0f) + { + #if !defined(OSG_GLES1_AVAILABLE) + #ifdef OSG_GL_VERTEX_FUNCS_AVAILABLE + if (_useVertexAttributeAliasing) _glVertexAttrib4f( _texCoordAliasList[unit]._location, x,y,z,w); + else _glMultiTexCoord4f(GL_TEXTURE0+unit,x,y,z,w); + #else + _glVertexAttrib4f( _texCoordAliasList[unit]._location, x,y,z,w); + #endif + #endif + } + + void VerteAttrib(unsigned int location, float x, float y=0.0f, float z=0.0f, float w=0.0f) + { + _glVertexAttrib4f( location, x,y,z,w); + } + + + /** Mark all the vertex attributes as being disabled but leave the disabling till a later call to applyDisablingOfVertexAttributes.*/ + void lazyDisablingOfVertexAttributes(); + + /** Disable all the vertex attributes that have been marked as to be disabled.*/ + void applyDisablingOfVertexAttributes(); + + /** Wrapper around glInterleavedArrays(..). + * also resets the internal array points and modes within osg::State to keep the other + * vertex array operations consistent. */ + void setInterleavedArrays( GLenum format, GLsizei stride, const GLvoid* pointer); + + /** Set the vertex pointer using an osg::Array, and manage any VBO that are required.*/ + inline void setVertexPointer(const Array* array) + { + if (array) + { + GLBufferObject* vbo = isVertexBufferObjectSupported() ? array->getOrCreateGLBufferObject(_contextID) : 0; + if (vbo) + { + bindVertexBufferObject(vbo); + setVertexPointer(array->getDataSize(),array->getDataType(),0,(const GLvoid *)(vbo->getOffset(array->getBufferIndex())),array->getNormalize()); + } + else + { + unbindVertexBufferObject(); + setVertexPointer(array->getDataSize(),array->getDataType(),0,array->getDataPointer(),array->getNormalize()); + } + } + } + + /** wrapper around glEnableClientState(GL_VERTEX_ARRAY);glVertexPointer(..); + * note, only updates values that change.*/ + inline void setVertexPointer( GLint size, GLenum type, + GLsizei stride, const GLvoid *ptr, GLboolean normalized=GL_FALSE ) + { + #ifdef OSG_GL_VERTEX_ARRAY_FUNCS_AVAILABLE + if (_useVertexAttributeAliasing) + { + setVertexAttribPointer(_vertexAlias._location, size, type, normalized, stride, ptr); + } + else + { + if (!_vertexArray._enabled || _vertexArray._dirty) + { + _vertexArray._enabled = true; + glEnableClientState(GL_VERTEX_ARRAY); + } + //if (_vertexArray._pointer!=ptr || _vertexArray._dirty) + { + _vertexArray._pointer=ptr; + glVertexPointer( size, type, stride, ptr ); + } + _vertexArray._lazy_disable = false; + _vertexArray._dirty = false; + _vertexArray._normalized = normalized; + } + #else + setVertexAttribPointer(_vertexAlias._location, size, type, normalized, stride, ptr); + #endif + } + + /** wrapper around glDisableClientState(GL_VERTEX_ARRAY). + * note, only updates values that change.*/ + inline void disableVertexPointer() + { + #ifdef OSG_GL_VERTEX_ARRAY_FUNCS_AVAILABLE + if (_useVertexAttributeAliasing) + { + disableVertexAttribPointer(_vertexAlias._location); + } + else + { + if (_vertexArray._enabled || _vertexArray._dirty) + { + _vertexArray._lazy_disable = false; + _vertexArray._enabled = false; + _vertexArray._dirty = false; + glDisableClientState(GL_VERTEX_ARRAY); + } + } + #else + disableVertexAttribPointer(_vertexAlias._location); + #endif + } + + inline void dirtyVertexPointer() + { + #ifdef OSG_GL_VERTEX_ARRAY_FUNCS_AVAILABLE + if (_useVertexAttributeAliasing) + { + dirtyVertexAttribPointer(_vertexAlias._location); + } + else + { + _vertexArray._pointer = 0; + _vertexArray._dirty = true; + } + #else + dirtyVertexAttribPointer(_vertexAlias._location); + #endif + } + + + /** Set the normal pointer using an osg::Array, and manage any VBO that are required.*/ + inline void setNormalPointer(const Array* array) + { + if (array) + { + GLBufferObject* vbo = isVertexBufferObjectSupported() ? array->getOrCreateGLBufferObject(_contextID) : 0; + if (vbo) + { + bindVertexBufferObject(vbo); + setNormalPointer(array->getDataType(),0,(const GLvoid *)(vbo->getOffset(array->getBufferIndex())),array->getNormalize()); + } + else + { + unbindVertexBufferObject(); + setNormalPointer(array->getDataType(),0,array->getDataPointer(),array->getNormalize()); + } + } + } + + /** wrapper around glEnableClientState(GL_NORMAL_ARRAY);glNormalPointer(..); + * note, only updates values that change.*/ + inline void setNormalPointer( GLenum type, GLsizei stride, + const GLvoid *ptr, GLboolean normalized=GL_FALSE ) + { + #ifdef OSG_GL_VERTEX_ARRAY_FUNCS_AVAILABLE + if (_useVertexAttributeAliasing) + { + setVertexAttribPointer(_normalAlias._location, 3, type, normalized, stride, ptr); + } + else + { + if (!_normalArray._enabled || _normalArray._dirty) + { + _normalArray._enabled = true; + glEnableClientState(GL_NORMAL_ARRAY); + } + //if (_normalArray._pointer!=ptr || _normalArray._dirty) + { + _normalArray._pointer=ptr; + glNormalPointer( type, stride, ptr ); + } + _normalArray._lazy_disable = false; + _normalArray._dirty = false; + _normalArray._normalized = normalized; + } + #else + setVertexAttribPointer(_normalAlias._location, 3, type, normalized, stride, ptr); + #endif + } + + /** wrapper around glDisableClientState(GL_NORMAL_ARRAY); + * note, only updates values that change.*/ + inline void disableNormalPointer() + { + #ifdef OSG_GL_VERTEX_ARRAY_FUNCS_AVAILABLE + if (_useVertexAttributeAliasing) + { + disableVertexAttribPointer(_normalAlias._location); + } + else + { + if (_normalArray._enabled || _normalArray._dirty) + { + _normalArray._lazy_disable = false; + _normalArray._enabled = false; + _normalArray._dirty = false; + glDisableClientState(GL_NORMAL_ARRAY); + } + } + #else + disableVertexAttribPointer(_normalAlias._location); + #endif + } + + inline void dirtyNormalPointer() + { + #ifdef OSG_GL_VERTEX_ARRAY_FUNCS_AVAILABLE + if (_useVertexAttributeAliasing) + { + dirtyVertexAttribPointer(_normalAlias._location); + } + else + { + _normalArray._pointer = 0; + _normalArray._dirty = true; + } + #else + dirtyVertexAttribPointer(_normalAlias._location); + #endif + } + + /** Set the color pointer using an osg::Array, and manage any VBO that are required.*/ + inline void setColorPointer(const Array* array) + { + if (array) + { + GLBufferObject* vbo = isVertexBufferObjectSupported() ? array->getOrCreateGLBufferObject(_contextID) : 0; + if (vbo) + { + bindVertexBufferObject(vbo); + setColorPointer(array->getDataSize(),array->getDataType(),0,(const GLvoid *)(vbo->getOffset(array->getBufferIndex())),array->getNormalize()); + } + else + { + unbindVertexBufferObject(); + setColorPointer(array->getDataSize(),array->getDataType(),0,array->getDataPointer(),array->getNormalize()); + } + } + } + + + /** wrapper around glEnableClientState(GL_COLOR_ARRAY);glColorPointer(..); + * note, only updates values that change.*/ + inline void setColorPointer( GLint size, GLenum type, + GLsizei stride, const GLvoid *ptr, GLboolean normalized=GL_TRUE ) + { + #ifdef OSG_GL_VERTEX_ARRAY_FUNCS_AVAILABLE + if (_useVertexAttributeAliasing) + { + setVertexAttribPointer(_colorAlias._location, size, type, normalized, stride, ptr); + } + else + { + if (!_colorArray._enabled || _colorArray._dirty) + { + _colorArray._enabled = true; + glEnableClientState(GL_COLOR_ARRAY); + } + //if (_colorArray._pointer!=ptr || _colorArray._dirty) + { + _colorArray._pointer=ptr; + glColorPointer( size, type, stride, ptr ); + } + _colorArray._lazy_disable = false; + _colorArray._dirty = false; + _colorArray._normalized = normalized; + } + #else + setVertexAttribPointer(_colorAlias._location, size, type, normalized, stride, ptr); + #endif + } + + /** wrapper around glDisableClientState(GL_COLOR_ARRAY); + * note, only updates values that change.*/ + inline void disableColorPointer() + { + #ifdef OSG_GL_VERTEX_ARRAY_FUNCS_AVAILABLE + if (_useVertexAttributeAliasing) + { + disableVertexAttribPointer(_colorAlias._location); + } + else + { + if (_colorArray._enabled || _colorArray._dirty) + { + _colorArray._lazy_disable = false; + _colorArray._enabled = false; + _colorArray._dirty = false; + glDisableClientState(GL_COLOR_ARRAY); + } + } + #else + disableVertexAttribPointer(_colorAlias._location); + #endif + } + + inline void dirtyColorPointer() + { + #ifdef OSG_GL_VERTEX_ARRAY_FUNCS_AVAILABLE + if (_useVertexAttributeAliasing) + { + dirtyVertexAttribPointer(_colorAlias._location); + } + else + { + _colorArray._pointer = 0; + _colorArray._dirty = true; + } + #else + dirtyVertexAttribPointer(_colorAlias._location); + #endif + } + + + inline bool isSecondaryColorSupported() const { return _isSecondaryColorSupportResolved?_isSecondaryColorSupported:computeSecondaryColorSupported(); } + + + /** Set the secondary color pointer using an osg::Array, and manage any VBO that are required.*/ + inline void setSecondaryColorPointer(const Array* array) + { + if (array) + { + GLBufferObject* vbo = isVertexBufferObjectSupported() ? array->getOrCreateGLBufferObject(_contextID) : 0; + if (vbo) + { + bindVertexBufferObject(vbo); + setSecondaryColorPointer(array->getDataSize(),array->getDataType(),0,(const GLvoid *)(vbo->getOffset(array->getBufferIndex())),array->getNormalize()); + } + else + { + unbindVertexBufferObject(); + setSecondaryColorPointer(array->getDataSize(),array->getDataType(),0,array->getDataPointer(),array->getNormalize()); + } + } + } + + /** wrapper around glEnableClientState(GL_SECONDARY_COLOR_ARRAY);glSecondayColorPointer(..); + * note, only updates values that change.*/ + void setSecondaryColorPointer( GLint size, GLenum type, GLsizei stride, const GLvoid *ptr, GLboolean normalized=GL_TRUE ); + + /** wrapper around glDisableClientState(GL_SECONDARY_COLOR_ARRAY); + * note, only updates values that change.*/ + inline void disableSecondaryColorPointer() + { + #ifdef OSG_GL_VERTEX_ARRAY_FUNCS_AVAILABLE + if (_useVertexAttributeAliasing) + { + disableVertexAttribPointer(_secondaryColorAlias._location); + } + else + { + if (_secondaryColorArray._enabled || _secondaryColorArray._dirty) + { + _secondaryColorArray._lazy_disable = false; + _secondaryColorArray._enabled = false; + _secondaryColorArray._dirty = false; + if (isSecondaryColorSupported()) glDisableClientState(GL_SECONDARY_COLOR_ARRAY); + } + } + #else + disableVertexAttribPointer(_secondaryColorAlias._location); + #endif + } + + inline void dirtySecondaryColorPointer() + { + #ifdef OSG_GL_VERTEX_ARRAY_FUNCS_AVAILABLE + if (_useVertexAttributeAliasing) + { + dirtyVertexAttribPointer(_secondaryColorAlias._location); + } + else + { + _secondaryColorArray._pointer = 0; + _secondaryColorArray._dirty = true; + } + #else + dirtyVertexAttribPointer(_secondaryColorAlias._location); + #endif + } + + inline bool isFogCoordSupported() const { return _isFogCoordSupportResolved?_isFogCoordSupported:computeFogCoordSupported(); } + + + /** Set the fog coord pointer using an osg::Array, and manage any VBO that are required.*/ + inline void setFogCoordPointer(const Array* array) + { + if (array) + { + GLBufferObject* vbo = isVertexBufferObjectSupported() ? array->getOrCreateGLBufferObject(_contextID) : 0; + if (vbo) + { + bindVertexBufferObject(vbo); + setFogCoordPointer(array->getDataType(),0,(const GLvoid *)(vbo->getOffset(array->getBufferIndex())),array->getNormalize()); + } + else + { + unbindVertexBufferObject(); + setFogCoordPointer(array->getDataType(),0,array->getDataPointer(),array->getNormalize()); + } + } + } + + + /** wrapper around glEnableClientState(GL_FOG_COORDINATE_ARRAY);glFogCoordPointer(..); + * note, only updates values that change.*/ + void setFogCoordPointer( GLenum type, GLsizei stride, const GLvoid *ptr, GLboolean normalized=GL_FALSE ); + + /** wrapper around glDisableClientState(GL_FOG_COORDINATE_ARRAY); + * note, only updates values that change.*/ + inline void disableFogCoordPointer() + { + #ifdef OSG_GL_VERTEX_ARRAY_FUNCS_AVAILABLE + if (_useVertexAttributeAliasing) + { + disableVertexAttribPointer(_fogCoordAlias._location); + } + else + { + if (_fogArray._enabled || _fogArray._dirty) + { + _fogArray._lazy_disable = false; + _fogArray._enabled = false; + _fogArray._dirty = false; + if (isFogCoordSupported()) glDisableClientState(GL_FOG_COORDINATE_ARRAY); + } + } + #else + disableVertexAttribPointer(_fogCoordAlias._location); + #endif + } + + inline void dirtyFogCoordPointer() + { + #ifdef OSG_GL_VERTEX_ARRAY_FUNCS_AVAILABLE + if (_useVertexAttributeAliasing) + { + dirtyVertexAttribPointer(_fogCoordAlias._location); + } + else + { + _fogArray._pointer = 0; + _fogArray._dirty = true; + } + #else + dirtyVertexAttribPointer(_fogCoordAlias._location); + #endif + } + + + + /** Set the tex coord pointer using an osg::Array, and manage any VBO that are required.*/ + inline void setTexCoordPointer(unsigned int unit, const Array* array) + { + if (array) + { + GLBufferObject* vbo = isVertexBufferObjectSupported() ? array->getOrCreateGLBufferObject(_contextID) : 0; + if (vbo) + { + bindVertexBufferObject(vbo); + setTexCoordPointer(unit, array->getDataSize(),array->getDataType(),0, (const GLvoid *)(vbo->getOffset(array->getBufferIndex())),array->getNormalize()); + } + else + { + unbindVertexBufferObject(); + setTexCoordPointer(unit, array->getDataSize(),array->getDataType(),0,array->getDataPointer(),array->getNormalize()); + } + } + } + + /** wrapper around glEnableClientState(GL_TEXTURE_COORD_ARRAY);glTexCoordPointer(..); + * note, only updates values that change.*/ + inline void setTexCoordPointer( unsigned int unit, + GLint size, GLenum type, + GLsizei stride, const GLvoid *ptr, GLboolean normalized=GL_FALSE ) + { + #ifdef OSG_GL_VERTEX_ARRAY_FUNCS_AVAILABLE + if (_useVertexAttributeAliasing) + { + setVertexAttribPointer(_texCoordAliasList[unit]._location, size, type, normalized, stride, ptr); + } + else + { + if (setClientActiveTextureUnit(unit)) + { + if ( unit >= _texCoordArrayList.size()) _texCoordArrayList.resize(unit+1); + EnabledArrayPair& eap = _texCoordArrayList[unit]; + + if (!eap._enabled || eap._dirty) + { + eap._enabled = true; + glEnableClientState(GL_TEXTURE_COORD_ARRAY); + } + //if (eap._pointer!=ptr || eap._dirty) + { + glTexCoordPointer( size, type, stride, ptr ); + eap._pointer = ptr; + } + eap._lazy_disable = false; + eap._dirty = false; + eap._normalized = normalized; + } + } + #else + setVertexAttribPointer(_texCoordAliasList[unit]._location, size, type, normalized, stride, ptr); + #endif + } + + /** wrapper around glDisableClientState(GL_TEXTURE_COORD_ARRAY); + * note, only updates values that change.*/ + inline void disableTexCoordPointer( unsigned int unit ) + { + #ifdef OSG_GL_VERTEX_ARRAY_FUNCS_AVAILABLE + if (_useVertexAttributeAliasing) + { + disableVertexAttribPointer(_texCoordAliasList[unit]._location); + } + else + { + if (setClientActiveTextureUnit(unit)) + { + if ( unit >= _texCoordArrayList.size()) _texCoordArrayList.resize(unit+1); + EnabledArrayPair& eap = _texCoordArrayList[unit]; + + if (eap._enabled || eap._dirty) + { + eap._lazy_disable = false; + eap._enabled = false; + eap._dirty = false; + glDisableClientState(GL_TEXTURE_COORD_ARRAY); + } + } + } + #else + disableVertexAttribPointer(_texCoordAliasList[unit]._location); + #endif + } + + inline void dirtyTexCoordPointer( unsigned int unit ) + { + #ifdef OSG_GL_VERTEX_ARRAY_FUNCS_AVAILABLE + if (_useVertexAttributeAliasing) + { + dirtyVertexAttribPointer(_texCoordAliasList[unit]._location); + } + else + { + if ( unit >= _texCoordArrayList.size()) return; // _texCoordArrayList.resize(unit+1); + EnabledArrayPair& eap = _texCoordArrayList[unit]; + eap._pointer = 0; + eap._dirty = true; + } + #else + dirtyVertexAttribPointer(_texCoordAliasList[unit]._location); + #endif + } + + + inline void disableTexCoordPointersAboveAndIncluding( unsigned int unit ) + { + #ifdef OSG_GL_VERTEX_ARRAY_FUNCS_AVAILABLE + if (_useVertexAttributeAliasing) + { + disableVertexAttribPointersAboveAndIncluding(_texCoordAliasList[unit]._location); + } + else + { + while (unit<_texCoordArrayList.size()) + { + EnabledArrayPair& eap = _texCoordArrayList[unit]; + if (eap._enabled || eap._dirty) + { + if (setClientActiveTextureUnit(unit)) + { + eap._lazy_disable = false; + eap._enabled = false; + eap._dirty = false; + glDisableClientState(GL_TEXTURE_COORD_ARRAY); + } + } + ++unit; + } + } + #else + disableVertexAttribPointersAboveAndIncluding(_texCoordAliasList[unit]._location); + #endif + } + + inline void dirtyTexCoordPointersAboveAndIncluding( unsigned int unit ) + { + #ifdef OSG_GL_VERTEX_ARRAY_FUNCS_AVAILABLE + if (_useVertexAttributeAliasing) + { + dirtyVertexAttribPointersAboveAndIncluding(_texCoordAliasList[unit]._location); + } + else + { + while (unit<_texCoordArrayList.size()) + { + EnabledArrayPair& eap = _texCoordArrayList[unit]; + eap._pointer = 0; + eap._dirty = true; + ++unit; + } + } + #else + dirtyVertexAttribPointersAboveAndIncluding(_texCoordAliasList[unit]._location); + #endif + } + + + /// For GL>=2.0 uses GL_MAX_TEXTURE_COORDS, for GL<2 uses GL_MAX_TEXTURE_UNITS + inline GLint getMaxTextureCoords() const { return _glMaxTextureCoords; } + + /// For GL>=2.0 uses GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, for GL<2 uses GL_MAX_TEXTURE_UNITS + inline GLint getMaxTextureUnits() const { return _glMaxTextureUnits; } + + + /** Set the current texture unit, return true if selected, + * false if selection failed such as when multi texturing is not supported. + * note, only updates values that change.*/ + inline bool setActiveTextureUnit( unsigned int unit ); + + /** Get the current texture unit.*/ + unsigned int getActiveTextureUnit() const { return _currentActiveTextureUnit; } + + /** Set the current tex coord array texture unit, return true if selected, + * false if selection failed such as when multi texturing is not supported. + * note, only updates values that change.*/ + bool setClientActiveTextureUnit( unsigned int unit ); + + /** Get the current tex coord array texture unit.*/ + unsigned int getClientActiveTextureUnit() const { return _currentClientActiveTextureUnit; } + + /** Set the vertex attrib pointer using an osg::Array, and manage any VBO that are required.*/ + inline void setVertexAttribPointer(unsigned int unit, const Array* array) + { + if (array) + { + GLBufferObject* vbo = isVertexBufferObjectSupported() ? array->getOrCreateGLBufferObject(_contextID) : 0; + if (vbo) + { + bindVertexBufferObject(vbo); + setVertexAttribPointer(unit, array->getDataSize(),array->getDataType(),array->getNormalize(),0,(const GLvoid *)(vbo->getOffset(array->getBufferIndex()))); + } + else + { + unbindVertexBufferObject(); + setVertexAttribPointer(unit, array->getDataSize(),array->getDataType(),array->getNormalize(),0,array->getDataPointer()); + } + } + } + + /** Set the vertex attrib pointer using an osg::Array, and manage any VBO that are required.*/ + inline void setVertexAttribLPointer(unsigned int unit, const Array* array) + { + if (array) + { + GLBufferObject* vbo = array->getOrCreateGLBufferObject(_contextID); + if (vbo) + { + bindVertexBufferObject(vbo); + setVertexAttribLPointer(unit, array->getDataSize(),array->getDataType(),0,(const GLvoid *)(vbo->getOffset(array->getBufferIndex()))); + } + else + { + unbindVertexBufferObject(); + setVertexAttribLPointer(unit, array->getDataSize(),array->getDataType(),0,array->getDataPointer()); + } + } + } + + /** Set the vertex attrib pointer using an osg::Array, and manage any VBO that are required.*/ + inline void setVertexAttribIPointer(unsigned int unit, const Array* array) + { + if (array) + { + GLBufferObject* vbo = array->getOrCreateGLBufferObject(_contextID); + if (vbo) + { + bindVertexBufferObject(vbo); + setVertexAttribIPointer(unit, array->getDataSize(),array->getDataType(),0,(const GLvoid *)(vbo->getOffset(array->getBufferIndex()))); + } + else + { + unbindVertexBufferObject(); + setVertexAttribIPointer(unit, array->getDataSize(),array->getDataType(),0,array->getDataPointer()); + } + } + } + + /** wrapper around glEnableVertexAttribArrayARB(index);glVertexAttribPointerARB(..); + * note, only updates values that change.*/ + void setVertexAttribPointer( unsigned int index, + GLint size, GLenum type, GLboolean normalized, + GLsizei stride, const GLvoid *ptr ); + + /** wrapper around glEnableVertexAttribArrayARB(index);glVertexAttribIPointer(..); + * note, only updates values that change.*/ + void setVertexAttribIPointer( unsigned int index, + GLint size, GLenum type, + GLsizei stride, const GLvoid *ptr ); + + /** wrapper around glEnableVertexAttribArrayARB(index);glVertexAttribLPointer(..); + * note, only updates values that change.*/ + void setVertexAttribLPointer( unsigned int index, + GLint size, GLenum type, + GLsizei stride, const GLvoid *ptr ); + + /** wrapper around DisableVertexAttribArrayARB(index); + * note, only updates values that change.*/ + void disableVertexAttribPointer( unsigned int index ); + + void disableVertexAttribPointersAboveAndIncluding( unsigned int index ); + + inline void dirtyVertexAttribPointer( unsigned int index ) + { + if (index<_vertexAttribArrayList.size()) + { + EnabledArrayPair& eap = _vertexAttribArrayList[index]; + eap._pointer = 0; + eap._dirty = true; + } + } + + inline void dirtyVertexAttribPointersAboveAndIncluding( unsigned int index ) + { + while (index<_vertexAttribArrayList.size()) + { + EnabledArrayPair& eap = _vertexAttribArrayList[index]; + eap._pointer = 0; + eap._dirty = true; + ++index; + } + } + + bool isVertexBufferObjectSupported() const { return _isVertexBufferObjectSupportResolved?_isVertexBufferObjectSupported:computeVertexBufferObjectSupported(); } + + + inline void setLastAppliedProgramObject(const Program::PerContextProgram* program) + { + if (_lastAppliedProgramObject!=program) + { + _lastAppliedProgramObject = program; + } + } + inline const Program::PerContextProgram* getLastAppliedProgramObject() const { return _lastAppliedProgramObject; } + + inline GLint getUniformLocation( unsigned int uniformNameID ) const { return _lastAppliedProgramObject ? _lastAppliedProgramObject->getUniformLocation(uniformNameID) : -1; } + /** + * Alternative version of getUniformLocation( unsigned int uniformNameID ) + * retrofited into OSG for backward compatibility with osgCal, + * after uniform ids were refactored from std::strings to GLints in OSG version 2.9.10. + * + * Drawbacks: This method is not particularly fast. It has to access mutexed static + * map of uniform ids. So don't overuse it or your app performance will suffer. + */ + inline GLint getUniformLocation( const std::string & uniformName ) const { return _lastAppliedProgramObject ? _lastAppliedProgramObject->getUniformLocation(uniformName) : -1; } + inline GLint getAttribLocation( const std::string& name ) const { return _lastAppliedProgramObject ? _lastAppliedProgramObject->getAttribLocation(name) : -1; } + + typedef std::pair AttributePair; + typedef std::vector AttributeVec; + + AttributeVec& getAttributeVec( const osg::StateAttribute* attribute ) + { + AttributeStack& as = _attributeMap[ attribute->getTypeMemberPair() ]; + return as.attributeVec; + } + + /** Set the frame stamp for the current frame.*/ + inline void setFrameStamp(FrameStamp* fs) { _frameStamp = fs; } + + /** Get the frame stamp for the current frame.*/ + inline FrameStamp* getFrameStamp() { return _frameStamp.get(); } + + /** Get the const frame stamp for the current frame.*/ + inline const FrameStamp* getFrameStamp() const { return _frameStamp.get(); } + + + /** Set the DisplaySettings. Note, nothing is applied, the visual settings are just + * used in the State object to pass the current visual settings to Drawables + * during rendering. */ + inline void setDisplaySettings(DisplaySettings* vs) { _displaySettings = vs; } + + /** Get the DisplaySettings */ + inline const DisplaySettings* getDisplaySettings() const { return _displaySettings.get(); } + + + + /** Set flag for early termination of the draw traversal.*/ + void setAbortRenderingPtr(bool* abortPtr) { _abortRenderingPtr = abortPtr; } + + /** Get flag for early termination of the draw traversal, + * if true steps should be taken to complete rendering early.*/ + bool getAbortRendering() const { return _abortRenderingPtr!=0?(*_abortRenderingPtr):false; } + + + struct DynamicObjectRenderingCompletedCallback : public osg::Referenced + { + virtual void completed(osg::State*) = 0; + }; + + /** Set the callback to be called when the dynamic object count hits 0.*/ + void setDynamicObjectRenderingCompletedCallback(DynamicObjectRenderingCompletedCallback* cb){ _completeDynamicObjectRenderingCallback = cb; } + + /** Get the callback to be called when the dynamic object count hits 0.*/ + DynamicObjectRenderingCompletedCallback* getDynamicObjectRenderingCompletedCallback() { return _completeDynamicObjectRenderingCallback.get(); } + + /** Set the number of dynamic objects that will be rendered in this graphics context this frame.*/ + void setDynamicObjectCount(unsigned int count, bool callCallbackOnZero = false) + { + if (_dynamicObjectCount != count) + { + _dynamicObjectCount = count; + if (_dynamicObjectCount==0 && callCallbackOnZero && _completeDynamicObjectRenderingCallback.valid()) + { + _completeDynamicObjectRenderingCallback->completed(this); + } + } + } + + /** Get the number of dynamic objects that will be rendered in this graphics context this frame.*/ + unsigned int getDynamicObjectCount() const { return _dynamicObjectCount; } + + /** Decrement the number of dynamic objects left to render this frame, and once the count goes to zero call the + * DynamicObjectRenderingCompletedCallback to inform of completion.*/ + inline void decrementDynamicObjectCount() + { + --_dynamicObjectCount; + if (_dynamicObjectCount==0 && _completeDynamicObjectRenderingCallback.valid()) + { + _completeDynamicObjectRenderingCallback->completed(this); + } + } + + void setMaxTexturePoolSize(unsigned int size); + unsigned int getMaxTexturePoolSize() const { return _maxTexturePoolSize; } + + void setMaxBufferObjectPoolSize(unsigned int size); + unsigned int getMaxBufferObjectPoolSize() const { return _maxBufferObjectPoolSize; } + + + enum CheckForGLErrors + { + /** NEVER_CHECK_GL_ERRORS hints that OpenGL need not be checked for, this + is the fastest option since checking for errors does incurr a small overhead.*/ + NEVER_CHECK_GL_ERRORS, + /** ONCE_PER_FRAME means that OpenGl errors will be checked for once per + frame, the overhead is still small, but at least OpenGL errors that are occurring + will be caught, the reporting isn't fine grained enough for debugging purposes.*/ + ONCE_PER_FRAME, + /** ONCE_PER_ATTRIBUTE means that OpenGL errors will be checked for after + every attribute is applied, allow errors to be directly associated with + particular operations which makes debugging much easier.*/ + ONCE_PER_ATTRIBUTE + }; + + /** Set whether and how often OpenGL errors should be checked for.*/ + void setCheckForGLErrors(CheckForGLErrors check) { _checkGLErrors = check; } + + /** Get whether and how often OpenGL errors should be checked for.*/ + CheckForGLErrors getCheckForGLErrors() const { return _checkGLErrors; } + + bool checkGLErrors(const char* str) const; + bool checkGLErrors(StateAttribute::GLMode mode) const; + bool checkGLErrors(const StateAttribute* attribute) const; + + /** print out the internal details of osg::State - useful for debugging.*/ + void print(std::ostream& fout) const; + + /** Initialize extension used by osg:::State.*/ + void initializeExtensionProcs(); + + virtual void objectDeleted(void* object); + + /** Get the GL adapter object used to map OpenGL 1.0 glBegin/glEnd usage to vertex arrays.*/ + inline GLBeginEndAdapter& getGLBeginEndAdapter() { return _glBeginEndAdapter; } + + /** Get the helper class for dispatching osg::Arrays as OpenGL attribute data.*/ + inline ArrayDispatchers& getArrayDispatchers() { return _arrayDispatchers; } + + + /** Set the helper class that provides applications with estimate on how much different graphics operations will cost.*/ + inline void setGraphicsCostEstimator(GraphicsCostEstimator* gce) { _graphicsCostEstimator = gce; } + + /** Get the helper class that provides applications with estimate on how much different graphics operations will cost.*/ + inline GraphicsCostEstimator* getGraphicsCostEstimator() { return _graphicsCostEstimator.get(); } + + /** Get the cont helper class that provides applications with estimate on how much different graphics operations will cost.*/ + inline const GraphicsCostEstimator* getGraphicsCostEstimator() const { return _graphicsCostEstimator.get(); } + + + + /** Support for synchronizing the system time and the timestamp + * counter available with ARB_timer_query. Note that State + * doesn't update these values itself. + */ + Timer_t getStartTick() const { return _startTick; } + void setStartTick(Timer_t tick) { _startTick = tick; } + Timer_t getGpuTick() const { return _gpuTick; } + + double getGpuTime() const + { + return osg::Timer::instance()->delta_s(_startTick, _gpuTick); + } + GLuint64EXT getGpuTimestamp() const { return _gpuTimestamp; } + + void setGpuTimestamp(Timer_t tick, GLuint64EXT timestamp) + { + _gpuTick = tick; + _gpuTimestamp = timestamp; + } + int getTimestampBits() const { return _timestampBits; } + void setTimestampBits(int bits) { _timestampBits = bits; } + + /** called by the GraphicsContext just before GraphicsContext::swapBuffersImplementation().*/ + virtual void frameCompleted(); + + protected: + + virtual ~State(); + + GraphicsContext* _graphicsContext; + unsigned int _contextID; + + bool _shaderCompositionEnabled; + bool _shaderCompositionDirty; + osg::ref_ptr _shaderComposer; + osg::Program* _currentShaderCompositionProgram; + StateSet::UniformList _currentShaderCompositionUniformList; + + ref_ptr _frameStamp; + + ref_ptr _identity; + ref_ptr _initialViewMatrix; + ref_ptr _projection; + ref_ptr _modelView; + ref_ptr _modelViewCache; + + bool _useModelViewAndProjectionUniforms; + ref_ptr _modelViewMatrixUniform; + ref_ptr _projectionMatrixUniform; + ref_ptr _modelViewProjectionMatrixUniform; + ref_ptr _normalMatrixUniform; + + Matrix _initialInverseViewMatrix; + + ref_ptr _displaySettings; + + bool* _abortRenderingPtr; + CheckForGLErrors _checkGLErrors; + + + bool _useVertexAttributeAliasing; + VertexAttribAlias _vertexAlias; + VertexAttribAlias _normalAlias; + VertexAttribAlias _colorAlias; + VertexAttribAlias _secondaryColorAlias; + VertexAttribAlias _fogCoordAlias; + VertexAttribAliasList _texCoordAliasList; + + Program::AttribBindingList _attributeBindingList; + + void setUpVertexAttribAlias(VertexAttribAlias& alias, GLuint location, const std::string glName, const std::string osgName, const std::string& declaration); + + + struct ModeStack + { + typedef std::vector ValueVec; + + ModeStack() + { + valid = true; + changed = false; + last_applied_value = false; + global_default_value = false; + } + + void print(std::ostream& fout) const; + + bool valid; + bool changed; + bool last_applied_value; + bool global_default_value; + ValueVec valueVec; + }; + + struct AttributeStack + { + AttributeStack() + { + changed = false; + last_applied_attribute = 0L; + last_applied_shadercomponent = 0L; + global_default_attribute = 0L; + + } + + void print(std::ostream& fout) const; + + /** apply an attribute if required, passing in attribute and appropriate attribute stack */ + bool changed; + const StateAttribute* last_applied_attribute; + const ShaderComponent* last_applied_shadercomponent; + ref_ptr global_default_attribute; + AttributeVec attributeVec; + }; + + + struct UniformStack + { + typedef std::pair UniformPair; + typedef std::vector UniformVec; + + UniformStack() {} + + void print(std::ostream& fout) const; + + UniformVec uniformVec; + }; + + + /** Apply an OpenGL mode if required, passing in mode, enable flag and + * appropriate mode stack. This is a wrapper around \c glEnable() and + * \c glDisable(), that just actually calls these functions if the + * \c enabled flag is different than the current state. + * @return \c true if the state was actually changed. \c false + * otherwise. Notice that a \c false return does not indicate + * an error, it just means that the mode was already set to the + * same value as the \c enabled parameter. + */ + inline bool applyMode(StateAttribute::GLMode mode,bool enabled,ModeStack& ms) + { + if (ms.valid && ms.last_applied_value != enabled) + { + ms.last_applied_value = enabled; + + if (enabled) glEnable(mode); + else glDisable(mode); + + if (_checkGLErrors==ONCE_PER_ATTRIBUTE) checkGLErrors(mode); + + return true; + } + else + return false; + } + + inline bool applyModeOnTexUnit(unsigned int unit,StateAttribute::GLMode mode,bool enabled,ModeStack& ms) + { + if (ms.valid && ms.last_applied_value != enabled) + { + if (setActiveTextureUnit(unit)) + { + ms.last_applied_value = enabled; + + if (enabled) glEnable(mode); + else glDisable(mode); + + if (_checkGLErrors==ONCE_PER_ATTRIBUTE) checkGLErrors(mode); + + return true; + } + else + return false; + } + else + return false; + } + + /** apply an attribute if required, passing in attribute and appropriate attribute stack */ + inline bool applyAttribute(const StateAttribute* attribute,AttributeStack& as) + { + if (as.last_applied_attribute != attribute) + { + if (!as.global_default_attribute.valid()) as.global_default_attribute = dynamic_cast(attribute->cloneType()); + + as.last_applied_attribute = attribute; + attribute->apply(*this); + + const ShaderComponent* sc = attribute->getShaderComponent(); + if (as.last_applied_shadercomponent != sc) + { + as.last_applied_shadercomponent = sc; + _shaderCompositionDirty = true; + } + + if (_checkGLErrors==ONCE_PER_ATTRIBUTE) checkGLErrors(attribute); + + return true; + } + else + return false; + } + + inline bool applyAttributeOnTexUnit(unsigned int unit,const StateAttribute* attribute,AttributeStack& as) + { + if (as.last_applied_attribute != attribute) + { + if (setActiveTextureUnit(unit)) + { + if (!as.global_default_attribute.valid()) as.global_default_attribute = dynamic_cast(attribute->cloneType()); + + as.last_applied_attribute = attribute; + attribute->apply(*this); + + const ShaderComponent* sc = attribute->getShaderComponent(); + if (as.last_applied_shadercomponent != sc) + { + as.last_applied_shadercomponent = sc; + _shaderCompositionDirty = true; + } + + if (_checkGLErrors==ONCE_PER_ATTRIBUTE) checkGLErrors(attribute); + + return true; + } + else + return false; + } + else + return false; + } + + + inline bool applyGlobalDefaultAttribute(AttributeStack& as) + { + if (as.last_applied_attribute != as.global_default_attribute.get()) + { + as.last_applied_attribute = as.global_default_attribute.get(); + if (as.global_default_attribute.valid()) + { + as.global_default_attribute->apply(*this); + const ShaderComponent* sc = as.global_default_attribute->getShaderComponent(); + if (as.last_applied_shadercomponent != sc) + { + as.last_applied_shadercomponent = sc; + _shaderCompositionDirty = true; + } + + if (_checkGLErrors==ONCE_PER_ATTRIBUTE) checkGLErrors(as.global_default_attribute.get()); + } + return true; + } + else + return false; + } + + inline bool applyGlobalDefaultAttributeOnTexUnit(unsigned int unit,AttributeStack& as) + { + if (as.last_applied_attribute != as.global_default_attribute.get()) + { + if (setActiveTextureUnit(unit)) + { + as.last_applied_attribute = as.global_default_attribute.get(); + if (as.global_default_attribute.valid()) + { + as.global_default_attribute->apply(*this); + const ShaderComponent* sc = as.global_default_attribute->getShaderComponent(); + if (as.last_applied_shadercomponent != sc) + { + as.last_applied_shadercomponent = sc; + _shaderCompositionDirty = true; + } + if (_checkGLErrors==ONCE_PER_ATTRIBUTE) checkGLErrors(as.global_default_attribute.get()); + } + return true; + } + else + return false; + } + else + return false; + } + + + typedef std::map ModeMap; + typedef std::vector TextureModeMapList; + + typedef std::map AttributeMap; + typedef std::vector TextureAttributeMapList; + + typedef std::map UniformMap; + + typedef std::vector > MatrixStack; + + typedef std::set AppliedProgramObjectSet; + + ModeMap _modeMap; + AttributeMap _attributeMap; + UniformMap _uniformMap; + + TextureModeMapList _textureModeMapList; + TextureAttributeMapList _textureAttributeMapList; + + AppliedProgramObjectSet _appliedProgramObjectSet; + const Program::PerContextProgram* _lastAppliedProgramObject; + + StateSetStack _stateStateStack; + + unsigned int _maxTexturePoolSize; + unsigned int _maxBufferObjectPoolSize; + + + struct EnabledArrayPair + { + EnabledArrayPair():_lazy_disable(false),_dirty(true),_enabled(false),_normalized(0),_pointer(0) {} + EnabledArrayPair(const EnabledArrayPair& eap):_lazy_disable(eap._lazy_disable),_dirty(eap._dirty), _enabled(eap._enabled),_normalized(eap._normalized),_pointer(eap._pointer) {} + EnabledArrayPair& operator = (const EnabledArrayPair& eap) { _lazy_disable = eap._lazy_disable;_dirty=eap._dirty; _enabled=eap._enabled; _normalized=eap._normalized;_pointer=eap._pointer; return *this; } + + bool _lazy_disable; + bool _dirty; + bool _enabled; + GLboolean _normalized; + const GLvoid* _pointer; + }; + + typedef std::vector EnabledTexCoordArrayList; + typedef std::vector EnabledVertexAttribArrayList; + + EnabledArrayPair _vertexArray; + EnabledArrayPair _normalArray; + EnabledArrayPair _colorArray; + EnabledArrayPair _secondaryColorArray; + EnabledArrayPair _fogArray; + EnabledTexCoordArrayList _texCoordArrayList; + EnabledVertexAttribArrayList _vertexAttribArrayList; + + unsigned int _currentActiveTextureUnit; + unsigned int _currentClientActiveTextureUnit; + GLBufferObject* _currentVBO; + GLBufferObject* _currentEBO; + GLBufferObject* _currentPBO; + + + inline ModeMap& getOrCreateTextureModeMap(unsigned int unit) + { + if (unit>=_textureModeMapList.size()) _textureModeMapList.resize(unit+1); + return _textureModeMapList[unit]; + } + + + inline AttributeMap& getOrCreateTextureAttributeMap(unsigned int unit) + { + if (unit>=_textureAttributeMapList.size()) _textureAttributeMapList.resize(unit+1); + return _textureAttributeMapList[unit]; + } + + inline void pushModeList(ModeMap& modeMap,const StateSet::ModeList& modeList); + inline void pushAttributeList(AttributeMap& attributeMap,const StateSet::AttributeList& attributeList); + inline void pushUniformList(UniformMap& uniformMap,const StateSet::UniformList& uniformList); + + inline void popModeList(ModeMap& modeMap,const StateSet::ModeList& modeList); + inline void popAttributeList(AttributeMap& attributeMap,const StateSet::AttributeList& attributeList); + inline void popUniformList(UniformMap& uniformMap,const StateSet::UniformList& uniformList); + + inline void applyModeList(ModeMap& modeMap,const StateSet::ModeList& modeList); + inline void applyAttributeList(AttributeMap& attributeMap,const StateSet::AttributeList& attributeList); + inline void applyUniformList(UniformMap& uniformMap,const StateSet::UniformList& uniformList); + + inline void applyModeMap(ModeMap& modeMap); + inline void applyAttributeMap(AttributeMap& attributeMap); + inline void applyUniformMap(UniformMap& uniformMap); + + inline void applyModeListOnTexUnit(unsigned int unit,ModeMap& modeMap,const StateSet::ModeList& modeList); + inline void applyAttributeListOnTexUnit(unsigned int unit,AttributeMap& attributeMap,const StateSet::AttributeList& attributeList); + + inline void applyModeMapOnTexUnit(unsigned int unit,ModeMap& modeMap); + inline void applyAttributeMapOnTexUnit(unsigned int unit,AttributeMap& attributeMap); + + void haveAppliedMode(ModeMap& modeMap,StateAttribute::GLMode mode,StateAttribute::GLModeValue value); + void haveAppliedMode(ModeMap& modeMap,StateAttribute::GLMode mode); + void haveAppliedAttribute(AttributeMap& attributeMap,const StateAttribute* attribute); + void haveAppliedAttribute(AttributeMap& attributeMap,StateAttribute::Type type, unsigned int member); + bool getLastAppliedMode(const ModeMap& modeMap,StateAttribute::GLMode mode) const; + const StateAttribute* getLastAppliedAttribute(const AttributeMap& attributeMap,StateAttribute::Type type, unsigned int member) const; + + void loadModelViewMatrix(); + + + mutable bool _isSecondaryColorSupportResolved; + mutable bool _isSecondaryColorSupported; + bool computeSecondaryColorSupported() const; + + mutable bool _isFogCoordSupportResolved; + mutable bool _isFogCoordSupported; + bool computeFogCoordSupported() const; + + mutable bool _isVertexBufferObjectSupportResolved; + mutable bool _isVertexBufferObjectSupported; + bool computeVertexBufferObjectSupported() const; + + typedef void (GL_APIENTRY * ActiveTextureProc) (GLenum texture); + typedef void (GL_APIENTRY * FogCoordPointerProc) (GLenum type, GLsizei stride, const GLvoid *pointer); + typedef void (GL_APIENTRY * SecondaryColorPointerProc) (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer); + typedef void (GL_APIENTRY * MultiTexCoord4fProc) (GLenum target, GLfloat x, GLfloat y, GLfloat z, GLfloat w); + typedef void (GL_APIENTRY * VertexAttrib4fProc)(GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); + typedef void (GL_APIENTRY * VertexAttrib4fvProc)(GLuint index, const GLfloat *v); + typedef void (GL_APIENTRY * VertexAttribPointerProc) (unsigned int, GLint, GLenum, GLboolean normalized, GLsizei stride, const GLvoid *pointer); + typedef void (GL_APIENTRY * VertexAttribIPointerProc) (unsigned int, GLint, GLenum, GLsizei stride, const GLvoid *pointer); + typedef void (GL_APIENTRY * VertexAttribLPointerProc) (unsigned int, GLint, GLenum, GLsizei stride, const GLvoid *pointer); + typedef void (GL_APIENTRY * EnableVertexAttribProc) (unsigned int); + typedef void (GL_APIENTRY * DisableVertexAttribProc) (unsigned int); + typedef void (GL_APIENTRY * BindBufferProc) (GLenum target, GLuint buffer); + + typedef void (GL_APIENTRY * DrawArraysInstancedProc)( GLenum mode, GLint first, GLsizei count, GLsizei primcount ); + typedef void (GL_APIENTRY * DrawElementsInstancedProc)( GLenum mode, GLsizei count, GLenum type, const GLvoid *indices, GLsizei primcount ); + + bool _extensionProcsInitialized; + GLint _glMaxTextureCoords; + GLint _glMaxTextureUnits; + ActiveTextureProc _glClientActiveTexture; + ActiveTextureProc _glActiveTexture; + MultiTexCoord4fProc _glMultiTexCoord4f; + VertexAttrib4fProc _glVertexAttrib4f; + VertexAttrib4fvProc _glVertexAttrib4fv; + FogCoordPointerProc _glFogCoordPointer; + SecondaryColorPointerProc _glSecondaryColorPointer; + VertexAttribPointerProc _glVertexAttribPointer; + VertexAttribIPointerProc _glVertexAttribIPointer; + VertexAttribLPointerProc _glVertexAttribLPointer; + EnableVertexAttribProc _glEnableVertexAttribArray; + DisableVertexAttribProc _glDisableVertexAttribArray; + BindBufferProc _glBindBuffer; + DrawArraysInstancedProc _glDrawArraysInstanced; + DrawElementsInstancedProc _glDrawElementsInstanced; + + unsigned int _dynamicObjectCount; + osg::ref_ptr _completeDynamicObjectRenderingCallback; + + GLBeginEndAdapter _glBeginEndAdapter; + ArrayDispatchers _arrayDispatchers; + + osg::ref_ptr _graphicsCostEstimator; + + Timer_t _startTick; + Timer_t _gpuTick; + GLuint64EXT _gpuTimestamp; + int _timestampBits; +}; + +inline void State::pushModeList(ModeMap& modeMap,const StateSet::ModeList& modeList) +{ + for(StateSet::ModeList::const_iterator mitr=modeList.begin(); + mitr!=modeList.end(); + ++mitr) + { + // get the mode stack for incoming GLmode {mitr->first}. + ModeStack& ms = modeMap[mitr->first]; + if (ms.valueVec.empty()) + { + // first pair so simply push incoming pair to back. + ms.valueVec.push_back(mitr->second); + } + else if ((ms.valueVec.back() & StateAttribute::OVERRIDE) && !(mitr->second & StateAttribute::PROTECTED)) // check the existing override flag + { + // push existing back since override keeps the previous value. + ms.valueVec.push_back(ms.valueVec.back()); + } + else + { + // no override on so simply push incoming pair to back. + ms.valueVec.push_back(mitr->second); + } + ms.changed = true; + } +} + +inline void State::pushAttributeList(AttributeMap& attributeMap,const StateSet::AttributeList& attributeList) +{ + for(StateSet::AttributeList::const_iterator aitr=attributeList.begin(); + aitr!=attributeList.end(); + ++aitr) + { + // get the attribute stack for incoming type {aitr->first}. + AttributeStack& as = attributeMap[aitr->first]; + if (as.attributeVec.empty()) + { + // first pair so simply push incoming pair to back. + as.attributeVec.push_back( + AttributePair(aitr->second.first.get(),aitr->second.second)); + } + else if ((as.attributeVec.back().second & StateAttribute::OVERRIDE) && !(aitr->second.second & StateAttribute::PROTECTED)) // check the existing override flag + { + // push existing back since override keeps the previous value. + as.attributeVec.push_back(as.attributeVec.back()); + } + else + { + // no override on so simply push incoming pair to back. + as.attributeVec.push_back( + AttributePair(aitr->second.first.get(),aitr->second.second)); + } + as.changed = true; + } +} + + +inline void State::pushUniformList(UniformMap& uniformMap,const StateSet::UniformList& uniformList) +{ + for(StateSet::UniformList::const_iterator aitr=uniformList.begin(); + aitr!=uniformList.end(); + ++aitr) + { + // get the attribute stack for incoming type {aitr->first}. + UniformStack& us = uniformMap[aitr->first]; + if (us.uniformVec.empty()) + { + // first pair so simply push incoming pair to back. + us.uniformVec.push_back( + UniformStack::UniformPair(aitr->second.first.get(),aitr->second.second)); + } + else if ((us.uniformVec.back().second & StateAttribute::OVERRIDE) && !(aitr->second.second & StateAttribute::PROTECTED)) // check the existing override flag + { + // push existing back since override keeps the previous value. + us.uniformVec.push_back(us.uniformVec.back()); + } + else + { + // no override on so simply push incoming pair to back. + us.uniformVec.push_back( + UniformStack::UniformPair(aitr->second.first.get(),aitr->second.second)); + } + } +} + +inline void State::popModeList(ModeMap& modeMap,const StateSet::ModeList& modeList) +{ + for(StateSet::ModeList::const_iterator mitr=modeList.begin(); + mitr!=modeList.end(); + ++mitr) + { + // get the mode stack for incoming GLmode {mitr->first}. + ModeStack& ms = modeMap[mitr->first]; + if (!ms.valueVec.empty()) + { + ms.valueVec.pop_back(); + } + ms.changed = true; + } +} + +inline void State::popAttributeList(AttributeMap& attributeMap,const StateSet::AttributeList& attributeList) +{ + for(StateSet::AttributeList::const_iterator aitr=attributeList.begin(); + aitr!=attributeList.end(); + ++aitr) + { + // get the attribute stack for incoming type {aitr->first}. + AttributeStack& as = attributeMap[aitr->first]; + if (!as.attributeVec.empty()) + { + as.attributeVec.pop_back(); + } + as.changed = true; + } +} + +inline void State::popUniformList(UniformMap& uniformMap,const StateSet::UniformList& uniformList) +{ + for(StateSet::UniformList::const_iterator aitr=uniformList.begin(); + aitr!=uniformList.end(); + ++aitr) + { + // get the attribute stack for incoming type {aitr->first}. + UniformStack& us = uniformMap[aitr->first]; + if (!us.uniformVec.empty()) + { + us.uniformVec.pop_back(); + } + } +} + +inline void State::applyModeList(ModeMap& modeMap,const StateSet::ModeList& modeList) +{ + StateSet::ModeList::const_iterator ds_mitr = modeList.begin(); + ModeMap::iterator this_mitr=modeMap.begin(); + + while (this_mitr!=modeMap.end() && ds_mitr!=modeList.end()) + { + if (this_mitr->firstfirst) + { + + // note GLMode = this_mitr->first + ModeStack& ms = this_mitr->second; + if (ms.changed) + { + ms.changed = false; + if (!ms.valueVec.empty()) + { + bool new_value = ms.valueVec.back() & StateAttribute::ON; + applyMode(this_mitr->first,new_value,ms); + } + else + { + // assume default of disabled. + applyMode(this_mitr->first,ms.global_default_value,ms); + + } + + } + + ++this_mitr; + + } + else if (ds_mitr->firstfirst) + { + + // ds_mitr->first is a new mode, therefore + // need to insert a new mode entry for ds_mistr->first. + ModeStack& ms = modeMap[ds_mitr->first]; + + bool new_value = ds_mitr->second & StateAttribute::ON; + applyMode(ds_mitr->first,new_value,ms); + + // will need to disable this mode on next apply so set it to changed. + ms.changed = true; + + ++ds_mitr; + + } + else + { + // this_mitr & ds_mitr refer to the same mode, check the override + // if any otherwise just apply the incoming mode. + + ModeStack& ms = this_mitr->second; + + if (!ms.valueVec.empty() && (ms.valueVec.back() & StateAttribute::OVERRIDE) && !(ds_mitr->second & StateAttribute::PROTECTED)) + { + // override is on, just treat as a normal apply on modes. + + if (ms.changed) + { + ms.changed = false; + bool new_value = ms.valueVec.back() & StateAttribute::ON; + applyMode(this_mitr->first,new_value,ms); + + } + } + else + { + // no override on or no previous entry, therefore consider incoming mode. + bool new_value = ds_mitr->second & StateAttribute::ON; + if (applyMode(ds_mitr->first,new_value,ms)) + { + ms.changed = true; + } + } + + ++this_mitr; + ++ds_mitr; + } + } + + // iterator over the remaining state modes to apply any previous changes. + for(; + this_mitr!=modeMap.end(); + ++this_mitr) + { + // note GLMode = this_mitr->first + ModeStack& ms = this_mitr->second; + if (ms.changed) + { + ms.changed = false; + if (!ms.valueVec.empty()) + { + bool new_value = ms.valueVec.back() & StateAttribute::ON; + applyMode(this_mitr->first,new_value,ms); + } + else + { + // assume default of disabled. + applyMode(this_mitr->first,ms.global_default_value,ms); + + } + + } + } + + // iterator over the remaining incoming modes to apply any new mode. + for(; + ds_mitr!=modeList.end(); + ++ds_mitr) + { + ModeStack& ms = modeMap[ds_mitr->first]; + + bool new_value = ds_mitr->second & StateAttribute::ON; + applyMode(ds_mitr->first,new_value,ms); + + // will need to disable this mode on next apply so set it to changed. + ms.changed = true; + } +} + +inline void State::applyModeListOnTexUnit(unsigned int unit,ModeMap& modeMap,const StateSet::ModeList& modeList) +{ + StateSet::ModeList::const_iterator ds_mitr = modeList.begin(); + ModeMap::iterator this_mitr=modeMap.begin(); + + while (this_mitr!=modeMap.end() && ds_mitr!=modeList.end()) + { + if (this_mitr->firstfirst) + { + + // note GLMode = this_mitr->first + ModeStack& ms = this_mitr->second; + if (ms.changed) + { + ms.changed = false; + if (!ms.valueVec.empty()) + { + bool new_value = ms.valueVec.back() & StateAttribute::ON; + applyModeOnTexUnit(unit,this_mitr->first,new_value,ms); + } + else + { + // assume default of disabled. + applyModeOnTexUnit(unit,this_mitr->first,ms.global_default_value,ms); + + } + + } + + ++this_mitr; + + } + else if (ds_mitr->firstfirst) + { + + // ds_mitr->first is a new mode, therefore + // need to insert a new mode entry for ds_mistr->first. + ModeStack& ms = modeMap[ds_mitr->first]; + + bool new_value = ds_mitr->second & StateAttribute::ON; + applyModeOnTexUnit(unit,ds_mitr->first,new_value,ms); + + // will need to disable this mode on next apply so set it to changed. + ms.changed = true; + + ++ds_mitr; + + } + else + { + // this_mitr & ds_mitr refer to the same mode, check the override + // if any otherwise just apply the incoming mode. + + ModeStack& ms = this_mitr->second; + + if (!ms.valueVec.empty() && (ms.valueVec.back() & StateAttribute::OVERRIDE) && !(ds_mitr->second & StateAttribute::PROTECTED)) + { + // override is on, just treat as a normal apply on modes. + + if (ms.changed) + { + ms.changed = false; + bool new_value = ms.valueVec.back() & StateAttribute::ON; + applyModeOnTexUnit(unit,this_mitr->first,new_value,ms); + + } + } + else + { + // no override on or no previous entry, therefore consider incoming mode. + bool new_value = ds_mitr->second & StateAttribute::ON; + if (applyModeOnTexUnit(unit,ds_mitr->first,new_value,ms)) + { + ms.changed = true; + } + } + + ++this_mitr; + ++ds_mitr; + } + } + + // iterator over the remaining state modes to apply any previous changes. + for(; + this_mitr!=modeMap.end(); + ++this_mitr) + { + // note GLMode = this_mitr->first + ModeStack& ms = this_mitr->second; + if (ms.changed) + { + ms.changed = false; + if (!ms.valueVec.empty()) + { + bool new_value = ms.valueVec.back() & StateAttribute::ON; + applyModeOnTexUnit(unit,this_mitr->first,new_value,ms); + } + else + { + // assume default of disabled. + applyModeOnTexUnit(unit,this_mitr->first,ms.global_default_value,ms); + + } + + } + } + + // iterator over the remaining incoming modes to apply any new mode. + for(; + ds_mitr!=modeList.end(); + ++ds_mitr) + { + ModeStack& ms = modeMap[ds_mitr->first]; + + bool new_value = ds_mitr->second & StateAttribute::ON; + applyModeOnTexUnit(unit,ds_mitr->first,new_value,ms); + + // will need to disable this mode on next apply so set it to changed. + ms.changed = true; + } +} + +inline void State::applyAttributeList(AttributeMap& attributeMap,const StateSet::AttributeList& attributeList) +{ + StateSet::AttributeList::const_iterator ds_aitr=attributeList.begin(); + + AttributeMap::iterator this_aitr=attributeMap.begin(); + + while (this_aitr!=attributeMap.end() && ds_aitr!=attributeList.end()) + { + if (this_aitr->firstfirst) + { + + // note attribute type = this_aitr->first + AttributeStack& as = this_aitr->second; + if (as.changed) + { + as.changed = false; + if (!as.attributeVec.empty()) + { + const StateAttribute* new_attr = as.attributeVec.back().first; + applyAttribute(new_attr,as); + } + else + { + applyGlobalDefaultAttribute(as); + } + } + + ++this_aitr; + + } + else if (ds_aitr->firstfirst) + { + + // ds_aitr->first is a new attribute, therefore + // need to insert a new attribute entry for ds_aitr->first. + AttributeStack& as = attributeMap[ds_aitr->first]; + + const StateAttribute* new_attr = ds_aitr->second.first.get(); + applyAttribute(new_attr,as); + + as.changed = true; + + ++ds_aitr; + + } + else + { + // this_mitr & ds_mitr refer to the same attribute, check the override + // if any otherwise just apply the incoming attribute + + AttributeStack& as = this_aitr->second; + + if (!as.attributeVec.empty() && (as.attributeVec.back().second & StateAttribute::OVERRIDE) && !(ds_aitr->second.second & StateAttribute::PROTECTED)) + { + // override is on, just treat as a normal apply on attribute. + + if (as.changed) + { + as.changed = false; + const StateAttribute* new_attr = as.attributeVec.back().first; + applyAttribute(new_attr,as); + } + } + else + { + // no override on or no previous entry, therefore consider incoming attribute. + const StateAttribute* new_attr = ds_aitr->second.first.get(); + if (applyAttribute(new_attr,as)) + { + as.changed = true; + } + } + + ++this_aitr; + ++ds_aitr; + } + } + + // iterator over the remaining state attributes to apply any previous changes. + for(; + this_aitr!=attributeMap.end(); + ++this_aitr) + { + // note attribute type = this_aitr->first + AttributeStack& as = this_aitr->second; + if (as.changed) + { + as.changed = false; + if (!as.attributeVec.empty()) + { + const StateAttribute* new_attr = as.attributeVec.back().first; + applyAttribute(new_attr,as); + } + else + { + applyGlobalDefaultAttribute(as); + } + } + } + + // iterator over the remaining incoming attribute to apply any new attribute. + for(; + ds_aitr!=attributeList.end(); + ++ds_aitr) + { + // ds_aitr->first is a new attribute, therefore + // need to insert a new attribute entry for ds_aitr->first. + AttributeStack& as = attributeMap[ds_aitr->first]; + + const StateAttribute* new_attr = ds_aitr->second.first.get(); + applyAttribute(new_attr,as); + + // will need to update this attribute on next apply so set it to changed. + as.changed = true; + } + +} + +inline void State::applyAttributeListOnTexUnit(unsigned int unit,AttributeMap& attributeMap,const StateSet::AttributeList& attributeList) +{ + StateSet::AttributeList::const_iterator ds_aitr=attributeList.begin(); + + AttributeMap::iterator this_aitr=attributeMap.begin(); + + while (this_aitr!=attributeMap.end() && ds_aitr!=attributeList.end()) + { + if (this_aitr->firstfirst) + { + + // note attribute type = this_aitr->first + AttributeStack& as = this_aitr->second; + if (as.changed) + { + as.changed = false; + if (!as.attributeVec.empty()) + { + const StateAttribute* new_attr = as.attributeVec.back().first; + applyAttributeOnTexUnit(unit,new_attr,as); + } + else + { + applyGlobalDefaultAttributeOnTexUnit(unit,as); + } + } + + ++this_aitr; + + } + else if (ds_aitr->firstfirst) + { + + // ds_aitr->first is a new attribute, therefore + // need to insert a new attribute entry for ds_aitr->first. + AttributeStack& as = attributeMap[ds_aitr->first]; + + const StateAttribute* new_attr = ds_aitr->second.first.get(); + applyAttributeOnTexUnit(unit,new_attr,as); + + as.changed = true; + + ++ds_aitr; + + } + else + { + // this_mitr & ds_mitr refer to the same attribute, check the override + // if any otherwise just apply the incoming attribute + + AttributeStack& as = this_aitr->second; + + if (!as.attributeVec.empty() && (as.attributeVec.back().second & StateAttribute::OVERRIDE) && !(ds_aitr->second.second & StateAttribute::PROTECTED)) + { + // override is on, just treat as a normal apply on attribute. + + if (as.changed) + { + as.changed = false; + const StateAttribute* new_attr = as.attributeVec.back().first; + applyAttributeOnTexUnit(unit,new_attr,as); + } + } + else + { + // no override on or no previous entry, therefore consider incoming attribute. + const StateAttribute* new_attr = ds_aitr->second.first.get(); + if (applyAttributeOnTexUnit(unit,new_attr,as)) + { + as.changed = true; + } + } + + ++this_aitr; + ++ds_aitr; + } + } + + // iterator over the remaining state attributes to apply any previous changes. + for(; + this_aitr!=attributeMap.end(); + ++this_aitr) + { + // note attribute type = this_aitr->first + AttributeStack& as = this_aitr->second; + if (as.changed) + { + as.changed = false; + if (!as.attributeVec.empty()) + { + const StateAttribute* new_attr = as.attributeVec.back().first; + applyAttributeOnTexUnit(unit,new_attr,as); + } + else + { + applyGlobalDefaultAttributeOnTexUnit(unit,as); + } + } + } + + // iterator over the remaining incoming attribute to apply any new attribute. + for(; + ds_aitr!=attributeList.end(); + ++ds_aitr) + { + // ds_aitr->first is a new attribute, therefore + // need to insert a new attribute entry for ds_aitr->first. + AttributeStack& as = attributeMap[ds_aitr->first]; + + const StateAttribute* new_attr = ds_aitr->second.first.get(); + applyAttributeOnTexUnit(unit,new_attr,as); + + // will need to update this attribute on next apply so set it to changed. + as.changed = true; + } + +} + +inline void State::applyUniformList(UniformMap& uniformMap,const StateSet::UniformList& uniformList) +{ + if (!_lastAppliedProgramObject) return; + + StateSet::UniformList::const_iterator ds_aitr=uniformList.begin(); + + UniformMap::iterator this_aitr=uniformMap.begin(); + + while (this_aitr!=uniformMap.end() && ds_aitr!=uniformList.end()) + { + if (this_aitr->firstfirst) + { + // note attribute type = this_aitr->first + UniformStack& as = this_aitr->second; + if (!as.uniformVec.empty()) + { + _lastAppliedProgramObject->apply(*as.uniformVec.back().first); + } + + ++this_aitr; + + } + else if (ds_aitr->firstfirst) + { + _lastAppliedProgramObject->apply(*(ds_aitr->second.first.get())); + + ++ds_aitr; + } + else + { + // this_mitr & ds_mitr refer to the same attribute, check the override + // if any otherwise just apply the incoming attribute + + UniformStack& as = this_aitr->second; + + if (!as.uniformVec.empty() && (as.uniformVec.back().second & StateAttribute::OVERRIDE) && !(ds_aitr->second.second & StateAttribute::PROTECTED)) + { + // override is on, just treat as a normal apply on uniform. + _lastAppliedProgramObject->apply(*as.uniformVec.back().first); + } + else + { + // no override on or no previous entry, therefore consider incoming attribute. + _lastAppliedProgramObject->apply(*(ds_aitr->second.first.get())); + } + + ++this_aitr; + ++ds_aitr; + } + } + + // iterator over the remaining state attributes to apply any previous changes. + for(; + this_aitr!=uniformMap.end(); + ++this_aitr) + { + // note attribute type = this_aitr->first + UniformStack& as = this_aitr->second; + if (!as.uniformVec.empty()) + { + _lastAppliedProgramObject->apply(*as.uniformVec.back().first); + } + } + + // iterator over the remaining incoming attribute to apply any new attribute. + for(; + ds_aitr!=uniformList.end(); + ++ds_aitr) + { + _lastAppliedProgramObject->apply(*(ds_aitr->second.first.get())); + } + +} + +inline void State::applyModeMap(ModeMap& modeMap) +{ + for(ModeMap::iterator mitr=modeMap.begin(); + mitr!=modeMap.end(); + ++mitr) + { + // note GLMode = mitr->first + ModeStack& ms = mitr->second; + if (ms.changed) + { + ms.changed = false; + if (!ms.valueVec.empty()) + { + bool new_value = ms.valueVec.back() & StateAttribute::ON; + applyMode(mitr->first,new_value,ms); + } + else + { + // assume default of disabled. + applyMode(mitr->first,ms.global_default_value,ms); + } + + } + } +} + +inline void State::applyModeMapOnTexUnit(unsigned int unit,ModeMap& modeMap) +{ + for(ModeMap::iterator mitr=modeMap.begin(); + mitr!=modeMap.end(); + ++mitr) + { + // note GLMode = mitr->first + ModeStack& ms = mitr->second; + if (ms.changed) + { + ms.changed = false; + if (!ms.valueVec.empty()) + { + bool new_value = ms.valueVec.back() & StateAttribute::ON; + applyModeOnTexUnit(unit,mitr->first,new_value,ms); + } + else + { + // assume default of disabled. + applyModeOnTexUnit(unit,mitr->first,ms.global_default_value,ms); + } + + } + } +} + +inline void State::applyAttributeMap(AttributeMap& attributeMap) +{ + for(AttributeMap::iterator aitr=attributeMap.begin(); + aitr!=attributeMap.end(); + ++aitr) + { + AttributeStack& as = aitr->second; + if (as.changed) + { + as.changed = false; + if (!as.attributeVec.empty()) + { + const StateAttribute* new_attr = as.attributeVec.back().first; + applyAttribute(new_attr,as); + } + else + { + applyGlobalDefaultAttribute(as); + } + + } + } +} + +inline void State::applyAttributeMapOnTexUnit(unsigned int unit,AttributeMap& attributeMap) +{ + for(AttributeMap::iterator aitr=attributeMap.begin(); + aitr!=attributeMap.end(); + ++aitr) + { + AttributeStack& as = aitr->second; + if (as.changed) + { + as.changed = false; + if (!as.attributeVec.empty()) + { + const StateAttribute* new_attr = as.attributeVec.back().first; + applyAttributeOnTexUnit(unit,new_attr,as); + } + else + { + applyGlobalDefaultAttributeOnTexUnit(unit,as); + } + + } + } +} + +inline void State::applyUniformMap(UniformMap& uniformMap) +{ + if (!_lastAppliedProgramObject) return; + + for(UniformMap::iterator aitr=uniformMap.begin(); + aitr!=uniformMap.end(); + ++aitr) + { + UniformStack& as = aitr->second; + if (!as.uniformVec.empty()) + { + _lastAppliedProgramObject->apply(*as.uniformVec.back().first); + } + } +} + +inline bool State::setActiveTextureUnit( unsigned int unit ) +{ + if (unit!=_currentActiveTextureUnit) + { + if (_glActiveTexture && unit < (unsigned int)(maximum(_glMaxTextureCoords,_glMaxTextureUnits)) ) + { + _glActiveTexture(GL_TEXTURE0+unit); + _currentActiveTextureUnit = unit; + } + else + { + return unit==0; + } + } + return true; +} + +} + +#endif diff --git a/libs/include/android/osg/StateAttribute b/libs/include/android/osg/StateAttribute new file mode 100755 index 0000000..bf20219 --- /dev/null +++ b/libs/include/android/osg/StateAttribute @@ -0,0 +1,366 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_STATEATTRIBUTE +#define OSG_STATEATTRIBUTE 1 + +#include +#include +#include +#include +#include + +#include +#include +#include + +// define for the GL_EXT_secondary_color extension, GL_COLOR_SUM is OpenGL +// mode to be used to enable and disable the second color. +#ifndef GL_COLOR_SUM +#define GL_COLOR_SUM 0x8458 +#endif + +namespace osg { + + +// forward declare NodeVisitor, State & StateSet +class NodeVisitor; +class State; +class ShaderComposer; +class StateSet; +class Texture; + +/** META_StateAttribute macro define the standard clone, isSameKindAs, + * className and getType methods. + * Use when subclassing from Object to make it more convenient to define + * the standard pure virtual methods which are required for all Object + * subclasses.*/ +#define META_StateAttribute(library,name,type) \ + virtual osg::Object* cloneType() const { return new name(); } \ + virtual osg::Object* clone(const osg::CopyOp& copyop) const { return new name (*this,copyop); } \ + virtual bool isSameKindAs(const osg::Object* obj) const { return dynamic_cast(obj)!=NULL; } \ + virtual const char* libraryName() const { return #library; } \ + virtual const char* className() const { return #name; } \ + virtual Type getType() const { return type; } + +/** COMPARE_StateAttribute_Types macro is a helper for implementing the StateAtribute::compare(..) method.*/ +#define COMPARE_StateAttribute_Types(TYPE,rhs_attribute) \ + if (this==&rhs_attribute) return 0;\ + const std::type_info* type_lhs = &typeid(*this);\ + const std::type_info* type_rhs = &typeid(rhs_attribute);\ + if (type_lhs->before(*type_rhs)) return -1;\ + if (*type_lhs != *type_rhs) return 1;\ + const TYPE& rhs = static_cast(rhs_attribute); + + +/** COMPARE_StateAttribute_Parameter macro is a helper for implementing the StatateAtribute::compare(..) method. + * Macro assumes that variable rhs has been correctly defined by preceding code + * macro.*/ +#define COMPARE_StateAttribute_Parameter(parameter) \ + if (parameter TypeMemberPair; + + StateAttribute(); + + StateAttribute(const StateAttribute& sa,const CopyOp& copyop=CopyOp::SHALLOW_COPY): + Object(sa,copyop), + _shaderComponent(sa._shaderComponent), + _updateCallback(copyop(sa._updateCallback.get())), + _eventCallback(copyop(sa._eventCallback.get())) + {} + + + /** Clone the type of an attribute, with Object* return type. + Must be defined by derived classes.*/ + virtual Object* cloneType() const = 0; + + /** Clone an attribute, with Object* return type. + Must be defined by derived classes.*/ + virtual Object* clone(const CopyOp&) const = 0; + + /** Return true if this and obj are of the same kind of object.*/ + virtual bool isSameKindAs(const Object* obj) const { return dynamic_cast(obj)!=NULL; } + + /** Return the name of the attribute's library.*/ + virtual const char* libraryName() const { return "osg"; } + + /** Return the name of the attribute's class type.*/ + virtual const char* className() const { return "StateAttribute"; } + + + /** Fast alternative to dynamic_cast<> for determining if state attribute is a Texture.*/ + virtual Texture* asTexture() { return 0; } + + /** Fast alternative to dynamic_cast<> for determining if state attribute is a Texture.*/ + virtual const Texture* asTexture() const { return 0; } + + + /** Return the Type identifier of the attribute's class type.*/ + virtual Type getType() const = 0; + + /** Return the member identifier within the attribute's class type. Used for light number/clip plane number etc.*/ + virtual unsigned int getMember() const { return 0; } + + /** Return the TypeMemberPair that uniquely identifies this type member.*/ + inline TypeMemberPair getTypeMemberPair() const { return TypeMemberPair(getType(),getMember()); } + + /** Return true if StateAttribute is a type which controls texturing and needs to be issued w.r.t to specific texture unit.*/ + virtual bool isTextureAttribute() const { return false; } + + /** Return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs.*/ + virtual int compare(const StateAttribute& sa) const = 0; + + bool operator < (const StateAttribute& rhs) const { return compare(rhs)<0; } + bool operator == (const StateAttribute& rhs) const { return compare(rhs)==0; } + bool operator != (const StateAttribute& rhs) const { return compare(rhs)!=0; } + + + /** A vector of osg::StateSet pointers which is used to store the parent(s) of this StateAttribute.*/ + typedef std::vector ParentList; + + /** Get the parent list of this StateAttribute. */ + inline const ParentList& getParents() const { return _parents; } + + inline StateSet* getParent(unsigned int i) { return _parents[i]; } + /** + * Get a single const parent of this StateAttribute. + * @param i index of the parent to get. + * @return the parent i. + */ + inline const StateSet* getParent(unsigned int i) const { return _parents[i]; } + + /** + * Get the number of parents of this StateAttribute. + * @return the number of parents of this StateAttribute. + */ + inline unsigned int getNumParents() const { return static_cast(_parents.size()); } + + void setShaderComponent(ShaderComponent* sc) { _shaderComponent = sc; } + ShaderComponent* getShaderComponent() { return _shaderComponent.get(); } + const ShaderComponent* getShaderComponent() const { return _shaderComponent.get(); } + + struct ModeUsage + { + virtual ~ModeUsage() {} + virtual void usesMode(GLMode mode) = 0; + virtual void usesTextureMode(GLMode mode) = 0; + }; + + /** Return the modes associated with this StateAttribute.*/ + virtual bool getModeUsage(ModeUsage&) const + { + // default to no GLMode's associated with use of the StateAttribute. + return false; + } + + /** Check the modes associated with this StateAttribute are supported by current OpenGL drivers, + * and if not set the associated mode in osg::State to be black listed/invalid. + * Return true if all associated modes are valid.*/ + virtual bool checkValidityOfAssociatedModes(osg::State&) const + { + // default to no black listed GLMode's associated with use of the StateAttribute. + return true; + } + + // provide callback for backwards compatibility. + typedef osg::StateAttributeCallback Callback; + + /** Set the UpdateCallback which allows users to attach customize the updating of an object during the update traversal.*/ + void setUpdateCallback(StateAttributeCallback* uc); + + /** Get the non const UpdateCallback.*/ + StateAttributeCallback* getUpdateCallback() { return _updateCallback.get(); } + + /** Get the const UpdateCallback.*/ + const StateAttributeCallback* getUpdateCallback() const { return _updateCallback.get(); } + + + /** Set the EventCallback which allows users to attach customize the updating of an object during the Event traversal.*/ + void setEventCallback(StateAttributeCallback* ec); + + /** Get the non const EventCallback.*/ + StateAttributeCallback* getEventCallback() { return _eventCallback.get(); } + + /** Get the const EventCallback.*/ + const StateAttributeCallback* getEventCallback() const { return _eventCallback.get(); } + + + /** apply the OpenGL state attributes. + * The render info for the current OpenGL context is passed + * in to allow the StateAttribute to obtain details on the + * the current context and state. + */ + virtual void apply(State&) const {} + + /** Default to nothing to compile - all state is applied immediately. */ + virtual void compileGLObjects(State&) const {} + + /** Resize any per context GLObject buffers to specified size. */ + virtual void resizeGLObjectBuffers(unsigned int /*maxSize*/) {} + + /** Release OpenGL objects in specified graphics context if State + object is passed, otherwise release OpenGL objects for all graphics context if + State object pointer NULL.*/ + virtual void releaseGLObjects(State* =0) const {} + + + protected: + + virtual ~StateAttribute() {} + + void addParent(osg::StateSet* object); + void removeParent(osg::StateSet* object); + + ParentList _parents; + friend class osg::StateSet; + + ref_ptr _shaderComponent; + + ref_ptr _updateCallback; + ref_ptr _eventCallback; +}; + +} + +#endif diff --git a/libs/include/android/osg/StateAttributeCallback b/libs/include/android/osg/StateAttributeCallback new file mode 100755 index 0000000..09e38ce --- /dev/null +++ b/libs/include/android/osg/StateAttributeCallback @@ -0,0 +1,39 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +#ifndef OSG_STATEATTRIBUTECALLBACK +#define OSG_STATEATTRIBUTECALLBACK 1 + +#include +#include + +namespace osg { + +class StateAttribute; +class NodeVisitor; + +class OSG_EXPORT StateAttributeCallback : public virtual osg::Object +{ + public: + StateAttributeCallback() {} + + StateAttributeCallback(const StateAttributeCallback&,const CopyOp&) {} + + META_Object(osg,StateAttributeCallback); + + /** do customized update code.*/ + virtual void operator () (StateAttribute*, NodeVisitor*) {} +}; + +} + +#endif diff --git a/libs/include/android/osg/StateSet b/libs/include/android/osg/StateSet new file mode 100755 index 0000000..e14398f --- /dev/null +++ b/libs/include/android/osg/StateSet @@ -0,0 +1,520 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2008 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_STATESET +#define OSG_STATESET 1 + +#include +#include +#include +#include + +#include +#include +#include + +#ifndef GL_RESCALE_NORMAL +// allow compilation against GL1.1 headers. +#define GL_RESCALE_NORMAL 0x803A +#endif + +namespace osg { + +// forward declare for the purposes of the UpdateCallback. +class NodeVisitor; + +/** Stores a set of modes and attributes which represent a set of OpenGL state. + * Notice that a \c StateSet contains just a subset of the whole OpenGL state. + *

In OSG, each \c Drawable and each \c Node has a reference to a + * \c StateSet. These StateSets can be shared between + * different Drawables and Nodes (that is, several + * Drawables and Nodes can reference the same \c StateSet). + * Indeed, this practice is recommended whenever possible, + * as this minimizes expensive state changes in the graphics pipeline. +*/ +class OSG_EXPORT StateSet : public Object +{ + public : + + + StateSet(); + StateSet(const StateSet&,const CopyOp& copyop=CopyOp::SHALLOW_COPY); + + virtual Object* cloneType() const { return new StateSet(); } + virtual Object* clone(const CopyOp& copyop) const { return new StateSet(*this,copyop); } + virtual bool isSameKindAs(const Object* obj) const { return dynamic_cast(obj)!=NULL; } + virtual const char* libraryName() const { return "osg"; } + virtual const char* className() const { return "StateSet"; } + + /** return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs.*/ + int compare(const StateSet& rhs,bool compareAttributeContents=false) const; + + bool operator < (const StateSet& rhs) const { return compare(rhs)<0; } + bool operator == (const StateSet& rhs) const { return compare(rhs)==0; } + bool operator != (const StateSet& rhs) const { return compare(rhs)!=0; } + + + /** A vector of osg::Object pointers which is used to store the parent(s) of this Stateset, the parents could be osg::Node or osg::Drawable.*/ + typedef std::vector ParentList; + + /** Get the parent list of this StateSet. */ + inline const ParentList& getParents() const { return _parents; } + + /** Get the a copy of parent list of node. A copy is returned to + * prevent modification of the parent list.*/ + inline ParentList getParents() { return _parents; } + + inline Object* getParent(unsigned int i) { return _parents[i]; } + /** + * Get a single const parent of this StateSet. + * @param i index of the parent to get. + * @return the parent i. + */ + inline const Object* getParent(unsigned int i) const { return _parents[i]; } + + /** + * Get the number of parents of this StateSet. + * @return the number of parents of this StateSet. + */ + inline unsigned int getNumParents() const { return static_cast(_parents.size()); } + + + /** Compute the DataVariance based on an assessment of callback etc.*/ + virtual void computeDataVariance(); + + + /** Set all the modes to on or off so that it defines a + complete state, typically used for a default global state.*/ + void setGlobalDefaults(); + + /** Clear the StateSet of all modes and attributes.*/ + void clear(); + + /** Merge this \c StateSet with the \c StateSet passed as parameter. + * Every mode and attribute in this \c StateSet that is marked with + * \c StateAttribute::OVERRIDE is replaced with the + * equivalent mode or attribute from \c rhs. + */ + void merge(const StateSet& rhs); + + /** a container to map GLModes to their respective GLModeValues.*/ + typedef std::map ModeList; + + /** Set this \c StateSet to contain the specified \c GLMode with a given + * value. + * @note Don't use this method to set modes related to textures. For this + * purpose, use \c setTextureMode(), that accepts an extra parameter + * specifying which texture unit shall be affected by the call. + */ + void setMode(StateAttribute::GLMode mode, StateAttribute::GLModeValue value); + + /** Remove \c mode from this \c StateSet. + * @note Don't use this method to remove modes related to textures. For + * this purpose, use \c removeTextureMode(), that accepts an extra + * parameter specifying which texture unit shall be affected by + * the call. + */ + void removeMode(StateAttribute::GLMode mode); + + /** Get the value for a given \c GLMode. + * @param mode The \c GLMode whose value is desired. + * @return If \c mode is contained within this \c StateSet, returns the + * value associated with it. Otherwise, returns + * \c StateAttribute::INHERIT. + * @note Don't use this method to get the value of modes related to + * textures. For this purpose, use \c removeTextureMode(), that + * accepts an extra parameter specifying which texture unit shall + * be affected by the call. + */ + StateAttribute::GLModeValue getMode(StateAttribute::GLMode mode) const; + + /** Set the list of all GLModes contained in this \c StateSet.*/ + inline void setModeList(ModeList& ml) { _modeList=ml; } + + /** Return the list of all GLModes contained in this \c StateSet.*/ + inline ModeList& getModeList() { return _modeList; } + + /** Return the \c const list of all GLModes contained in this + * const StateSet. + */ + inline const ModeList& getModeList() const { return _modeList; } + + + + /** Simple pairing between an attribute and its override flag.*/ + typedef std::pair,StateAttribute::OverrideValue> RefAttributePair; + + /** a container to map to their respective RefAttributePair.*/ + typedef std::map AttributeList; + + /** Set this StateSet to contain specified attribute and override flag.*/ + void setAttribute(StateAttribute *attribute, StateAttribute::OverrideValue value=StateAttribute::OFF); + + /** Set this StateSet to contain specified attribute and set the associated GLMode's to specified value.*/ + void setAttributeAndModes(StateAttribute *attribute, StateAttribute::GLModeValue value=StateAttribute::ON); + + /** remove attribute of specified type from StateSet.*/ + void removeAttribute(StateAttribute::Type type, unsigned int member=0); + + /** remove attribute from StateSet.*/ + void removeAttribute(StateAttribute *attribute); + + /** Get specified StateAttribute for specified type. + * Returns NULL if no type is contained within StateSet.*/ + StateAttribute* getAttribute(StateAttribute::Type type, unsigned int member = 0); + + /** Get specified const StateAttribute for specified type. + * Returns NULL if no type is contained within const StateSet.*/ + const StateAttribute* getAttribute(StateAttribute::Type type, unsigned int member = 0) const; + + /** Get specified RefAttributePair for specified type. + * Returns NULL if no type is contained within StateSet.*/ + const RefAttributePair* getAttributePair(StateAttribute::Type type, unsigned int member = 0) const; + + /** set the list of all StateAttributes contained in this StateSet.*/ + inline void setAttributeList(AttributeList& al) { _attributeList=al; } + + /** return the list of all StateAttributes contained in this StateSet.*/ + inline AttributeList& getAttributeList() { return _attributeList; } + + /** return the const list of all StateAttributes contained in this const StateSet.*/ + inline const AttributeList& getAttributeList() const { return _attributeList; } + + + + typedef std::vector TextureModeList; + + /** Set this \c StateSet to contain specified \c GLMode with a given + * value. + * @param unit The texture unit to be affected (used with + * multi-texturing). + * @param mode The OpenGL mode to be added to the \c StateSet. + * @param value The value to be assigned to \c mode. + */ + void setTextureMode(unsigned int unit,StateAttribute::GLMode mode, StateAttribute::GLModeValue value); + + /** Remove texture mode from StateSet.*/ + void removeTextureMode(unsigned int unit,StateAttribute::GLMode mode); + + /** Get specified GLModeValue for specified GLMode. + * returns INHERIT if no GLModeValue is contained within StateSet.*/ + StateAttribute::GLModeValue getTextureMode(unsigned int unit,StateAttribute::GLMode mode) const; + + /** set the list of all Texture related GLModes contained in this StateSet.*/ + inline void setTextureModeList(TextureModeList& tml) { _textureModeList=tml; } + + /** return the list of all Texture related GLModes contained in this StateSet.*/ + inline TextureModeList& getTextureModeList() { return _textureModeList; } + + /** return the const list of all Texture related GLModes contained in this const StateSet.*/ + inline const TextureModeList& getTextureModeList() const { return _textureModeList; } + + /** Return the number texture units active in the TextureModeList.*/ + inline unsigned int getNumTextureModeLists() const { return static_cast(_textureModeList.size()); } + + typedef std::vector TextureAttributeList; + + /** Set this StateSet to contain specified attribute and override flag.*/ + void setTextureAttribute(unsigned int unit,StateAttribute *attribute, StateAttribute::OverrideValue value=StateAttribute::OFF); + /** Set this StateSet to contain specified attribute and set the associated GLMode's to specified value.*/ + void setTextureAttributeAndModes(unsigned int unit,StateAttribute *attribute, StateAttribute::GLModeValue value=StateAttribute::ON); + + /** remove texture attribute of specified type from StateSet.*/ + void removeTextureAttribute(unsigned int unit, StateAttribute::Type type); + + /** remove texture attribute from StateSet.*/ + void removeTextureAttribute(unsigned int unit, StateAttribute *attribute); + + /** Get specified Texture related StateAttribute for specified type. + * Returns NULL if no type is contained within StateSet.*/ + StateAttribute* getTextureAttribute(unsigned int unit,StateAttribute::Type type); + + /** Get specified Texture related const StateAttribute for specified type. + * Returns NULL if no type is contained within const StateSet.*/ + const StateAttribute* getTextureAttribute(unsigned int unit,StateAttribute::Type type) const; + + /** Get specified Texture related RefAttributePair for specified type. + * Returns NULL if no type is contained within StateSet.*/ + const RefAttributePair* getTextureAttributePair(unsigned int unit,StateAttribute::Type type) const; + + /** Set the list of all Texture related StateAttributes contained in this StateSet.*/ + inline void setTextureAttributeList(TextureAttributeList& tal) { _textureAttributeList=tal; } + + /** Return the list of all Texture related StateAttributes contained in this StateSet.*/ + inline TextureAttributeList& getTextureAttributeList() { return _textureAttributeList; } + + /** Return the const list of all Texture related StateAttributes contained in this const StateSet.*/ + inline const TextureAttributeList& getTextureAttributeList() const { return _textureAttributeList; } + + /** Return the number of texture units active in the TextureAttributeList.*/ + inline unsigned int getNumTextureAttributeLists() const { return static_cast(_textureAttributeList.size()); } + + + void setAssociatedModes(const StateAttribute* attribute, StateAttribute::GLModeValue value); + void removeAssociatedModes(const StateAttribute* attribute); + + void setAssociatedTextureModes(unsigned int unit,const StateAttribute* attribute, StateAttribute::GLModeValue value); + void removeAssociatedTextureModes(unsigned int unit,const StateAttribute* attribute); + + + + + /** Simple pairing between a Uniform and its override flag.*/ + typedef std::pair,StateAttribute::OverrideValue> RefUniformPair; + + /** a container to map Uniform name to its respective RefUniformPair.*/ + typedef std::map UniformList; + + /** Set this StateSet to contain specified uniform and override flag.*/ + void addUniform(Uniform* uniform, StateAttribute::OverrideValue value=StateAttribute::ON); + + /** remove uniform of specified name from StateSet.*/ + void removeUniform(const std::string& name); + + /** remove Uniform from StateSet.*/ + void removeUniform(Uniform* uniform); + + /** Get Uniform for specified name. + * Returns NULL if no matching Uniform is contained within StateSet.*/ + Uniform* getUniform(const std::string& name); + + /** Get Uniform for specified name, if one is not available create it, add it to this StateSet and return a pointer to it.*/ + Uniform* getOrCreateUniform(const std::string& name, Uniform::Type type, unsigned int numElements=1); + + /** Get const Uniform for specified name. + * Returns NULL if no matching Uniform is contained within StateSet.*/ + const Uniform* getUniform(const std::string& name) const; + + /** Get specified RefUniformPair for specified Uniform name. + * Returns NULL if no Uniform is contained within StateSet.*/ + const RefUniformPair* getUniformPair(const std::string& name) const; + + /** set the list of all Uniforms contained in this StateSet.*/ + inline void setUniformList(UniformList& al) { _uniformList=al; } + + /** return the list of all Uniforms contained in this StateSet.*/ + inline UniformList& getUniformList() { return _uniformList; } + + /** return the const list of all Uniforms contained in this const StateSet.*/ + inline const UniformList& getUniformList() const { return _uniformList; } + + enum RenderingHint + { + DEFAULT_BIN = 0, + OPAQUE_BIN = 1, + TRANSPARENT_BIN = 2 + }; + + /** Set the \c RenderingHint of this \c StateSet. \c RenderingHint is + * used by the renderer to determine which draw bin to drop associated + * osg::Drawables in. Typically, users will set this to either + * \c StateSet::OPAQUE_BIN or \c StateSet::TRANSPARENT_BIN. + * Drawables in the opaque bin are sorted by their + * \c StateSet, so that the number of expensive changes in the OpenGL + * state is minimized. Drawables in the transparent bin are + * sorted by depth, so that objects farther from the viewer are + * rendered first (and hence alpha blending works nicely for + * translucent objects). + */ + void setRenderingHint(int hint); + + /** Get the \c RenderingHint of this \c StateSet.*/ + inline int getRenderingHint() const { return _renderingHint; } + + enum RenderBinMode + { + INHERIT_RENDERBIN_DETAILS, + USE_RENDERBIN_DETAILS, + OVERRIDE_RENDERBIN_DETAILS + }; + + /** Set the render bin details.*/ + void setRenderBinDetails(int binNum,const std::string& binName,RenderBinMode mode=USE_RENDERBIN_DETAILS); + + /** Set the render bin details to inherit.*/ + void setRenderBinToInherit(); + + /** Get whether the render bin details are set and should be used.*/ + inline bool useRenderBinDetails() const { return _binMode!=INHERIT_RENDERBIN_DETAILS; } + + /** Set the render bin mode.*/ + inline void setRenderBinMode(RenderBinMode mode) { _binMode=mode; } + + /** Get the render bin mode.*/ + inline RenderBinMode getRenderBinMode() const { return _binMode; } + + /** Set the render bin number.*/ + inline void setBinNumber(int num) { _binNum=num; } + + /** Get the render bin number.*/ + inline int getBinNumber() const { return _binNum; } + + /** Set the render bin name.*/ + inline void setBinName(const std::string& name) { _binName=name; } + + /** Get the render bin name.*/ + inline const std::string& getBinName() const { return _binName; } + + /** By default render bins will be nested within each other dependent + * upon where they are set in the scene graph. This can be problematic + * if a transparent render bin is attached to an opaque render bin + * which is attached to another transparent render bin as these render + * bins will be sorted separately, giving the wrong draw ordering for + * back-to-front transparency. Therefore, to prevent render bins being + * nested, call setNestRenderBins(false). */ + inline void setNestRenderBins(bool val) { _nestRenderBins = val; } + + /** Get whether associated RenderBin should be nested within parents RenderBin.*/ + inline bool getNestRenderBins() const { return _nestRenderBins; } + + + struct Callback : public virtual osg::Object + { + Callback() {} + + Callback(const Callback&,const CopyOp&) {} + + META_Object(osg,Callback); + + /** do customized callback code.*/ + virtual void operator() (StateSet*, NodeVisitor*) {} + }; + + /** Set the Update Callback which allows users to attach customize the updating of an object during the update traversal.*/ + void setUpdateCallback(Callback* ac); + + /** Get the non const Update Callback.*/ + Callback* getUpdateCallback() { return _updateCallback.get(); } + + /** Get the const Update Callback.*/ + const Callback* getUpdateCallback() const { return _updateCallback.get(); } + + /** Return whether this StateSet has update callbacks associated with it, and therefore must be traversed.*/ + bool requiresUpdateTraversal() const { return _updateCallback.valid() || getNumChildrenRequiringUpdateTraversal()!=0; } + + /** Get the number of Objects of this StateSet which require Update traversal, + * since they have an Update Callback attached to them or their children.*/ + inline unsigned int getNumChildrenRequiringUpdateTraversal() const { return _numChildrenRequiringUpdateTraversal; } + + /** Run the update callbacks attached directly to this StateSet or to its children.*/ + void runUpdateCallbacks(osg::NodeVisitor* nv); + + + /** Set the Event Callback which allows users to attach customize the updating of an object during the event traversal.*/ + void setEventCallback(Callback* ac); + + /** Get the non const Event Callback.*/ + Callback* getEventCallback() { return _eventCallback.get(); } + + /** Get the const Event Callback.*/ + const Callback* getEventCallback() const { return _eventCallback.get(); } + + /** Return whether this StateSet has event callbacks associated with it, and therefore must be traversed.*/ + bool requiresEventTraversal() const { return _eventCallback.valid() || getNumChildrenRequiringEventTraversal()!=0; } + + /** Get the number of Objects of this StateSet which require Event traversal, + * since they have an Eevnt Callback attached to them or their children.*/ + inline unsigned int getNumChildrenRequiringEventTraversal() const { return _numChildrenRequiringEventTraversal; } + + /** Run the event callbacks attached directly to this StateSet or to its children.*/ + void runEventCallbacks(osg::NodeVisitor* nv); + + /** Check the modes associated with this StateSet are supported by current OpenGL drivers, + * and if not set the associated mode in osg::State to be black listed/invalid. + * Return true if all associated modes are valid.*/ + bool checkValidityOfAssociatedModes(State& state) const; + + /** Set whether to use a mutex to ensure ref() and unref() are thread safe.*/ + virtual void setThreadSafeRefUnref(bool threadSafe); + + /** call compile on all StateAttributes contained within this StateSet.*/ + void compileGLObjects(State& state) const; + + /** Resize any per context GLObject buffers to specified size. */ + virtual void resizeGLObjectBuffers(unsigned int maxSize); + + /** call release on all StateAttributes contained within this StateSet.*/ + virtual void releaseGLObjects(State* state=0) const; + + protected : + + + virtual ~StateSet(); + + StateSet& operator = (const StateSet&) { return *this; } + + void addParent(osg::Object* object); + void removeParent(osg::Object* object); + + ParentList _parents; + friend class osg::Node; + friend class osg::Drawable; + friend class osg::Uniform; + friend class osg::StateAttribute; + + ModeList _modeList; + AttributeList _attributeList; + + TextureModeList _textureModeList; + TextureAttributeList _textureAttributeList; + + UniformList _uniformList; + + inline ModeList& getOrCreateTextureModeList(unsigned int unit) + { + if (unit>=_textureModeList.size()) _textureModeList.resize(unit+1); + return _textureModeList[unit]; + } + + inline AttributeList& getOrCreateTextureAttributeList(unsigned int unit) + { + if (unit>=_textureAttributeList.size()) _textureAttributeList.resize(unit+1); + return _textureAttributeList[unit]; + } + + int compareModes(const ModeList& lhs,const ModeList& rhs); + int compareAttributePtrs(const AttributeList& lhs,const AttributeList& rhs); + int compareAttributeContents(const AttributeList& lhs,const AttributeList& rhs); + + void setMode(ModeList& modeList,StateAttribute::GLMode mode, StateAttribute::GLModeValue value); + void setModeToInherit(ModeList& modeList,StateAttribute::GLMode mode); + StateAttribute::GLModeValue getMode(const ModeList& modeList,StateAttribute::GLMode mode) const; + + void setAttribute(AttributeList& attributeList,StateAttribute *attribute, const StateAttribute::OverrideValue value=StateAttribute::OFF); + + StateAttribute* getAttribute(AttributeList& attributeList,const StateAttribute::Type type, unsigned int member); + const StateAttribute* getAttribute(const AttributeList& attributeList,const StateAttribute::Type type, unsigned int member) const; + const RefAttributePair* getAttributePair(const AttributeList& attributeList,const StateAttribute::Type type, unsigned int member) const; + + int _renderingHint; + + RenderBinMode _binMode; + int _binNum; + std::string _binName; + bool _nestRenderBins; + + ref_ptr _updateCallback; + unsigned int _numChildrenRequiringUpdateTraversal; + void setNumChildrenRequiringUpdateTraversal(unsigned int num); + + ref_ptr _eventCallback; + unsigned int _numChildrenRequiringEventTraversal; + void setNumChildrenRequiringEventTraversal(unsigned int num); + +}; + +extern OSG_EXPORT bool isTextureMode(StateAttribute::GLMode mode); + +} + +#endif diff --git a/libs/include/android/osg/Stats b/libs/include/android/osg/Stats new file mode 100755 index 0000000..ccdc06d --- /dev/null +++ b/libs/include/android/osg/Stats @@ -0,0 +1,125 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2007 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_STATS +#define OSG_STATS 1 + +#include +#include +#include + +#include +#include +#include +#include + +namespace osg { + +class OSG_EXPORT Stats : public osg::Referenced +{ + public: + + Stats(const std::string& name); + + Stats(const std::string& name, unsigned int numberOfFrames); + + void setName(const std::string& name) { _name = name; } + const std::string& getName() const { return _name; } + + void allocate(unsigned int numberOfFrames); + + unsigned int getEarliestFrameNumber() const { return _latestFrameNumber < static_cast(_attributeMapList.size()) ? 0 : _latestFrameNumber - static_cast(_attributeMapList.size()) + 1; } + unsigned int getLatestFrameNumber() const { return _latestFrameNumber; } + + typedef std::map AttributeMap; + typedef std::vector AttributeMapList; + + bool setAttribute(unsigned int frameNumber, const std::string& attributeName, double value); + + inline bool getAttribute(unsigned int frameNumber, const std::string& attributeName, double& value) const + { + OpenThreads::ScopedLock lock(_mutex); + return getAttributeNoMutex(frameNumber, attributeName, value); + } + + bool getAveragedAttribute(const std::string& attributeName, double& value, bool averageInInverseSpace=false) const; + + bool getAveragedAttribute(unsigned int startFrameNumber, unsigned int endFrameNumber, const std::string& attributeName, double& value, bool averageInInverseSpace=false) const; + + inline AttributeMap& getAttributeMap(unsigned int frameNumber) + { + OpenThreads::ScopedLock lock(_mutex); + return getAttributeMapNoMutex(frameNumber); + } + + inline const AttributeMap& getAttributeMap(unsigned int frameNumber) const + { + OpenThreads::ScopedLock lock(_mutex); + return getAttributeMapNoMutex(frameNumber); + } + + typedef std::map CollectMap; + + void collectStats(const std::string& str, bool flag) { _collectMap[str] = flag; } + + inline bool collectStats(const std::string& str) const + { + OpenThreads::ScopedLock lock(_mutex); + + CollectMap::const_iterator itr = _collectMap.find(str); + return (itr != _collectMap.end()) ? itr->second : false; + } + + void report(std::ostream& out, const char* indent=0) const; + void report(std::ostream& out, unsigned int frameNumber, const char* indent=0) const; + + protected: + + virtual ~Stats() {} + + bool getAttributeNoMutex(unsigned int frameNumber, const std::string& attributeName, double& value) const; + + AttributeMap& getAttributeMapNoMutex(unsigned int frameNumber); + const AttributeMap& getAttributeMapNoMutex(unsigned int frameNumber) const; + + + int getIndex(unsigned int frameNumber) const + { + // reject frame that are in the future + if (frameNumber > _latestFrameNumber) return -1; + + // reject frames that are too early + if (frameNumber < getEarliestFrameNumber()) return -1; + + if (frameNumber >= _baseFrameNumber) return frameNumber - _baseFrameNumber; + else return static_cast(_attributeMapList.size()) - (_baseFrameNumber-frameNumber); + } + + std::string _name; + + mutable OpenThreads::Mutex _mutex; + + unsigned int _baseFrameNumber; + unsigned int _latestFrameNumber; + + AttributeMapList _attributeMapList; + AttributeMap _invalidAttributeMap; + + CollectMap _collectMap; + +}; + + +} + +#endif diff --git a/libs/include/android/osg/Stencil b/libs/include/android/osg/Stencil new file mode 100755 index 0000000..912586c --- /dev/null +++ b/libs/include/android/osg/Stencil @@ -0,0 +1,228 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_STENCIL +#define OSG_STENCIL 1 + +#include + +namespace osg { + +#ifndef GL_INCR_WRAP +#define GL_INCR_WRAP 0x8507 +#define GL_DECR_WRAP 0x8508 +#endif + + +/** Encapsulate OpenGL glStencilFunc/Op/Mask functions. +* +* All functionality except INCR_WRAP and DECR_WRAP is supported by OpenGL 1.1. +* INCR_WRAP an DECR_WRAP are available since OpenGL 1.4 or when +* GL_EXT_stencil_wrap extension is present. +* +* If INCR_WRAP or DECR_WRAP values are used while they are detected to be not supported, +* the INCR or DECR values are sent to OpenGL instead. Note: do not use Stencil::getFunction() +* to detect whether WRAP operations is used as the object's value is kept intact. +* Use osg::Stencil::getExtensions() method instead. +* +* OpenGL 2.0 introduced two side stenciling that is available through +* osg::StencilTwoSided class. +*/ +class OSG_EXPORT Stencil : public StateAttribute +{ + public : + + + Stencil(); + + /** Copy constructor using CopyOp to manage deep vs shallow copy.*/ + Stencil(const Stencil& stencil,const CopyOp& copyop=CopyOp::SHALLOW_COPY): + StateAttribute(stencil,copyop), + _func(stencil._func), + _funcRef(stencil._funcRef), + _funcMask(stencil._funcMask), + _sfail(stencil._sfail), + _zfail(stencil._zfail), + _zpass(stencil._zpass), + _writeMask(stencil._writeMask) {} + + + META_StateAttribute(osg, Stencil, STENCIL); + + /** return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs.*/ + virtual int compare(const StateAttribute& sa) const + { + // check the types are equal and then create the rhs variable + // used by the COMPARE_StateAttribute_Parameter macros below. + COMPARE_StateAttribute_Types(Stencil,sa) + + // compare each parameter in turn against the rhs. + COMPARE_StateAttribute_Parameter(_func) + COMPARE_StateAttribute_Parameter(_funcRef) + COMPARE_StateAttribute_Parameter(_funcMask) + COMPARE_StateAttribute_Parameter(_sfail) + COMPARE_StateAttribute_Parameter(_zfail) + COMPARE_StateAttribute_Parameter(_zpass) + COMPARE_StateAttribute_Parameter(_writeMask) + + return 0; // passed all the above comparison macros, must be equal. + } + + virtual bool getModeUsage(StateAttribute::ModeUsage& usage) const + { + usage.usesMode(GL_STENCIL_TEST); + return true; + } + + enum Function + { + NEVER = GL_NEVER, + LESS = GL_LESS, + EQUAL = GL_EQUAL, + LEQUAL = GL_LEQUAL, + GREATER = GL_GREATER, + NOTEQUAL = GL_NOTEQUAL, + GEQUAL = GL_GEQUAL, + ALWAYS = GL_ALWAYS + }; + + inline void setFunction(Function func,int ref,unsigned int mask) + { + _func = func; + _funcRef = ref; + _funcMask = mask; + } + + inline void setFunction(Function func) { _func = func; } + inline Function getFunction() const { return _func; } + + inline void setFunctionRef(int ref) { _funcRef=ref; } + inline int getFunctionRef() const { return _funcRef; } + + inline void setFunctionMask(unsigned int mask) { _funcMask=mask; } + inline unsigned int getFunctionMask() const { return _funcMask; } + + + enum Operation + { + KEEP = GL_KEEP, + ZERO = GL_ZERO, + REPLACE = GL_REPLACE, + INCR = GL_INCR, + DECR = GL_DECR, + INVERT = GL_INVERT, + INCR_WRAP = GL_INCR_WRAP, + DECR_WRAP = GL_DECR_WRAP + }; + + /** set the operations to apply when the various stencil and depth + * tests fail or pass. First parameter is to control the operation + * when the stencil test fails. The second parameter is to control the + * operation when the stencil test passes, but depth test fails. The + * third parameter controls the operation when both the stencil test + * and depth pass. Ordering of parameter is the same as if using + * glStencilOp(,,).*/ + inline void setOperation(Operation sfail, Operation zfail, Operation zpass) + { + _sfail = sfail; + _zfail = zfail; + _zpass = zpass; + } + + /** set the operation when the stencil test fails.*/ + inline void setStencilFailOperation(Operation sfail) { _sfail = sfail; } + + /** get the operation when the stencil test fails.*/ + inline Operation getStencilFailOperation() const { return _sfail; } + + /** set the operation when the stencil test passes but the depth test fails.*/ + inline void setStencilPassAndDepthFailOperation(Operation zfail) { _zfail=zfail; } + + /** get the operation when the stencil test passes but the depth test fails.*/ + inline Operation getStencilPassAndDepthFailOperation() const { return _zfail; } + + /** set the operation when both the stencil test and the depth test pass.*/ + inline void setStencilPassAndDepthPassOperation(Operation zpass) { _zpass=zpass; } + + /** get the operation when both the stencil test and the depth test pass.*/ + inline Operation getStencilPassAndDepthPassOperation() const { return _zpass; } + + + inline void setWriteMask(unsigned int mask) { _writeMask = mask; } + + inline unsigned int getWriteMask() const { return _writeMask; } + + + virtual void apply(State& state) const; + + + + /** Extensions class which encapsulates the querying of extensions and + * associated function pointers, and provide convenience wrappers to + * check for the extensions or use the associated functions. + */ + class OSG_EXPORT Extensions : public osg::Referenced + { + public: + Extensions(unsigned int contextID); + + Extensions(const Extensions& rhs); + + void lowestCommonDenominator(const Extensions& rhs); + + void setupGLExtensions(unsigned int contextID); + + void setStencilWrapSupported(bool flag) { _isStencilWrapSupported = flag; } + bool isStencilWrapSupported() const { return _isStencilWrapSupported; } + + protected: + + ~Extensions() {} + + bool _isStencilWrapSupported; + }; + + /** Function to call to get the extension of a specified context. + * If the Extension object for that context has not yet been created + * and the 'createIfNotInitalized' flag been set to false then returns NULL. + * If 'createIfNotInitalized' is true then the Extensions object is + * automatically created. However, in this case the extension object + * will only be created with the graphics context associated with ContextID. + */ + static Extensions* getExtensions(unsigned int contextID, bool createIfNotInitalized); + + /** The setExtensions method allows users to override the extensions across graphics contexts. + * Typically used when you have different extensions supported across graphics pipes + * but need to ensure that they all use the same low common denominator extensions. + */ + static void setExtensions(unsigned int contextID, Extensions* extensions); + + protected: + + virtual ~Stencil(); + + Function _func; + int _funcRef; + unsigned int _funcMask; + + Operation _sfail; + Operation _zfail; + Operation _zpass; + + unsigned int _writeMask; + +}; + +} + +#endif diff --git a/libs/include/android/osg/StencilTwoSided b/libs/include/android/osg/StencilTwoSided new file mode 100755 index 0000000..fc33cc8 --- /dev/null +++ b/libs/include/android/osg/StencilTwoSided @@ -0,0 +1,231 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_STENCILTWOSIDED +#define OSG_STENCILTWOSIDED 1 + +#include + +namespace osg { + +#ifndef GL_STENCIL_TEST_TWO_SIDE +#define GL_STENCIL_TEST_TWO_SIDE 0x8910 +#endif + +/** Provides OpenGL two sided stencil functionality, also known as separate stencil. + * It enables to specify different stencil function for front and back facing polygons. + * Two sided stenciling is used usually to eliminate the need of two rendering passes + * when using standard stenciling functions. See also \sa osg::Stencil. + * + * Two sided stenciling is available since OpenGL 2.0. It is also supported by + * EXT_stencil_two_side extension especially on Nvidia cards. + * Another extension introduced by ATI is ATI_separate_stencil. However, ATI's extension + * is limited to have reference and mask value the same for both faces. + * ATI's extension is currently not supported by the current implementation. + * + * osg::StencilTwoSided does nothing if OpenGL 2.0 or EXT_stencil_two_side are not available. +*/ +class OSG_EXPORT StencilTwoSided : public StateAttribute +{ + public : + + + StencilTwoSided(); + + /** Copy constructor using CopyOp to manage deep vs shallow copy.*/ + StencilTwoSided(const StencilTwoSided& stencil,const CopyOp& copyop=CopyOp::SHALLOW_COPY); + + META_StateAttribute(osg, StencilTwoSided, STENCIL); + + /** return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs.*/ + virtual int compare(const StateAttribute& sa) const; + + virtual bool getModeUsage(StateAttribute::ModeUsage& usage) const + { + usage.usesMode(GL_STENCIL_TEST); + return true; + } + + enum Face + { + FRONT = 0, + BACK = 1 + }; + + enum Function + { + NEVER = GL_NEVER, + LESS = GL_LESS, + EQUAL = GL_EQUAL, + LEQUAL = GL_LEQUAL, + GREATER = GL_GREATER, + NOTEQUAL = GL_NOTEQUAL, + GEQUAL = GL_GEQUAL, + ALWAYS = GL_ALWAYS + }; + + inline void setFunction(Face face, Function func,int ref,unsigned int mask) + { + _func[face] = func; + _funcRef[face] = ref; + _funcMask[face] = mask; + } + + inline void setFunction(Face face, Function func) { _func[face] = func; } + inline Function getFunction(Face face) const { return _func[face]; } + + inline void setFunctionRef(Face face, int ref) { _funcRef[face]=ref; } + inline int getFunctionRef(Face face) const { return _funcRef[face]; } + + inline void setFunctionMask(Face face, unsigned int mask) { _funcMask[face]=mask; } + inline unsigned int getFunctionMask(Face face) const { return _funcMask[face]; } + + + enum Operation + { + KEEP = GL_KEEP, + ZERO = GL_ZERO, + REPLACE = GL_REPLACE, + INCR = GL_INCR, + DECR = GL_DECR, + INVERT = GL_INVERT, + INCR_WRAP = GL_INCR_WRAP, + DECR_WRAP = GL_DECR_WRAP + }; + + /** set the operations to apply when the various stencil and depth + * tests fail or pass. First parameter is to control the operation + * when the stencil test fails. The second parameter is to control the + * operation when the stencil test passes, but depth test fails. The + * third parameter controls the operation when both the stencil test + * and depth pass. Ordering of parameter is the same as if using + * glStencilOp(,,).*/ + inline void setOperation(Face face, Operation sfail, Operation zfail, Operation zpass) + { + _sfail[face] = sfail; + _zfail[face] = zfail; + _zpass[face] = zpass; + } + + /** set the operation when the stencil test fails.*/ + inline void setStencilFailOperation(Face face, Operation sfail) { _sfail[face] = sfail; } + + /** get the operation when the stencil test fails.*/ + inline Operation getStencilFailOperation(Face face) const { return _sfail[face]; } + + /** set the operation when the stencil test passes but the depth test fails.*/ + inline void setStencilPassAndDepthFailOperation(Face face, Operation zfail) { _zfail[face]=zfail; } + + /** get the operation when the stencil test passes but the depth test fails.*/ + inline Operation getStencilPassAndDepthFailOperation(Face face) const { return _zfail[face]; } + + /** set the operation when both the stencil test and the depth test pass.*/ + inline void setStencilPassAndDepthPassOperation(Face face, Operation zpass) { _zpass[face]=zpass; } + + /** get the operation when both the stencil test and the depth test pass.*/ + inline Operation getStencilPassAndDepthPassOperation(Face face) const { return _zpass[face]; } + + + inline void setWriteMask(Face face, unsigned int mask) { _writeMask[face] = mask; } + + inline unsigned int getWriteMask(Face face) const { return _writeMask[face]; } + + + virtual void apply(State& state) const; + + public: + + /** Extensions class which encapsulates the querying of extensions and + * associated function pointers, and provide convenience wrappers to + * check for the extensions or use the associated functions. + */ + class OSG_EXPORT Extensions : public osg::Referenced + { + public: + Extensions(unsigned int contextID); + + Extensions(const Extensions& rhs); + + void lowestCommonDenominator(const Extensions& rhs); + + void setupGLExtensions(unsigned int contextID); + + void setStencilTwoSidedSupported(bool flag) { _isStencilTwoSidedSupported=flag; } + bool isStencilTwoSidedSupported() const { return _isStencilTwoSidedSupported; } + void setOpenGL20Supported(bool flag) { _isOpenGL20Supported=flag; } + bool isOpenGL20Supported() const { return _isOpenGL20Supported; } + void setSeparateStencilSupported(bool flag) { _isSeparateStencilSupported=flag; } + bool isSeparateStencilSupported() const { return _isSeparateStencilSupported; } + + void glActiveStencilFace(GLenum face) const; + void glStencilOpSeparate(GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass) const; + void glStencilMaskSeparate(GLenum face, GLuint mask) const; + void glStencilFuncSeparate(GLenum face, GLenum func, GLint ref, GLuint mask) const; + void glStencilFuncSeparateATI(GLenum frontfunc, GLenum backfunc, GLint ref, GLuint mask) const; + + protected: + + ~Extensions() {} + + bool _isStencilTwoSidedSupported; + bool _isOpenGL20Supported; + bool _isSeparateStencilSupported; + + typedef void (GL_APIENTRY * ActiveStencilFaceProc) (GLenum); + typedef void (GL_APIENTRY * StencilOpSeparate) (GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass); + typedef void (GL_APIENTRY * StencilMaskSeparate) (GLenum face, GLuint mask); + typedef void (GL_APIENTRY * StencilFuncSeparate) (GLenum face, GLenum func, GLint ref, GLuint mask); + typedef void (GL_APIENTRY * StencilFuncSeparateATI) (GLenum frontfunc, GLenum backfunc, GLint ref, GLuint mask); + + ActiveStencilFaceProc _glActiveStencilFace; + StencilOpSeparate _glStencilOpSeparate; + StencilMaskSeparate _glStencilMaskSeparate; + StencilFuncSeparate _glStencilFuncSeparate; + StencilFuncSeparate _glStencilFuncSeparateATI; + }; + + /** Function to call to get the extension of a specified context. + * If the Extension object for that context has not yet been created + * and the 'createIfNotInitalized' flag been set to false then returns NULL. + * If 'createIfNotInitalized' is true then the Extensions object is + * automatically created. However, in this case the extension object + * will only be created with the graphics context associated with ContextID. + */ + static Extensions* getExtensions(unsigned int contextID,bool createIfNotInitalized); + + /** The setExtensions method allows users to override the extensions across graphics contexts. + * Typically used when you have different extensions supported across graphics pipes + * but need to ensure that they all use the same low common denominator extensions. + */ + static void setExtensions(unsigned int contextID,Extensions* extensions); + + + protected: + + virtual ~StencilTwoSided(); + + Function _func[2]; + int _funcRef[2]; + unsigned int _funcMask[2]; + + Operation _sfail[2]; + Operation _zfail[2]; + Operation _zpass[2]; + + unsigned int _writeMask[2]; + +}; + +} + +#endif diff --git a/libs/include/android/osg/Switch b/libs/include/android/osg/Switch new file mode 100755 index 0000000..65635d2 --- /dev/null +++ b/libs/include/android/osg/Switch @@ -0,0 +1,98 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_SWITCH +#define OSG_SWITCH 1 + +#include + +namespace osg { + +/** Switch is a Group node that allows switching between children. + * Typical uses would be for objects which might need to be rendered + * differently at different times, for instance a switch could be used + * to represent the different states of a traffic light. +*/ +class OSG_EXPORT Switch : public Group +{ + public : + + + Switch(); + + /** Copy constructor using CopyOp to manage deep vs shallow copy. */ + Switch(const Switch&,const CopyOp& copyop=CopyOp::SHALLOW_COPY); + + virtual Switch* asSwitch() { return this; } + virtual const Switch* asSwitch() const { return this; } + + + META_Node(osg, Switch); + + virtual void traverse(NodeVisitor& nv); + + void setNewChildDefaultValue(bool value) { _newChildDefaultValue = value; } + + bool getNewChildDefaultValue() const { return _newChildDefaultValue; } + + virtual bool addChild( Node *child ); + + virtual bool addChild( Node *child, bool value ); + + virtual bool insertChild( unsigned int index, Node *child ); + + virtual bool insertChild( unsigned int index, Node *child, bool value ); + + virtual bool removeChildren(unsigned int pos,unsigned int numChildrenToRemove); + + + void setValue(unsigned int pos,bool value); + + bool getValue(unsigned int pos) const; + + void setChildValue(const Node* child,bool value); + + bool getChildValue(const Node* child) const; + + /** Set all the children off (false), and set the new default child + * value to off (false). */ + bool setAllChildrenOff(); + + /** Set all the children on (true), and set the new default child + * value to on (true). */ + bool setAllChildrenOn(); + + /** Set a single child on, switch off all other children. */ + bool setSingleChildOn(unsigned int pos); + + + typedef std::vector ValueList; + + void setValueList(const ValueList& values) { _values=values; } + + const ValueList& getValueList() const { return _values; } + + virtual BoundingSphere computeBound() const; + + protected : + + virtual ~Switch() {} + + // This is effectively a bit mask. + bool _newChildDefaultValue; + ValueList _values; +}; + +} + +#endif diff --git a/libs/include/android/osg/TemplatePrimitiveFunctor b/libs/include/android/osg/TemplatePrimitiveFunctor new file mode 100755 index 0000000..699e0c8 --- /dev/null +++ b/libs/include/android/osg/TemplatePrimitiveFunctor @@ -0,0 +1,317 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_TERMPLATEPRIMITIVEFUNCTOR +#define OSG_TERMPLATEPRIMITIVEFUNCTOR 1 + +#include +#include + +namespace osg { + + + /** Provides access to the primitives that compose an \c osg::Drawable. + *

Notice that \c TemplatePrimitiveFunctor is a class template, and that it inherits + * from its template parameter \c T. This template parameter must implement + * operator()(const osg::Vec3 v1, const osg::Vec3 v2, const osg::Vec3 + * v3, bool treatVertexDataAsTemporary), + * operator()(const osg::Vec3 v1, const osg::Vec3 v2, bool + * treatVertexDataAsTemporary), operator()(const osg::Vec3 v1, + * const osg::Vec3 v2, const osg::Vec3 v3, bool treatVertexDataAsTemporary), + * and operator()(const osg::Vec3 v1, const osg::Vec3 v2, const osg::Vec3 v3, + * const osg::Vec3 v4, bool treatVertexDataAsTemporary) which will be called + * for the matching primitive when the functor is applied to a \c Drawable. + * Parameters \c v1, \c v2, \c v3, and \c v4 are the vertices of the primitive. + * The last parameter, \c treatVertexDataAsTemporary, indicates whether these + * vertices are coming from a "real" vertex array, or from a temporary vertex array, + * created by the \c TemplatePrimitiveFunctor from some other geometry representation. + * @see \c PrimitiveFunctor for general usage hints. + */ + template + class TemplatePrimitiveFunctor : public PrimitiveFunctor, public T + { + public: + + TemplatePrimitiveFunctor() + { + _vertexArraySize=0; + _vertexArrayPtr=0; + _modeCache=0; + _treatVertexDataAsTemporary=false; + } + + virtual ~TemplatePrimitiveFunctor() {} + + void setTreatVertexDataAsTemporary(bool treatVertexDataAsTemporary) { _treatVertexDataAsTemporary=treatVertexDataAsTemporary; } + bool getTreatVertexDataAsTemporary() const { return _treatVertexDataAsTemporary; } + + virtual void setVertexArray(unsigned int,const Vec2*) + { + notify(WARN)<<"Triangle Functor does not support Vec2* vertex arrays"<operator()(*(vptr),*(vptr+1),*(vptr+2),_treatVertexDataAsTemporary); + break; + } + case(GL_TRIANGLE_STRIP): { + const Vec3* vptr = &_vertexArrayPtr[first]; + for(GLsizei i=2;ioperator()(*(vptr),*(vptr+2),*(vptr+1),_treatVertexDataAsTemporary); + else this->operator()(*(vptr),*(vptr+1),*(vptr+2),_treatVertexDataAsTemporary); + } + break; + } + case(GL_QUADS): { + const Vec3* vptr = &_vertexArrayPtr[first]; + for(GLsizei i=3;ioperator()(*(vptr),*(vptr+1),*(vptr+2),*(vptr+3),_treatVertexDataAsTemporary); + } + break; + } + case(GL_QUAD_STRIP): { + const Vec3* vptr = &_vertexArrayPtr[first]; + for(GLsizei i=3;ioperator()(*(vptr),*(vptr+1),*(vptr+3),*(vptr+2),_treatVertexDataAsTemporary); + } + break; + } + case(GL_POLYGON): // treat polygons as GL_TRIANGLE_FAN + case(GL_TRIANGLE_FAN): { + const Vec3* vfirst = &_vertexArrayPtr[first]; + const Vec3* vptr = vfirst+1; + for(GLsizei i=2;ioperator()(*(vfirst),*(vptr),*(vptr+1),_treatVertexDataAsTemporary); + } + break; + } + case(GL_POINTS): { + const Vec3* vlast = &_vertexArrayPtr[first+count]; + for(const Vec3* vptr=&_vertexArrayPtr[first];vptroperator()(*(vptr),_treatVertexDataAsTemporary); + break; + } + case(GL_LINES): { + const Vec3* vlast = &_vertexArrayPtr[first+count-1]; + for(const Vec3* vptr=&_vertexArrayPtr[first];vptroperator()(*(vptr),*(vptr+1),_treatVertexDataAsTemporary); + break; + } + case(GL_LINE_STRIP): { + const Vec3* vlast = &_vertexArrayPtr[first+count-1]; + for(const Vec3* vptr=&_vertexArrayPtr[first];vptroperator()(*(vptr),*(vptr+1),_treatVertexDataAsTemporary); + break; + } + case(GL_LINE_LOOP): { + const Vec3* vlast = &_vertexArrayPtr[first+count-1]; + for(const Vec3* vptr=&_vertexArrayPtr[first];vptroperator()(*(vptr),*(vptr+1),_treatVertexDataAsTemporary); + this->operator()(*(vlast),_vertexArrayPtr[first],_treatVertexDataAsTemporary); + break; + } + default: + break; + } + } + + template + void drawElementsTemplate(GLenum mode,GLsizei count,const IndexType* indices) + { + if (indices==0 || count==0) return; + + typedef const IndexType* IndexPointer; + + switch(mode) + { + case(GL_TRIANGLES): { + IndexPointer ilast = &indices[count]; + for(IndexPointer iptr=indices;iptroperator()(_vertexArrayPtr[*iptr],_vertexArrayPtr[*(iptr+1)],_vertexArrayPtr[*(iptr+2)],_treatVertexDataAsTemporary); + break; + } + case(GL_TRIANGLE_STRIP): { + IndexPointer iptr = indices; + for(GLsizei i=2;ioperator()(_vertexArrayPtr[*(iptr)],_vertexArrayPtr[*(iptr+2)], + _vertexArrayPtr[*(iptr+1)],_treatVertexDataAsTemporary); + else this->operator()(_vertexArrayPtr[*(iptr)],_vertexArrayPtr[*(iptr+1)], + _vertexArrayPtr[*(iptr+2)],_treatVertexDataAsTemporary); + } + break; + } + case(GL_QUADS): { + IndexPointer iptr = indices; + for(GLsizei i=3;ioperator()(_vertexArrayPtr[*(iptr)],_vertexArrayPtr[*(iptr+1)], + _vertexArrayPtr[*(iptr+2)],_vertexArrayPtr[*(iptr+3)], + _treatVertexDataAsTemporary); + } + break; + } + case(GL_QUAD_STRIP): { + IndexPointer iptr = indices; + for(GLsizei i=3;ioperator()(_vertexArrayPtr[*(iptr)],_vertexArrayPtr[*(iptr+1)], + _vertexArrayPtr[*(iptr+3)],_vertexArrayPtr[*(iptr+2)], + _treatVertexDataAsTemporary); + } + break; + } + case(GL_POLYGON): // treat polygons as GL_TRIANGLE_FAN + case(GL_TRIANGLE_FAN): { + IndexPointer iptr = indices; + const Vec3& vfirst = _vertexArrayPtr[*iptr]; + ++iptr; + for(GLsizei i=2;ioperator()(vfirst,_vertexArrayPtr[*(iptr)],_vertexArrayPtr[*(iptr+1)], + _treatVertexDataAsTemporary); + } + break; + } + case(GL_POINTS): { + IndexPointer ilast = &indices[count]; + for(IndexPointer iptr=indices;iptroperator()(_vertexArrayPtr[*iptr],_treatVertexDataAsTemporary); + break; + } + case(GL_LINES): { + IndexPointer ilast = &indices[count-1]; + for(IndexPointer iptr=indices;iptroperator()(_vertexArrayPtr[*iptr],_vertexArrayPtr[*(iptr+1)], + _treatVertexDataAsTemporary); + break; + } + case(GL_LINE_STRIP): { + IndexPointer ilast = &indices[count-1]; + for(IndexPointer iptr=indices;iptroperator()(_vertexArrayPtr[*iptr],_vertexArrayPtr[*(iptr+1)], + _treatVertexDataAsTemporary); + break; + } + case(GL_LINE_LOOP): { + IndexPointer ilast = &indices[count-1]; + for(IndexPointer iptr=indices;iptroperator()(_vertexArrayPtr[*iptr],_vertexArrayPtr[*(iptr+1)], + _treatVertexDataAsTemporary); + this->operator()(_vertexArrayPtr[*(ilast)],_vertexArrayPtr[indices[0]], + _treatVertexDataAsTemporary); + break; + } + default: + break; + } + } + + + virtual void drawElements(GLenum mode,GLsizei count,const GLubyte* indices) + { + drawElementsTemplate(mode, count, indices); + } + + virtual void drawElements(GLenum mode,GLsizei count,const GLushort* indices) + { + drawElementsTemplate(mode, count, indices); + } + + virtual void drawElements(GLenum mode,GLsizei count,const GLuint* indices) + { + drawElementsTemplate(mode, count, indices); + } + + /** Note: + * begin(..),vertex(..) & end() are convenience methods for adapting + * non vertex array primitives to vertex array based primitives. + * This is done to simplify the implementation of primitive functor + * subclasses - users only need override drawArray and drawElements. + */ + virtual void begin(GLenum mode) + { + _modeCache = mode; + _vertexCache.clear(); + } + + virtual void vertex(const Vec2& vert) { _vertexCache.push_back(osg::Vec3(vert[0],vert[1],0.0f)); } + virtual void vertex(const Vec3& vert) { _vertexCache.push_back(vert); } + virtual void vertex(const Vec4& vert) { _vertexCache.push_back(osg::Vec3(vert[0],vert[1],vert[2])/vert[3]); } + virtual void vertex(float x,float y) { _vertexCache.push_back(osg::Vec3(x,y,0.0f)); } + virtual void vertex(float x,float y,float z) { _vertexCache.push_back(osg::Vec3(x,y,z)); } + virtual void vertex(float x,float y,float z,float w) { _vertexCache.push_back(osg::Vec3(x,y,z)/w); } + virtual void end() + { + if (!_vertexCache.empty()) + { + setVertexArray(_vertexCache.size(),&_vertexCache.front()); + _treatVertexDataAsTemporary = true; + drawArrays(_modeCache,0,_vertexCache.size()); + } + } + + protected: + + + unsigned int _vertexArraySize; + const Vec3* _vertexArrayPtr; + + GLenum _modeCache; + std::vector _vertexCache; + bool _treatVertexDataAsTemporary; + }; + + +} + +#endif diff --git a/libs/include/android/osg/TexEnv b/libs/include/android/osg/TexEnv new file mode 100755 index 0000000..8d24b51 --- /dev/null +++ b/libs/include/android/osg/TexEnv @@ -0,0 +1,95 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_TEXENV +#define OSG_TEXENV 1 + +#include +#include +#include + +#ifndef OSG_GL_FIXED_FUNCTION_AVAILABLE + #define GL_MODULATE 0x2100 + #define GL_ADD 0x0104 + #define GL_MODULATE 0x2100 + #define GL_DECAL 0x2101 +#endif + +namespace osg { + +/** TexEnv encapsulates the OpenGL glTexEnv (texture environment) state. +*/ +class OSG_EXPORT TexEnv : public StateAttribute +{ + public : + + enum Mode { + DECAL = GL_DECAL, + MODULATE = GL_MODULATE, + BLEND = GL_BLEND, + REPLACE = GL_REPLACE, + ADD = GL_ADD + }; + + TexEnv(Mode mode=MODULATE); + + /** Copy constructor using CopyOp to manage deep vs shallow copy. */ + TexEnv(const TexEnv& texenv,const CopyOp& copyop=CopyOp::SHALLOW_COPY): + StateAttribute(texenv,copyop), + _mode(texenv._mode), + _color(texenv._color) {} + + + META_StateAttribute(osg, TexEnv, TEXENV); + + virtual bool isTextureAttribute() const { return true; } + + /** Return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs. */ + virtual int compare(const StateAttribute& sa) const + { + // Check for equal types, then create the rhs variable + // used by the COMPARE_StateAttribute_Parameter macros below. + COMPARE_StateAttribute_Types(TexEnv,sa) + + // Compare each parameter in turn against the rhs. + COMPARE_StateAttribute_Parameter(_mode) + COMPARE_StateAttribute_Parameter(_color) + + return 0; // Passed all the above comparison macros, so must be equal. + } + + + void setMode( Mode mode ) { _mode = mode; } + + Mode getMode() const { return _mode; } + + void setColor( const Vec4& color ) { _color = color; } + + Vec4& getColor() { return _color; } + + const Vec4& getColor() const { return _color; } + + + virtual void apply(State& state) const; + + protected : + + virtual ~TexEnv( void ); + + Mode _mode; + osg::Vec4 _color; +}; + +} + +#endif diff --git a/libs/include/android/osg/TexEnvCombine b/libs/include/android/osg/TexEnvCombine new file mode 100755 index 0000000..02f2783 --- /dev/null +++ b/libs/include/android/osg/TexEnvCombine @@ -0,0 +1,287 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_TEXENVCOMBINE +#define OSG_TEXENVCOMBINE 1 + +#include +#include +#include + +// If not defined by gl.h use the definition found in: +// http://oss.sgi.com/projects/ogl-sample/registry/ARB/texture_env_combine.txt +#ifndef GL_ARB_texture_env_combine +#define GL_COMBINE_ARB 0x8570 +#define GL_COMBINE_RGB_ARB 0x8571 +#define GL_COMBINE_ALPHA_ARB 0x8572 +#define GL_SOURCE0_RGB_ARB 0x8580 +#define GL_SOURCE1_RGB_ARB 0x8581 +#define GL_SOURCE2_RGB_ARB 0x8582 +#define GL_SOURCE0_ALPHA_ARB 0x8588 +#define GL_SOURCE1_ALPHA_ARB 0x8589 +#define GL_SOURCE2_ALPHA_ARB 0x858A +#define GL_OPERAND0_RGB_ARB 0x8590 +#define GL_OPERAND1_RGB_ARB 0x8591 +#define GL_OPERAND2_RGB_ARB 0x8592 +#define GL_OPERAND0_ALPHA_ARB 0x8598 +#define GL_OPERAND1_ALPHA_ARB 0x8599 +#define GL_OPERAND2_ALPHA_ARB 0x859A +#define GL_RGB_SCALE_ARB 0x8573 +#define GL_ADD_SIGNED_ARB 0x8574 +#define GL_INTERPOLATE_ARB 0x8575 +#define GL_SUBTRACT_ARB 0x84E7 +#define GL_CONSTANT_ARB 0x8576 +#define GL_PRIMARY_COLOR_ARB 0x8577 +#define GL_PREVIOUS_ARB 0x8578 +#endif + +#ifndef GL_ARB_texture_env_dot3 +#define GL_DOT3_RGB_ARB 0x86AE +#define GL_DOT3_RGBA_ARB 0x86AF +#endif + +#ifndef GL_TEXTURE0 +#define GL_TEXTURE0 0x84C0 +#endif + +namespace osg { + +/** TexEnvCombine encapsulates the OpenGL glTexEnvCombine (texture + * environment) state. */ +class OSG_EXPORT TexEnvCombine : public StateAttribute +{ + public : + + TexEnvCombine(); + + /** Copy constructor using CopyOp to manage deep vs shallow copy. */ + TexEnvCombine(const TexEnvCombine& texenv,const CopyOp& copyop=CopyOp::SHALLOW_COPY): + StateAttribute(texenv,copyop), + _needsTexEnvCrossbar(texenv._needsTexEnvCrossbar), + _combine_RGB(texenv._combine_RGB), + _combine_Alpha(texenv._combine_Alpha), + _source0_RGB(texenv._source0_RGB), + _source1_RGB(texenv._source1_RGB), + _source2_RGB(texenv._source2_RGB), + _source0_Alpha(texenv._source0_Alpha), + _source1_Alpha(texenv._source1_Alpha), + _source2_Alpha(texenv._source2_Alpha), + _operand0_RGB(texenv._operand0_RGB), + _operand1_RGB(texenv._operand1_RGB), + _operand2_RGB(texenv._operand2_RGB), + _operand0_Alpha(texenv._operand0_Alpha), + _operand1_Alpha(texenv._operand1_Alpha), + _operand2_Alpha(texenv._operand2_Alpha), + _scale_RGB(texenv._scale_RGB), + _scale_Alpha(texenv._scale_Alpha), + _constantColor(texenv._constantColor) {} + + + META_StateAttribute(osg, TexEnvCombine, TEXENV); + + + virtual bool isTextureAttribute() const { return true; } + + /** Return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs. */ + virtual int compare(const StateAttribute& sa) const + { + // Check for equal types, then create the rhs variable + // used by the COMPARE_StateAttribute_parameter macros below. + COMPARE_StateAttribute_Types(TexEnvCombine,sa) + + // Compare each parameter in turn against the rhs. + COMPARE_StateAttribute_Parameter(_needsTexEnvCrossbar) + COMPARE_StateAttribute_Parameter(_combine_RGB) + COMPARE_StateAttribute_Parameter(_combine_Alpha) + COMPARE_StateAttribute_Parameter(_source0_RGB) + COMPARE_StateAttribute_Parameter(_source1_RGB) + COMPARE_StateAttribute_Parameter(_source2_RGB) + COMPARE_StateAttribute_Parameter(_source0_Alpha) + COMPARE_StateAttribute_Parameter(_source1_Alpha) + COMPARE_StateAttribute_Parameter(_source2_Alpha) + COMPARE_StateAttribute_Parameter(_operand0_RGB) + COMPARE_StateAttribute_Parameter(_operand1_RGB) + COMPARE_StateAttribute_Parameter(_operand2_RGB) + COMPARE_StateAttribute_Parameter(_operand0_Alpha) + COMPARE_StateAttribute_Parameter(_operand1_Alpha) + COMPARE_StateAttribute_Parameter(_operand2_Alpha) + COMPARE_StateAttribute_Parameter(_scale_RGB) + COMPARE_StateAttribute_Parameter(_scale_Alpha) + COMPARE_StateAttribute_Parameter(_constantColor) + + return 0; // Passed all the above comparison macros, so must be equal. + } + + + enum CombineParam + { + REPLACE = GL_REPLACE, + MODULATE = GL_MODULATE, + ADD = GL_ADD, + ADD_SIGNED = GL_ADD_SIGNED_ARB, + INTERPOLATE = GL_INTERPOLATE_ARB, + SUBTRACT = GL_SUBTRACT_ARB, + DOT3_RGB = GL_DOT3_RGB_ARB, + DOT3_RGBA = GL_DOT3_RGBA_ARB + }; + + void setCombine_RGB(GLint cm); + void setCombine_Alpha(GLint cm); + + GLint getCombine_RGB() const { return _combine_RGB; } + GLint getCombine_Alpha() const { return _combine_Alpha; } + + enum SourceParam + { + CONSTANT = GL_CONSTANT_ARB, + PRIMARY_COLOR = GL_PRIMARY_COLOR_ARB, + PREVIOUS = GL_PREVIOUS_ARB, + TEXTURE = GL_TEXTURE, + TEXTURE0 = GL_TEXTURE0, + TEXTURE1 = GL_TEXTURE0+1, + TEXTURE2 = GL_TEXTURE0+2, + TEXTURE3 = GL_TEXTURE0+3, + TEXTURE4 = GL_TEXTURE0+4, + TEXTURE5 = GL_TEXTURE0+5, + TEXTURE6 = GL_TEXTURE0+6, + TEXTURE7 = GL_TEXTURE0+7 + }; + + void setSource0_RGB(GLint sp); + void setSource1_RGB(GLint sp); + void setSource2_RGB(GLint sp); + + void setSource0_Alpha(GLint sp); + void setSource1_Alpha(GLint sp); + void setSource2_Alpha(GLint sp); + + GLint getSource0_RGB() const { return _source0_RGB; } + GLint getSource1_RGB() const { return _source1_RGB; } + GLint getSource2_RGB() const { return _source2_RGB; } + + GLint getSource0_Alpha() const { return _source0_Alpha; } + GLint getSource1_Alpha() const { return _source1_Alpha; } + GLint getSource2_Alpha() const { return _source2_Alpha; } + + enum OperandParam + { + SRC_COLOR = GL_SRC_COLOR, + ONE_MINUS_SRC_COLOR = GL_ONE_MINUS_SRC_COLOR, + SRC_ALPHA = GL_SRC_ALPHA, + ONE_MINUS_SRC_ALPHA = GL_ONE_MINUS_SRC_ALPHA + }; + + void setOperand0_RGB(GLint op); + void setOperand1_RGB(GLint op); + void setOperand2_RGB(GLint op); + + void setOperand0_Alpha(GLint op); + void setOperand1_Alpha(GLint op); + void setOperand2_Alpha(GLint op); + + GLint getOperand0_RGB() const { return _operand0_RGB; } + GLint getOperand1_RGB() const { return _operand1_RGB; } + GLint getOperand2_RGB() const { return _operand2_RGB; } + + GLint getOperand0_Alpha() const { return _operand0_Alpha; } + GLint getOperand1_Alpha() const { return _operand1_Alpha; } + GLint getOperand2_Alpha() const { return _operand2_Alpha; } + + + void setScale_RGB(float scale); + void setScale_Alpha(float scale); + + float getScale_RGB() const { return _scale_RGB; } + float getScale_Alpha() const { return _scale_Alpha; } + + void setConstantColor( const Vec4& color ) { _constantColor = color; } + const Vec4& getConstantColor() const { return _constantColor; } + + /** Set the constant color attribute to the given light direction + * for use with DOT3 combine operation. */ + void setConstantColorAsLightDirection(const Vec3& direction) + { + _constantColor.set((direction.x()+1.0f)*0.5f,(direction.y()+1.0f)*0.5f,(direction.z()+1.0f)*0.5f,1.0f); + } + + Vec3 getConstantColorAsLightDirection() const + { + return Vec3(_constantColor.x()*2.0f-1.0f, _constantColor.y()*2.0f-1.0f, _constantColor.z()*2.0f-1.0f); + } + + virtual void apply(State& state) const; + + protected : + + virtual ~TexEnvCombine(); + + inline bool needsTexEnvCombiner(GLint value) const + { + switch(value) + { + case(CONSTANT): + case(PRIMARY_COLOR): + case(PREVIOUS): + case(TEXTURE): + return false; + } + return true; + } + + void computeNeedForTexEnvCombiners() + { + _needsTexEnvCrossbar = (needsTexEnvCombiner(_source0_RGB) || + needsTexEnvCombiner(_source1_RGB) || + needsTexEnvCombiner(_source2_RGB) || + needsTexEnvCombiner(_source0_Alpha) || + needsTexEnvCombiner(_source1_Alpha) || + needsTexEnvCombiner(_source2_Alpha)); + } + + + + + + bool _needsTexEnvCrossbar; + + GLint _combine_RGB; + GLint _combine_Alpha; + + GLint _source0_RGB; + GLint _source1_RGB; + GLint _source2_RGB; + + GLint _source0_Alpha; + GLint _source1_Alpha; + GLint _source2_Alpha; + + + GLint _operand0_RGB; + GLint _operand1_RGB; + GLint _operand2_RGB; + + GLint _operand0_Alpha; + GLint _operand1_Alpha; + GLint _operand2_Alpha; + + + float _scale_RGB; + float _scale_Alpha; + + osg::Vec4 _constantColor; + +}; + +} + +#endif diff --git a/libs/include/android/osg/TexEnvFilter b/libs/include/android/osg/TexEnvFilter new file mode 100755 index 0000000..38fe6d1 --- /dev/null +++ b/libs/include/android/osg/TexEnvFilter @@ -0,0 +1,70 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_TEXENVFILTER +#define OSG_TEXENVFILTER 1 + +#include +#include + +#ifndef GL_EXT_texture_lod_bias +#define GL_MAX_TEXTURE_LOD_BIAS_EXT 0x84FD +#define GL_TEXTURE_FILTER_CONTROL_EXT 0x8500 +#define GL_TEXTURE_LOD_BIAS_EXT 0x8501 +#endif + +namespace osg { + +/** TexEnvFilter - encapsulates the OpenGL glTexEnv (GL_TEXTURE_FILTER_CONTROL) state.*/ +class OSG_EXPORT TexEnvFilter : public StateAttribute +{ + public: + TexEnvFilter(float lodBias = 0.0f); + + /** Copy constructor using CopyOp to manage deep vs shallow copy.*/ + TexEnvFilter(const TexEnvFilter& texenv,const CopyOp& copyop=CopyOp::SHALLOW_COPY): + StateAttribute(texenv,copyop), + _lodBias(texenv._lodBias) {} + + META_StateAttribute(osg, TexEnvFilter, TEXENVFILTER); + + virtual bool isTextureAttribute() const { return true; } + + /** return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs.*/ + virtual int compare(const StateAttribute& sa) const + { + // check the types are equal and then create the rhs variable + // used by the COMPARE_StateAttribute_Parameter macros below. + COMPARE_StateAttribute_Types(TexEnvFilter, sa) + + // compare each parameter in turn against the rhs. + COMPARE_StateAttribute_Parameter(_lodBias) + + return 0; // passed all the above comparison macros, must be equal. + } + + void setLodBias( float lodBias ) { _lodBias = lodBias; } + + float getLodBias() const { return _lodBias; } + + virtual void apply(State& state) const; + + protected: + virtual ~TexEnvFilter(); + + float _lodBias; +}; + +} + +#endif diff --git a/libs/include/android/osg/TexGen b/libs/include/android/osg/TexGen new file mode 100755 index 0000000..cb72006 --- /dev/null +++ b/libs/include/android/osg/TexGen @@ -0,0 +1,142 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_TEXGEN +#define OSG_TEXGEN 1 + +#include +#include + +#if defined(OSG_GLES1_AVAILABLE) || defined(OSG_GLES2_AVAILABLE) || defined(OSG_GL3_AVAILABLE) + #define GL_OBJECT_LINEAR 0x2401 + #define GL_EYE_LINEAR 0x2400 + #define GL_SPHERE_MAP 0x2402 + #define GL_TEXTURE_GEN_S 0x0C60 + #define GL_TEXTURE_GEN_T 0x0C61 + #define GL_TEXTURE_GEN_R 0x0C62 + #define GL_TEXTURE_GEN_Q 0x0C63 +#endif + +#ifndef GL_NORMAL_MAP_ARB + #define GL_NORMAL_MAP_ARB 0x8511 +#endif + +#ifndef GL_REFLECTION_MAP_ARB + #define GL_REFLECTION_MAP_ARB 0x8512 +#endif + +namespace osg { + +/** TexGen encapsulates the OpenGL glTexGen (texture coordinate generation) + * state.*/ +class OSG_EXPORT TexGen : public StateAttribute +{ + public : + + TexGen(); + + /** Copy constructor using CopyOp to manage deep vs shallow copy. */ + TexGen(const TexGen& texgen,const CopyOp& copyop=CopyOp::SHALLOW_COPY): + StateAttribute(texgen,copyop), + _mode(texgen._mode), + _plane_s(texgen._plane_s), + _plane_t(texgen._plane_t), + _plane_r(texgen._plane_r), + _plane_q(texgen._plane_q) {} + + META_StateAttribute(osg, TexGen, TEXGEN); + + virtual bool isTextureAttribute() const { return true; } + + /** Return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs. */ + virtual int compare(const StateAttribute& sa) const + { + // Check for equal types, then create the rhs variable + // used by the COMPARE_StateAttribute_Parameter macros below. + COMPARE_StateAttribute_Types(TexGen,sa) + + // Compare each parameter in turn against the rhs. + COMPARE_StateAttribute_Parameter(_mode) + COMPARE_StateAttribute_Parameter(_plane_s) + COMPARE_StateAttribute_Parameter(_plane_t) + COMPARE_StateAttribute_Parameter(_plane_r) + COMPARE_StateAttribute_Parameter(_plane_q) + + return 0; // Passed all the above comparison macros, so must be equal. + } + + virtual bool getModeUsage(StateAttribute::ModeUsage& usage) const + { + usage.usesTextureMode(GL_TEXTURE_GEN_S); + usage.usesTextureMode(GL_TEXTURE_GEN_T); + + // Not happy with turning all tex gen parameters on + // as the OSG currently only supports 2D textures and therefore + // only S and T will be required, R&Q would be redundant... + // So commenting out the following until OSG supports 3D textures. + // I plan to revamp the OpenGL state management later so will + // tidy up then. Robert Osfield. Jan 2001. + + // The tidy up is now happening, but will have a think before + // resolving the below parameters. + + usage.usesTextureMode(GL_TEXTURE_GEN_R); + usage.usesTextureMode(GL_TEXTURE_GEN_Q); + return true; + } + + virtual void apply(State& state) const; + + enum Mode { + OBJECT_LINEAR = GL_OBJECT_LINEAR, + EYE_LINEAR = GL_EYE_LINEAR, + SPHERE_MAP = GL_SPHERE_MAP, + NORMAL_MAP = GL_NORMAL_MAP_ARB, + REFLECTION_MAP = GL_REFLECTION_MAP_ARB + }; + + inline void setMode( Mode mode ) { _mode = mode; } + + Mode getMode() const { return _mode; } + + enum Coord { + S, T, R, Q + }; + + void setPlane(Coord which, const Plane& plane); + + Plane& getPlane(Coord which); + + const Plane& getPlane(Coord which) const; + + /** Set the tex gen planes from specified matrix. + * Typical usage would be to pass in a projection + * matrix to set up projective texturing. + */ + void setPlanesFromMatrix(const Matrixd& matrix); + + protected : + + virtual ~TexGen( void ); + + Mode _mode; + + /** Additional texgen coefficients for GL_OBJECT_PLANE or + * GL_EYE_PLANE, */ + Plane _plane_s, _plane_t, _plane_r, _plane_q; + +}; + +} + +#endif diff --git a/libs/include/android/osg/TexGenNode b/libs/include/android/osg/TexGenNode new file mode 100755 index 0000000..f63c4d5 --- /dev/null +++ b/libs/include/android/osg/TexGenNode @@ -0,0 +1,78 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_TexGenNode +#define OSG_TexGenNode 1 + +#include +#include + +namespace osg { + +/** Node for defining the position of TexGen in the scene. */ +class OSG_EXPORT TexGenNode : public Group +{ + + public: + + TexGenNode(); + TexGenNode(TexGen* texgen); + + TexGenNode(const TexGenNode& tgb, const CopyOp& copyop=CopyOp::SHALLOW_COPY); + + META_Node(osg, TexGenNode); + + + enum ReferenceFrame + { + RELATIVE_RF, + ABSOLUTE_RF + }; + + /** Set the TexGenNode's ReferenceFrame, either to be relative to its + * parent reference frame. */ + void setReferenceFrame(ReferenceFrame rf); + + /** Get the TexGenNode's ReferenceFrame.*/ + ReferenceFrame getReferenceFrame() const { return _referenceFrame; } + + /** Set the texture unit that this TexGenNode is associated with.*/ + void setTextureUnit(unsigned int textureUnit) { _textureUnit = textureUnit; } + + unsigned int getTextureUnit() const { return _textureUnit; } + + /** Set the TexGen. */ + void setTexGen(TexGen* texgen); + + /** Get the TexGen. */ + inline TexGen* getTexGen() { return _texgen.get(); } + + /** Get the const TexGen. */ + inline const TexGen* getTexGen() const { return _texgen.get(); } + + /** Set whether to use a mutex to ensure ref() and unref() are thread safe.*/ + virtual void setThreadSafeRefUnref(bool threadSafe); + + protected: + + virtual ~TexGenNode(); + + unsigned int _textureUnit; + osg::ref_ptr _texgen; + + ReferenceFrame _referenceFrame; +}; + +} + +#endif diff --git a/libs/include/android/osg/TexMat b/libs/include/android/osg/TexMat new file mode 100755 index 0000000..a0e5b3b --- /dev/null +++ b/libs/include/android/osg/TexMat @@ -0,0 +1,89 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_TEXMAT +#define OSG_TEXMAT 1 + +#include +#include + +namespace osg { + +/** A texture matrix state class that encapsulates OpenGL texture matrix + * functionality. */ +class OSG_EXPORT TexMat : public StateAttribute +{ + public : + + TexMat(); + + TexMat(const Matrix& matrix):_matrix(matrix),_scaleByTextureRectangleSize(false) {} + + /** Copy constructor using CopyOp to manage deep vs shallow copy. */ + TexMat(const TexMat& texmat,const CopyOp& copyop=CopyOp::SHALLOW_COPY): + StateAttribute(texmat,copyop), + _matrix(texmat._matrix), + _scaleByTextureRectangleSize(texmat._scaleByTextureRectangleSize) {} + + META_StateAttribute(osg, TexMat, TEXMAT); + + virtual bool isTextureAttribute() const { return true; } + + /** Return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs. */ + virtual int compare(const StateAttribute& sa) const + { + // Check for equal types, then create the rhs variable + // used by the COMPARE_StateAttribute_Parameter macros below. + COMPARE_StateAttribute_Types(TexMat,sa) + + // Compare each parameter in turn against the rhs. + COMPARE_StateAttribute_Parameter(_matrix) + + return 0; // Passed all the above comparison macros, so must be equal. + } + + /** Set the texture matrix */ + inline void setMatrix(const Matrix& matrix) { _matrix = matrix; } + + /** Get the texture matrix */ + inline Matrix& getMatrix() { return _matrix; } + + /** Get the const texture matrix */ + inline const Matrix& getMatrix() const { return _matrix; } + + /** Switch on/off the post scaling of the TexMat matrix by the size of the last applied texture rectangle. + * Use a TexMat alongside a TextureRectangle with this scaling applied allows one to treat a TextureRectnagles texture coordinate + * range as if it were the usual non dimensional 0.0 to 1.0 range. + * Note, the TexMat matrix itself is not modified by the post scaling, its purely an operation passed to OpenGL to do the post scaling once the + * the TexMat matrix has been loaded.*/ + void setScaleByTextureRectangleSize(bool flag) { _scaleByTextureRectangleSize = flag; } + + /** Get whether the post scaling of the TexMat matrix, by the size of the last applied texture rectangle, is switched on/off.*/ + bool getScaleByTextureRectangleSize() const { return _scaleByTextureRectangleSize; } + + /** Apply texture matrix to OpenGL state. */ + virtual void apply(State& state) const; + + protected: + + virtual ~TexMat( void ); + + Matrix _matrix; + bool _scaleByTextureRectangleSize; + +}; + +} + + +#endif diff --git a/libs/include/android/osg/Texture b/libs/include/android/osg/Texture new file mode 100755 index 0000000..8035732 --- /dev/null +++ b/libs/include/android/osg/Texture @@ -0,0 +1,1456 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_TEXTURE +#define OSG_TEXTURE 1 + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +// If not defined by gl.h use the definition found in: +// http://oss.sgi.com/projects/ogl-sample/registry/EXT/texture_filter_anisotropic.txt +#ifndef GL_TEXTURE_MAX_ANISOTROPY_EXT + #define GL_TEXTURE_MAX_ANISOTROPY_EXT 0x84FE +#endif + +// If not defined, use the definition found in: +// http://www.opengl.org/registry/specs/ARB/texture_swizzle.txt +#ifndef GL_TEXTURE_SWIZZLE_RGBA + #define GL_TEXTURE_SWIZZLE_RGBA 0x8E46 +#endif + +#ifndef GL_ARB_texture_compression + #define GL_COMPRESSED_ALPHA_ARB 0x84E9 + #define GL_COMPRESSED_LUMINANCE_ARB 0x84EA + #define GL_COMPRESSED_LUMINANCE_ALPHA_ARB 0x84EB + #define GL_COMPRESSED_INTENSITY_ARB 0x84EC + #define GL_COMPRESSED_RGB_ARB 0x84ED + #define GL_COMPRESSED_RGBA_ARB 0x84EE + #define GL_TEXTURE_COMPRESSION_HINT_ARB 0x84EF + #define GL_TEXTURE_COMPRESSED_ARB 0x86A1 + #define GL_NUM_COMPRESSED_TEXTURE_FORMATS_ARB 0x86A2 + #define GL_COMPRESSED_TEXTURE_FORMATS_ARB 0x86A3 +#endif + +#ifndef GL_TEXTURE_COMPRESSED_IMAGE_SIZE_ARB + #define GL_TEXTURE_COMPRESSED_IMAGE_SIZE_ARB 0x86A0 +#endif + +#ifndef GL_EXT_texture_compression_s3tc + #define GL_COMPRESSED_RGB_S3TC_DXT1_EXT 0x83F0 + #define GL_COMPRESSED_RGBA_S3TC_DXT1_EXT 0x83F1 + #define GL_COMPRESSED_RGBA_S3TC_DXT3_EXT 0x83F2 + #define GL_COMPRESSED_RGBA_S3TC_DXT5_EXT 0x83F3 +#endif + +#ifndef GL_EXT_texture_compression_rgtc + #define GL_COMPRESSED_RED_RGTC1_EXT 0x8DBB + #define GL_COMPRESSED_SIGNED_RED_RGTC1_EXT 0x8DBC + #define GL_COMPRESSED_RED_GREEN_RGTC2_EXT 0x8DBD + #define GL_COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT 0x8DBE +#endif + +#ifndef GL_IMG_texture_compression_pvrtc + #define GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG 0x8C00 + #define GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG 0x8C01 + #define GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG 0x8C02 + #define GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG 0x8C03 +#endif + +#ifndef GL_OES_compressed_ETC1_RGB8_texture + #define GL_ETC1_RGB8_OES 0x8D64 +#endif + +#ifndef GL_ARB_INTERNAL_TEXTURE_FORMAT + #define GL_RGBA32F_ARB 0x8814 + #define GL_RGB32F_ARB 0x8815 + #define GL_ALPHA32F_ARB 0x8816 + #define GL_INTENSITY32F_ARB 0x8817 + #define GL_LUMINANCE32F_ARB 0x8818 + #define GL_LUMINANCE_ALPHA32F_ARB 0x8819 + #define GL_RGBA16F_ARB 0x881A + #define GL_RGB16F_ARB 0x881B + #define GL_ALPHA16F_ARB 0x881C + #define GL_INTENSITY16F_ARB 0x881D + #define GL_LUMINANCE16F_ARB 0x881E + #define GL_LUMINANCE_ALPHA16F_ARB 0x881F +#endif + +#ifndef GL_HALF_FLOAT + #define GL_HALF_FLOAT 0x140B +#endif + +#ifndef GL_NV_texture_shader + #define GL_HILO_NV 0x86F4 + #define GL_DSDT_NV 0x86F5 + #define GL_DSDT_MAG_NV 0x86F6 + #define GL_DSDT_MAG_VIB_NV 0x86F7 + #define GL_HILO16_NV 0x86F8 + #define GL_SIGNED_HILO_NV 0x86F9 + #define GL_SIGNED_HILO16_NV 0x86FA + #define GL_SIGNED_RGBA_NV 0x86FB + #define GL_SIGNED_RGBA8_NV 0x86FC + #define GL_SIGNED_RGB_NV 0x86FE + #define GL_SIGNED_RGB8_NV 0x86FF + #define GL_SIGNED_LUMINANCE_NV 0x8701 + #define GL_SIGNED_LUMINANCE8_NV 0x8702 + #define GL_SIGNED_LUMINANCE_ALPHA_NV 0x8703 + #define GL_SIGNED_LUMINANCE8_ALPHA8_NV 0x8704 + #define GL_SIGNED_ALPHA_NV 0x8705 + #define GL_SIGNED_ALPHA8_NV 0x8706 + #define GL_SIGNED_INTENSITY_NV 0x8707 + #define GL_SIGNED_INTENSITY8_NV 0x8708 + #define GL_DSDT8_NV 0x8709 + #define GL_DSDT8_MAG8_NV 0x870A + #define GL_DSDT8_MAG8_INTENSITY8_NV 0x870B + #define GL_SIGNED_RGB_UNSIGNED_ALPHA_NV 0x870C + #define GL_SIGNED_RGB8_UNSIGNED_ALPHA8_NV 0x870D +#endif + +#ifndef GL_NV_float_buffer + #define GL_FLOAT_R_NV 0x8880 + #define GL_FLOAT_RG_NV 0x8881 + #define GL_FLOAT_RGB_NV 0x8882 + #define GL_FLOAT_RGBA_NV 0x8883 + #define GL_FLOAT_R16_NV 0x8884 + #define GL_FLOAT_R32_NV 0x8885 + #define GL_FLOAT_RG16_NV 0x8886 + #define GL_FLOAT_RG32_NV 0x8887 + #define GL_FLOAT_RGB16_NV 0x8888 + #define GL_FLOAT_RGB32_NV 0x8889 + #define GL_FLOAT_RGBA16_NV 0x888A + #define GL_FLOAT_RGBA32_NV 0x888B +#endif + +#ifndef GL_ATI_texture_float + #define GL_RGBA_FLOAT32_ATI 0x8814 + #define GL_RGB_FLOAT32_ATI 0x8815 + #define GL_ALPHA_FLOAT32_ATI 0x8816 + #define GL_INTENSITY_FLOAT32_ATI 0x8817 + #define GL_LUMINANCE_FLOAT32_ATI 0x8818 + #define GL_LUMINANCE_ALPHA_FLOAT32_ATI 0x8819 + #define GL_RGBA_FLOAT16_ATI 0x881A + #define GL_RGB_FLOAT16_ATI 0x881B + #define GL_ALPHA_FLOAT16_ATI 0x881C + #define GL_INTENSITY_FLOAT16_ATI 0x881D + #define GL_LUMINANCE_FLOAT16_ATI 0x881E + #define GL_LUMINANCE_ALPHA_FLOAT16_ATI 0x881F +#endif + +#ifndef GL_MIRRORED_REPEAT_IBM + #define GL_MIRRORED_REPEAT_IBM 0x8370 +#endif + +#ifndef GL_CLAMP_TO_EDGE + #define GL_CLAMP_TO_EDGE 0x812F +#endif + +#ifndef GL_CLAMP + #define GL_CLAMP 0x2900 +#endif + +#ifndef GL_CLAMP_TO_BORDER_ARB + #define GL_CLAMP_TO_BORDER_ARB 0x812D +#endif + +#ifndef GL_INTENSITY + // OpenGL ES1 and ES2 doesn't provide GL_INTENSITY + #define GL_INTENSITY 0x8049 +#endif + +#ifndef GL_GENERATE_MIPMAP_SGIS + #define GL_GENERATE_MIPMAP_SGIS 0x8191 + #define GL_GENERATE_MIPMAP_HINT_SGIS 0x8192 +#endif + +#ifndef GL_TEXTURE_3D + #define GL_TEXTURE_3D 0x806F +#endif + +#ifndef GL_TEXTURE_2D_ARRAY_EXT + #define GL_TEXTURE_2D_ARRAY_EXT 0x8C1A + #define GL_TEXTURE_2D_ARRAY_EXT 0x8C1A + #define GL_PROXY_TEXTURE_2D_ARRAY_EXT 0x8C1B + #define GL_TEXTURE_BINDING_2D_ARRAY_EXT 0x8C1D + #define GL_MAX_ARRAY_TEXTURE_LAYERS_EXT 0x88FF + #define GL_COMPARE_REF_DEPTH_TO_TEXTURE_EXT 0x884E + #define GL_SAMPLER_2D_ARRAY_EXT 0x8DC1 + #define GL_SAMPLER_2D_ARRAY_SHADOW_EXT 0x8DC4 + #define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER_EXT 0x8CD4 +#endif + +#ifndef GL_TEXTURE_CUBE_MAP + #define GL_TEXTURE_CUBE_MAP 0x8513 + #define GL_TEXTURE_BINDING_CUBE_MAP 0x8514 + #define GL_TEXTURE_CUBE_MAP_POSITIVE_X 0x8515 + #define GL_TEXTURE_CUBE_MAP_NEGATIVE_X 0x8516 + #define GL_TEXTURE_CUBE_MAP_POSITIVE_Y 0x8517 + #define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y 0x8518 + #define GL_TEXTURE_CUBE_MAP_POSITIVE_Z 0x8519 + #define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z 0x851A + #define GL_PROXY_TEXTURE_CUBE_MAP 0x851B + #define GL_MAX_CUBE_MAP_TEXTURE_SIZE 0x851C +#endif + +#ifndef GL_TEXTURE_BINDING_3D + #define GL_TEXTURE_BINDING_3D 0x806A +#endif + +#ifndef GL_DEPTH_TEXTURE_MODE_ARB + #define GL_DEPTH_TEXTURE_MODE_ARB 0x884B +#endif + +#ifndef GL_TEXTURE_COMPARE_MODE_ARB + #define GL_TEXTURE_COMPARE_MODE_ARB 0x884C +#endif +#ifndef GL_TEXTURE_COMPARE_FUNC_ARB + #define GL_TEXTURE_COMPARE_FUNC_ARB 0x884D +#endif +#ifndef GL_COMPARE_R_TO_TEXTURE_ARB + #define GL_COMPARE_R_TO_TEXTURE_ARB 0x884E +#endif + +#ifndef TEXTURE_COMPARE_FAIL_VALUE_ARB + #define TEXTURE_COMPARE_FAIL_VALUE_ARB 0x80BF +#endif + +#if !defined( GL_MAX_TEXTURE_UNITS ) + #define GL_MAX_TEXTURE_UNITS 0x84E2 +#endif + +#ifndef GL_TEXTURE_DEPTH + #define GL_TEXTURE_DEPTH 0x8071 +#endif + +#ifndef GL_TEXTURE_2D_MULTISAMPLE + #define GL_TEXTURE_2D_MULTISAMPLE 0x9100 +#endif + +// Integer texture extension as in http://www.opengl.org/registry/specs/EXT/texture_integer.txt +#ifndef GL_EXT_texture_integer + #define GL_RGBA32UI_EXT 0x8D70 + #define GL_RGB32UI_EXT 0x8D71 + #define GL_ALPHA32UI_EXT 0x8D72 + #define GL_INTENSITY32UI_EXT 0x8D73 + #define GL_LUMINANCE32UI_EXT 0x8D74 + #define GL_LUMINANCE_ALPHA32UI_EXT 0x8D75 + + #define GL_RGBA16UI_EXT 0x8D76 + #define GL_RGB16UI_EXT 0x8D77 + #define GL_ALPHA16UI_EXT 0x8D78 + #define GL_INTENSITY16UI_EXT 0x8D79 + #define GL_LUMINANCE16UI_EXT 0x8D7A + #define GL_LUMINANCE_ALPHA16UI_EXT 0x8D7B + + #define GL_RGBA8UI_EXT 0x8D7C + #define GL_RGB8UI_EXT 0x8D7D + #define GL_ALPHA8UI_EXT 0x8D7E + #define GL_INTENSITY8UI_EXT 0x8D7F + #define GL_LUMINANCE8UI_EXT 0x8D80 + #define GL_LUMINANCE_ALPHA8UI_EXT 0x8D81 + + #define GL_RGBA32I_EXT 0x8D82 + #define GL_RGB32I_EXT 0x8D83 + #define GL_ALPHA32I_EXT 0x8D84 + #define GL_INTENSITY32I_EXT 0x8D85 + #define GL_LUMINANCE32I_EXT 0x8D86 + #define GL_LUMINANCE_ALPHA32I_EXT 0x8D87 + + #define GL_RGBA16I_EXT 0x8D88 + #define GL_RGB16I_EXT 0x8D89 + #define GL_ALPHA16I_EXT 0x8D8A + #define GL_INTENSITY16I_EXT 0x8D8B + #define GL_LUMINANCE16I_EXT 0x8D8C + #define GL_LUMINANCE_ALPHA16I_EXT 0x8D8D + + #define GL_RGBA8I_EXT 0x8D8E + #define GL_RGB8I_EXT 0x8D8F + #define GL_ALPHA8I_EXT 0x8D90 + #define GL_INTENSITY8I_EXT 0x8D91 + #define GL_LUMINANCE8I_EXT 0x8D92 + #define GL_LUMINANCE_ALPHA8I_EXT 0x8D93 + + #define GL_RED_INTEGER_EXT 0x8D94 + #define GL_GREEN_INTEGER_EXT 0x8D95 + #define GL_BLUE_INTEGER_EXT 0x8D96 + #define GL_ALPHA_INTEGER_EXT 0x8D97 + #define GL_RGB_INTEGER_EXT 0x8D98 + #define GL_RGBA_INTEGER_EXT 0x8D99 + #define GL_BGR_INTEGER_EXT 0x8D9A + #define GL_BGRA_INTEGER_EXT 0x8D9B + #define GL_LUMINANCE_INTEGER_EXT 0x8D9C + #define GL_LUMINANCE_ALPHA_INTEGER_EXT 0x8D9D + + #define GL_RGBA_INTEGER_MODE_EXT 0x8D9E +#endif + +#ifndef GL_VERSION_1_1 +#define GL_R3_G3_B2 0x2A10 +#define GL_RGB4 0x804F +#define GL_RGB5 0x8050 +#define GL_RGB8 0x8051 +#define GL_RGB10 0x8052 +#define GL_RGB12 0x8053 +#define GL_RGB16 0x8054 +#define GL_RGBA2 0x8055 +#define GL_RGBA4 0x8056 +#define GL_RGB5_A1 0x8057 +#define GL_RGBA8 0x8058 +#define GL_RGB10_A2 0x8059 +#define GL_RGBA12 0x805A +#define GL_RGBA16 0x805B +#define GL_BGR_EXT 0x80E0 +#define GL_BGRA_EXT 0x80E1 +#endif + +#ifndef GL_ARB_texture_rg + #define GL_RG 0x8227 + #define GL_RG_INTEGER 0x8228 + #define GL_R8 0x8229 + #define GL_R16 0x822A + #define GL_RG8 0x822B + #define GL_RG16 0x822C + #define GL_R16F 0x822D + #define GL_R32F 0x822E + #define GL_RG16F 0x822F + #define GL_RG32F 0x8230 + #define GL_R8I 0x8231 + #define GL_R8UI 0x8232 + #define GL_R16I 0x8233 + #define GL_R16UI 0x8234 + #define GL_R32I 0x8235 + #define GL_R32UI 0x8236 + #define GL_RG8I 0x8237 + #define GL_RG8UI 0x8238 + #define GL_RG16I 0x8239 + #define GL_RG16UI 0x823A + #define GL_RG32I 0x823B + #define GL_RG32UI 0x823C +#endif + +#ifndef GL_ARB_shader_image_load_store + #define GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT 0x00000001 + #define GL_ELEMENT_ARRAY_BARRIER_BIT 0x00000002 + #define GL_UNIFORM_BARRIER_BIT 0x00000004 + #define GL_TEXTURE_FETCH_BARRIER_BIT 0x00000008 + #define GL_SHADER_IMAGE_ACCESS_BARRIER_BIT 0x00000020 + #define GL_COMMAND_BARRIER_BIT 0x00000040 + #define GL_PIXEL_BUFFER_BARRIER_BIT 0x00000080 + #define GL_TEXTURE_UPDATE_BARRIER_BIT 0x00000100 + #define GL_BUFFER_UPDATE_BARRIER_BIT 0x00000200 + #define GL_FRAMEBUFFER_BARRIER_BIT 0x00000400 + #define GL_TRANSFORM_FEEDBACK_BARRIER_BIT 0x00000800 + #define GL_ATOMIC_COUNTER_BARRIER_BIT 0x00001000 + #define GL_ALL_BARRIER_BITS 0xFFFFFFFF + #define GL_MAX_IMAGE_UNITS 0x8F38 + #define GL_MAX_COMBINED_IMAGE_UNITS_AND_FRAGMENT_OUTPUTS 0x8F39 + #define GL_IMAGE_BINDING_NAME 0x8F3A + #define GL_IMAGE_BINDING_LEVEL 0x8F3B + #define GL_IMAGE_BINDING_LAYERED 0x8F3C + #define GL_IMAGE_BINDING_LAYER 0x8F3D + #define GL_IMAGE_BINDING_ACCESS 0x8F3E + #define GL_IMAGE_1D 0x904C + #define GL_IMAGE_2D 0x904D + #define GL_IMAGE_3D 0x904E + #define GL_IMAGE_2D_RECT 0x904F + #define GL_IMAGE_CUBE 0x9050 + #define GL_IMAGE_BUFFER 0x9051 + #define GL_IMAGE_1D_ARRAY 0x9052 + #define GL_IMAGE_2D_ARRAY 0x9053 + #define GL_IMAGE_CUBE_MAP_ARRAY 0x9054 + #define GL_IMAGE_2D_MULTISAMPLE 0x9055 + #define GL_IMAGE_2D_MULTISAMPLE_ARRAY 0x9056 + #define GL_INT_IMAGE_1D 0x9057 + #define GL_INT_IMAGE_2D 0x9058 + #define GL_INT_IMAGE_3D 0x9059 + #define GL_INT_IMAGE_2D_RECT 0x905A + #define GL_INT_IMAGE_CUBE 0x905B + #define GL_INT_IMAGE_BUFFER 0x905C + #define GL_INT_IMAGE_1D_ARRAY 0x905D + #define GL_INT_IMAGE_2D_ARRAY 0x905E + #define GL_INT_IMAGE_CUBE_MAP_ARRAY 0x905F + #define GL_INT_IMAGE_2D_MULTISAMPLE 0x9060 + #define GL_INT_IMAGE_2D_MULTISAMPLE_ARRAY 0x9061 + #define GL_UNSIGNED_INT_IMAGE_1D 0x9062 + #define GL_UNSIGNED_INT_IMAGE_2D 0x9063 + #define GL_UNSIGNED_INT_IMAGE_3D 0x9064 + #define GL_UNSIGNED_INT_IMAGE_2D_RECT 0x9065 + #define GL_UNSIGNED_INT_IMAGE_CUBE 0x9066 + #define GL_UNSIGNED_INT_IMAGE_BUFFER 0x9067 + #define GL_UNSIGNED_INT_IMAGE_1D_ARRAY 0x9068 + #define GL_UNSIGNED_INT_IMAGE_2D_ARRAY 0x9069 + #define GL_UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY 0x906A + #define GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE 0x906B + #define GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE_ARRAY 0x906C + #define GL_MAX_IMAGE_SAMPLES 0x906D + #define GL_IMAGE_BINDING_FORMAT 0x906E + #define GL_IMAGE_FORMAT_COMPATIBILITY_TYPE 0x90C7 + #define GL_IMAGE_FORMAT_COMPATIBILITY_BY_SIZE 0x90C8 + #define GL_IMAGE_FORMAT_COMPATIBILITY_BY_CLASS 0x90C9 + #define GL_MAX_VERTEX_IMAGE_UNIFORMS 0x90CA + #define GL_MAX_TESS_CONTROL_IMAGE_UNIFORMS 0x90CB + #define GL_MAX_TESS_EVALUATION_IMAGE_UNIFORMS 0x90CC + #define GL_MAX_GEOMETRY_IMAGE_UNIFORMS 0x90CD + #define GL_MAX_FRAGMENT_IMAGE_UNIFORMS 0x90CE + #define GL_MAX_COMBINED_IMAGE_UNIFORMS 0x90CF +#endif + +namespace osg { + + +/** Texture pure virtual base class that encapsulates OpenGL texture + * functionality common to the various types of OSG textures. +*/ +class OSG_EXPORT Texture : public osg::StateAttribute +{ + + public : + + Texture(); + + /** Copy constructor using CopyOp to manage deep vs shallow copy. */ + Texture(const Texture& text,const CopyOp& copyop=CopyOp::SHALLOW_COPY); + + virtual osg::Object* cloneType() const = 0; + virtual osg::Object* clone(const CopyOp& copyop) const = 0; + virtual bool isSameKindAs(const osg::Object* obj) const { return dynamic_cast(obj)!=NULL; } + virtual const char* libraryName() const { return "osg"; } + virtual const char* className() const { return "Texture"; } + + /** Fast alternative to dynamic_cast<> for determining if state attribute is a Texture.*/ + virtual Texture* asTexture() { return this; } + + /** Fast alternative to dynamic_cast<> for determining if state attribute is a Texture.*/ + virtual const Texture* asTexture() const { return this; } + + virtual Type getType() const { return TEXTURE; } + + virtual bool isTextureAttribute() const { return true; } + + virtual GLenum getTextureTarget() const = 0; + + virtual bool getModeUsage(StateAttribute::ModeUsage& usage) const + { + usage.usesTextureMode(getTextureTarget()); + return true; + } + + virtual int getTextureWidth() const { return 0; } + virtual int getTextureHeight() const { return 0; } + virtual int getTextureDepth() const { return 0; } + + enum WrapParameter { + WRAP_S, + WRAP_T, + WRAP_R + }; + + enum WrapMode { + CLAMP = GL_CLAMP, + CLAMP_TO_EDGE = GL_CLAMP_TO_EDGE, + CLAMP_TO_BORDER = GL_CLAMP_TO_BORDER_ARB, + REPEAT = GL_REPEAT, + MIRROR = GL_MIRRORED_REPEAT_IBM + }; + + /** Sets the texture wrap mode. */ + void setWrap(WrapParameter which, WrapMode wrap); + /** Gets the texture wrap mode. */ + WrapMode getWrap(WrapParameter which) const; + + + /** Sets the border color. Only used when wrap mode is CLAMP_TO_BORDER. + * The border color will be casted to the appropriate type to match the + * internal pixel format of the texture. */ + void setBorderColor(const Vec4d& color) { _borderColor = color; dirtyTextureParameters(); } + + /** Gets the border color. */ + const Vec4d& getBorderColor() const { return _borderColor; } + + /** Sets the border width. */ + void setBorderWidth(GLint width) { _borderWidth = width; dirtyTextureParameters(); } + + GLint getBorderWidth() const { return _borderWidth; } + + enum FilterParameter { + MIN_FILTER, + MAG_FILTER + }; + + enum FilterMode { + LINEAR = GL_LINEAR, + LINEAR_MIPMAP_LINEAR = GL_LINEAR_MIPMAP_LINEAR, + LINEAR_MIPMAP_NEAREST = GL_LINEAR_MIPMAP_NEAREST, + NEAREST = GL_NEAREST, + NEAREST_MIPMAP_LINEAR = GL_NEAREST_MIPMAP_LINEAR, + NEAREST_MIPMAP_NEAREST = GL_NEAREST_MIPMAP_NEAREST + }; + + /** Sets the texture filter mode. */ + void setFilter(FilterParameter which, FilterMode filter); + + /** Gets the texture filter mode. */ + FilterMode getFilter(FilterParameter which) const; + + /** Sets the maximum anisotropy value, default value is 1.0 for no + * anisotropic filtering. If hardware does not support anisotropic + * filtering, use normal filtering (equivalent to a max anisotropy + * value of 1.0. Valid range is 1.0f upwards. The maximum value + * depends on the graphics system. */ + void setMaxAnisotropy(float anis); + + /** Gets the maximum anisotropy value. */ + inline float getMaxAnisotropy() const { return _maxAnisotropy; } + + /** Configure the source of texture swizzling for all channels */ + inline void setSwizzle(const Vec4i& swizzle) { _swizzle = swizzle; dirtyTextureParameters(); }; + + /** Gets the source of texture swizzling for all channels */ + inline const Vec4i& getSwizzle() const { return _swizzle; } + + /** Sets the hardware mipmap generation hint. If enabled, it will + * only be used if supported in the graphics system. */ + inline void setUseHardwareMipMapGeneration(bool useHardwareMipMapGeneration) { _useHardwareMipMapGeneration = useHardwareMipMapGeneration; } + + /** Gets the hardware mipmap generation hint. */ + inline bool getUseHardwareMipMapGeneration() const { return _useHardwareMipMapGeneration; } + + /** Sets whether or not the apply() function will unreference the image + * data. If enabled, and the image data is only referenced by this + * Texture, apply() will delete the image data. */ + inline void setUnRefImageDataAfterApply(bool flag) { _unrefImageDataAfterApply = flag; } + + /** Gets whether or not apply() unreferences image data. */ + inline bool getUnRefImageDataAfterApply() const { return _unrefImageDataAfterApply; } + + /** Sets whether to use client storage for the texture, if supported + * by the graphics system. Note: If enabled, and the graphics system + * supports it, the osg::Image(s) associated with this texture cannot + * be deleted, so the UnRefImageDataAfterApply flag would be ignored. */ + inline void setClientStorageHint(bool flag) { _clientStorageHint = flag; } + + /** Gets whether to use client storage for the texture. */ + inline bool getClientStorageHint() const { return _clientStorageHint; } + + /** Sets whether to force the texture to resize images that have dimensions + * that are not a power of two. If enabled, NPOT images will be resized, + * whether or not NPOT textures are supported by the hardware. If disabled, + * NPOT images will not be resized if supported by hardware. */ + inline void setResizeNonPowerOfTwoHint(bool flag) { _resizeNonPowerOfTwoHint = flag; } + + /** Gets whether texture will force non power to two images to be resized. */ + inline bool getResizeNonPowerOfTwoHint() const { return _resizeNonPowerOfTwoHint; } + + enum InternalFormatMode { + USE_IMAGE_DATA_FORMAT, + USE_USER_DEFINED_FORMAT, + USE_ARB_COMPRESSION, + USE_S3TC_DXT1_COMPRESSION, + USE_S3TC_DXT3_COMPRESSION, + USE_S3TC_DXT5_COMPRESSION, + USE_PVRTC_2BPP_COMPRESSION, + USE_PVRTC_4BPP_COMPRESSION, + USE_ETC_COMPRESSION, + USE_RGTC1_COMPRESSION, + USE_RGTC2_COMPRESSION, + USE_S3TC_DXT1c_COMPRESSION, + USE_S3TC_DXT1a_COMPRESSION + }; + + /** Sets the internal texture format mode. Note: If the texture format is + * USE_IMAGE_DATA_FORMAT, USE_ARB_COMPRESSION, or USE_S3TC_COMPRESSION, + * the internal format mode is set automatically and will overwrite the + * previous _internalFormat. */ + inline void setInternalFormatMode(InternalFormatMode mode) { _internalFormatMode = mode; } + + /** Gets the internal texture format mode. */ + inline InternalFormatMode getInternalFormatMode() const { return _internalFormatMode; } + + /** Sets the internal texture format. Implicitly sets the + * internalFormatMode to USE_USER_DEFINED_FORMAT. + * The corresponding internal format type will be computed. */ + inline void setInternalFormat(GLint internalFormat) + { + _internalFormatMode = USE_USER_DEFINED_FORMAT; + _internalFormat = internalFormat; + computeInternalFormatType(); + } + + + /** Gets the internal texture format. */ + inline GLint getInternalFormat() const { if (_internalFormat==0) computeInternalFormat(); return _internalFormat; } + + /** Return true if the internal format is one of the compressed formats.*/ + bool isCompressedInternalFormat() const; + + /** Sets the external source image format, used as a fallback when no osg::Image is attached to provide the source image format. */ + inline void setSourceFormat(GLenum sourceFormat) { _sourceFormat = sourceFormat; } + + /** Gets the external source image format. */ + inline GLenum getSourceFormat() const { return _sourceFormat; } + + /** Sets the external source data type, used as a fallback when no osg::Image is attached to provide the source image format.*/ + inline void setSourceType(GLenum sourceType) { _sourceType = sourceType; } + + /** Gets the external source data type.*/ + inline GLenum getSourceType() const { return _sourceType; } + + /** Texture type determined by the internal texture format */ + enum InternalFormatType{ + + //! default OpenGL format (clamped values to [0,1) or [0,255]) + NORMALIZED = 0x0, + + //! float values, Shader Model 3.0 (see ARB_texture_float) + FLOAT = 0x1, + + //! Signed integer values (see EXT_texture_integer) + SIGNED_INTEGER = 0x2, + + //! Unsigned integer value (see EXT_texture_integer) + UNSIGNED_INTEGER = 0x4 + }; + + /** Get the internal texture format type. */ + inline InternalFormatType getInternalFormatType() const { return _internalFormatType; } + + class TextureObject; + + /** Returns a pointer to the TextureObject for the current context. */ + inline TextureObject* getTextureObject(unsigned int contextID) const + { + return _textureObjectBuffer[contextID].get(); + } + + inline void setTextureObject(unsigned int contextID, TextureObject* to) + { + _textureObjectBuffer[contextID] = to; + } + + /** Forces a recompile on next apply() of associated OpenGL texture + * objects. */ + void dirtyTextureObject(); + + /** Returns true if the texture objects for all the required graphics + * contexts are loaded. */ + bool areAllTextureObjectsLoaded() const; + + + /** Gets the dirty flag for the current contextID. */ + inline unsigned int& getTextureParameterDirty(unsigned int contextID) const + { + return _texParametersDirtyList[contextID]; + } + + + /** Force a reset on next apply() of associated OpenGL texture + * parameters. */ + void dirtyTextureParameters(); + + /** Force a manual allocation of the mipmap levels on the next apply() call. + * User is responsible for filling the mipmap levels with valid data. + * The OpenGL's glGenerateMipmapEXT function is used to generate the mipmap levels. + * If glGenerateMipmapEXT is not supported or texture's internal format is not supported + * by the glGenerateMipmapEXT, then empty mipmap levels will + * be allocated manually. The mipmap levels are also allocated if a non-mipmapped + * min filter is used. */ + void allocateMipmapLevels(); + + /** Encapsulates texture image load/store attributes */ + struct ImageAttachment + { + GLuint unit; + GLint level; + GLboolean layered; + GLint layer; + GLenum access; + GLenum format; + + ImageAttachment() + : unit(0), level(0), layered(GL_FALSE), layer(0), access(0), format(0) {} + }; + + /** Type of access that will be performed on the texture image. */ + enum ImageAccess + { + NOT_USED = 0, + READ_ONLY = GL_READ_ONLY_ARB, + WRITE_ONLY = GL_WRITE_ONLY_ARB, + READ_WRITE = GL_READ_WRITE_ARB + }; + + /** Bind texture to an image unit (available only if GL version is 4.2 or greater) + * The format parameter for the image unit need not exactly match the texture internal format, + * but if it is set to 0, the texture internal format will be used. + * See http://www.opengl.org/registry/specs/ARB/shader_image_load_store.txt */ + void bindToImageUnit(unsigned int unit, GLenum access, GLenum format=0, int level=0, bool layered=false, int layer=0); + + ImageAttachment& getImageAttachment() { return _imageAttachment; } + const ImageAttachment& getImageAttachment() const { return _imageAttachment; } + + /** Sets GL_TEXTURE_COMPARE_MODE_ARB to GL_COMPARE_R_TO_TEXTURE_ARB + * See http://oss.sgi.com/projects/ogl-sample/registry/ARB/shadow.txt. */ + void setShadowComparison(bool flag) { _use_shadow_comparison = flag; } + bool getShadowComparison() const { return _use_shadow_comparison; } + + enum ShadowCompareFunc { + NEVER = GL_NEVER, + LESS = GL_LESS, + EQUAL = GL_EQUAL, + LEQUAL = GL_LEQUAL, + GREATER = GL_GREATER, + NOTEQUAL = GL_NOTEQUAL, + GEQUAL = GL_GEQUAL, + ALWAYS = GL_ALWAYS + }; + + /** Sets shadow texture comparison function. */ + void setShadowCompareFunc(ShadowCompareFunc func) { _shadow_compare_func = func; } + ShadowCompareFunc getShadowCompareFunc() const { return _shadow_compare_func; } + + enum ShadowTextureMode { + LUMINANCE = GL_LUMINANCE, + INTENSITY = GL_INTENSITY, + ALPHA = GL_ALPHA + }; + + /** Sets shadow texture mode after comparison. */ + void setShadowTextureMode(ShadowTextureMode mode) { _shadow_texture_mode = mode; } + ShadowTextureMode getShadowTextureMode() const { return _shadow_texture_mode; } + + /** Sets the TEXTURE_COMPARE_FAIL_VALUE_ARB texture parameter. See + * http://oss.sgi.com/projects/ogl-sample/registry/ARB/shadow_ambient.txt. */ + void setShadowAmbient(float shadow_ambient) { _shadow_ambient = shadow_ambient; } + float getShadowAmbient() const { return _shadow_ambient; } + + + /** Sets the texture image for the specified face. */ + virtual void setImage(unsigned int face, Image* image) = 0; + + /** Gets the texture image for the specified face. */ + virtual Image* getImage(unsigned int face) = 0; + + /** Gets the const texture image for specified face. */ + virtual const Image* getImage(unsigned int face) const = 0; + + /** Gets the number of images that can be assigned to this Texture. */ + virtual unsigned int getNumImages() const = 0; + + + /** Set the PBuffer graphics context to read from when using PBuffers for RenderToTexture.*/ + void setReadPBuffer(GraphicsContext* context) { _readPBuffer = context; } + + /** Get the PBuffer graphics context to read from when using PBuffers for RenderToTexture.*/ + GraphicsContext* getReadPBuffer() { return _readPBuffer.get(); } + + /** Get the const PBuffer graphics context to read from when using PBuffers for RenderToTexture.*/ + const GraphicsContext* getReadPBuffer() const { return _readPBuffer.get(); } + + /** Texture is a pure virtual base class, apply must be overridden. */ + virtual void apply(State& state) const = 0; + + /** Calls apply(state) to compile the texture. */ + virtual void compileGLObjects(State& state) const; + + /** Resize any per context GLObject buffers to specified size. */ + virtual void resizeGLObjectBuffers(unsigned int maxSize); + + /** If State is non-zero, this function releases OpenGL objects for + * the specified graphics context. Otherwise, releases OpenGL objects + * for all graphics contexts. */ + virtual void releaseGLObjects(State* state=0) const; + + /** Encapsulates queries of extension availability, obtains extension + * function pointers, and provides convenience wrappers for + * calling extension functions. */ + class OSG_EXPORT Extensions : public osg::Referenced + { + public: + Extensions(unsigned int contextID); + + void setMultiTexturingSupported(bool flag) { _isMultiTexturingSupported=flag; } + bool isMultiTexturingSupported() const { return _isMultiTexturingSupported; } + + void setTextureFilterAnisotropicSupported(bool flag) { _isTextureFilterAnisotropicSupported=flag; } + bool isTextureFilterAnisotropicSupported() const { return _isTextureFilterAnisotropicSupported; } + + void setTextureSwizzleSupported(bool flag) { _isTextureSwizzleSupported=flag; } + bool isTextureSwizzleSupported() const { return _isTextureSwizzleSupported; } + + void setTextureCompressionARBSupported(bool flag) { _isTextureCompressionARBSupported=flag; } + bool isTextureCompressionARBSupported() const { return _isTextureCompressionARBSupported; } + + void setTextureCompressionS3TCSupported(bool flag) { _isTextureCompressionS3TCSupported=flag; } + bool isTextureCompressionS3TCSupported() const { return _isTextureCompressionS3TCSupported; } + + void setTextureCompressionPVRTC2BPPSupported(bool flag) { _isTextureCompressionPVRTC2BPPSupported=flag; } + bool isTextureCompressionPVRTC2BPPSupported() const { return _isTextureCompressionPVRTC2BPPSupported; } + + void setTextureCompressionPVRTC4BPPSupported(bool flag) { _isTextureCompressionPVRTC4BPPSupported=flag; } + bool isTextureCompressionPVRTC4BPPSupported() const { return _isTextureCompressionPVRTC4BPPSupported; } + + void setTextureCompressionETCSupported(bool flag) { _isTextureCompressionETCSupported=flag; } + bool isTextureCompressionETCSupported() const { return _isTextureCompressionETCSupported; } + + void setTextureCompressionRGTCSupported(bool flag) { _isTextureCompressionRGTCSupported=flag; } + bool isTextureCompressionRGTCSupported() const { return _isTextureCompressionRGTCSupported; } + + void setTextureCompressionPVRTCSupported(bool flag) { _isTextureCompressionPVRTCSupported=flag; } + bool isTextureCompressionPVRTCSupported() const { return _isTextureCompressionPVRTCSupported; } + + void setTextureMirroredRepeatSupported(bool flag) { _isTextureMirroredRepeatSupported=flag; } + bool isTextureMirroredRepeatSupported() const { return _isTextureMirroredRepeatSupported; } + + void setTextureEdgeClampSupported(bool flag) { _isTextureEdgeClampSupported=flag; } + bool isTextureEdgeClampSupported() const { return _isTextureEdgeClampSupported; } + + void setTextureBorderClampSupported(bool flag) { _isTextureBorderClampSupported=flag; } + bool isTextureBorderClampSupported() const { return _isTextureBorderClampSupported; } + + void setGenerateMipMapSupported(bool flag) { _isGenerateMipMapSupported=flag; } + bool isGenerateMipMapSupported() const { return _isGenerateMipMapSupported; } + + void setPreferGenerateMipmapSGISForPowerOfTwo(bool flag) { _preferGenerateMipmapSGISForPowerOfTwo = flag; } + bool getPreferGenerateMipmapSGISForPowerOfTwo() const { return _preferGenerateMipmapSGISForPowerOfTwo; } + + void setTextureMultisampledSupported(bool flag) { _isTextureMultisampledSupported=flag; } + bool isTextureMultisampledSupported() const { return _isTextureMultisampledSupported; } + + void setShadowSupported(bool flag) { _isShadowSupported = flag; } + bool isShadowSupported() const { return _isShadowSupported; } + + void setShadowAmbientSupported(bool flag) { _isShadowAmbientSupported = flag; } + bool isShadowAmbientSupported() const { return _isShadowAmbientSupported; } + + void setTextureMaxLevelSupported(bool flag) { _isTextureMaxLevelSupported = flag; } + bool isTextureMaxLevelSupported() const { return _isTextureMaxLevelSupported; } + + void setMaxTextureSize(GLint maxsize) { _maxTextureSize=maxsize; } + GLint maxTextureSize() const { return _maxTextureSize; } + + void setNumTextureUnits(GLint nunits ) { _numTextureUnits=nunits; } + GLint numTextureUnits() const { return _numTextureUnits; } + + bool isCompressedTexImage2DSupported() const { return _glCompressedTexImage2D!=0; } + bool isCompressedTexSubImage2DSupported() const { return _glCompressedTexSubImage2D!=0; } + + bool isClientStorageSupported() const { return _isClientStorageSupported; } + + bool isNonPowerOfTwoTextureSupported(GLenum filter) const + { + return (filter==GL_LINEAR || filter==GL_NEAREST) ? + _isNonPowerOfTwoTextureNonMipMappedSupported : + _isNonPowerOfTwoTextureMipMappedSupported; + } + + void setTextureIntegerSupported(bool flag) { _isTextureIntegerEXTSupported=flag; } + bool isTextureIntegerSupported() const { return _isTextureIntegerEXTSupported; } + + bool isBindImageTextureSupported() const { return _glBindImageTexture!=0; } + + void glCompressedTexImage2D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const GLvoid *data) const + { + _glCompressedTexImage2D(target, level, internalformat, width, height, border, imageSize, data); + } + + void glCompressedTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const GLvoid *data) const + { + _glCompressedTexSubImage2D(target, level, xoffset, yoffset, width, height, format, imageSize, data); + } + + void glGetCompressedTexImage(GLenum target, GLint level, GLvoid *data) const + { + _glGetCompressedTexImage(target, level, data); + } + + void glTexImage2DMultisample(GLenum target, GLsizei samples, GLint internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations) const + { + _glTexImage2DMultisample(target, samples, internalformat, width, height, fixedsamplelocations); + } + + void glTexParameterIiv(GLenum target, GLenum pname, const GLint* data) const + { + _glTexParameterIiv(target, pname, data); + } + + void glTexParameterIuiv(GLenum target, GLenum pname, const GLuint* data) const + { + _glTexParameterIuiv(target, pname, data); + } + + // ARB_shader_image_load_store + void glBindImageTexture(GLuint unit, GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum access, GLenum format) const + { + _glBindImageTexture(unit, texture, level, layered, layer, access, format); + } + + protected: + + ~Extensions() {} + + typedef void (GL_APIENTRY * CompressedTexImage2DArbProc) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const GLvoid *data); + typedef void (GL_APIENTRY * CompressedTexSubImage2DArbProc) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const GLvoid *data); + typedef void (GL_APIENTRY * GetCompressedTexImageArbProc) (GLenum target, GLint level, GLvoid *data); + typedef void (GL_APIENTRY * TexImage2DMultisample)(GLenum target, GLsizei samples, GLint internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations); + typedef void (GL_APIENTRY * TexParameterIivProc)(GLenum target, GLenum pname, const GLint* data); + typedef void (GL_APIENTRY * TexParameterIuivProc)(GLenum target, GLenum pname, const GLuint* data); + typedef void (GL_APIENTRY * BindImageTextureProc)( GLuint unit, GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum access, GLenum format ); + + CompressedTexImage2DArbProc _glCompressedTexImage2D; + CompressedTexSubImage2DArbProc _glCompressedTexSubImage2D; + GetCompressedTexImageArbProc _glGetCompressedTexImage; + TexImage2DMultisample _glTexImage2DMultisample; + TexParameterIivProc _glTexParameterIiv; + TexParameterIuivProc _glTexParameterIuiv; + + // ARB_shader_image_load_store + BindImageTextureProc _glBindImageTexture; + + bool _isMultiTexturingSupported; + bool _isTextureFilterAnisotropicSupported; + bool _isTextureSwizzleSupported; + bool _isTextureCompressionARBSupported; + bool _isTextureCompressionS3TCSupported; + bool _isTextureCompressionPVRTC2BPPSupported; + bool _isTextureCompressionPVRTC4BPPSupported; + bool _isTextureCompressionETCSupported; + bool _isTextureCompressionRGTCSupported; + bool _isTextureCompressionPVRTCSupported; + bool _isTextureMirroredRepeatSupported; + bool _isTextureEdgeClampSupported; + bool _isTextureBorderClampSupported; + bool _isGenerateMipMapSupported; + bool _preferGenerateMipmapSGISForPowerOfTwo; + bool _isTextureMultisampledSupported; + bool _isShadowSupported; + bool _isShadowAmbientSupported; + bool _isClientStorageSupported; + bool _isNonPowerOfTwoTextureMipMappedSupported; + bool _isNonPowerOfTwoTextureNonMipMappedSupported; + bool _isTextureIntegerEXTSupported; + bool _isTextureMaxLevelSupported; + + GLint _maxTextureSize; + GLint _numTextureUnits; + }; + + /** Gets the extension for the specified context. Creates the + * Extensions object for that context if it doesn't exist. + * Returns NULL if the Extensions object for the context doesn't + * exist and the createIfNotInitalized flag is false. */ + static Extensions* getExtensions(unsigned int contextID,bool createIfNotInitalized); + + /** Overrides Extensions objects across graphics contexts. Typically + * used to ensure the same lowest common denominator of extensions + * on systems with different graphics pipes. */ + static void setExtensions(unsigned int contextID,Extensions* extensions); + + /** Determine whether the given internalFormat is a compressed + * image format. */ + static bool isCompressedInternalFormat(GLint internalFormat); + + /** Determine the size of a compressed image, given the internalFormat, + * the width, the height, and the depth of the image. The block size + * and the size are output parameters. */ + static void getCompressedSize(GLenum internalFormat, GLint width, GLint height, GLint depth, GLint& blockSize, GLint& size); + + + /** Helper method. Creates the texture, but doesn't set or use a + * texture binding. Note: Don't call this method directly unless + * you're implementing a subload callback. */ + void applyTexImage2D_load(State& state, GLenum target, const Image* image, GLsizei width, GLsizei height,GLsizei numMipmapLevels) const; + + /** Helper method. Subloads images into the texture, but doesn't set + * or use a texture binding. Note: Don't call this method directly + * unless you're implementing a subload callback. */ + void applyTexImage2D_subload(State& state, GLenum target, const Image* image, GLsizei width, GLsizei height, GLint inInternalFormat, GLsizei numMipmapLevels) const; + + + /** Returned by mipmapBeforeTexImage() to indicate what + * mipmapAfterTexImage() should do */ + enum GenerateMipmapMode + { + GENERATE_MIPMAP_NONE, + GENERATE_MIPMAP, + GENERATE_MIPMAP_TEX_PARAMETER + }; + + protected : + + virtual ~Texture(); + + virtual void computeInternalFormat() const = 0; + + /** Computes the internal format from Image parameters. */ + void computeInternalFormatWithImage(const osg::Image& image) const; + + /** Computes the texture dimension for the given Image. */ + void computeRequiredTextureDimensions(State& state, const osg::Image& image,GLsizei& width, GLsizei& height,GLsizei& numMipmapLevels) const; + + /** Computes the internal format type. */ + void computeInternalFormatType() const; + + /** Helper method. Sets texture parameters. */ + void applyTexParameters(GLenum target, State& state) const; + + /** Returns true if _useHardwareMipMapGeneration is true and either + * glGenerateMipmapEXT() or GL_GENERATE_MIPMAP_SGIS are supported. */ + bool isHardwareMipmapGenerationEnabled(const State& state) const; + + /** Returns true if the associated Image should be released and it's safe to do so. */ + bool isSafeToUnrefImageData(const State& state) const { + return (_unrefImageDataAfterApply && state.getMaxTexturePoolSize()==0 && areAllTextureObjectsLoaded()); + } + + /** Helper methods to be called before and after calling + * gl[Compressed][Copy]Tex[Sub]Image2D to handle generating mipmaps. */ + GenerateMipmapMode mipmapBeforeTexImage(const State& state, bool hardwareMipmapOn) const; + void mipmapAfterTexImage(State& state, GenerateMipmapMode beforeResult) const; + + /** Helper method to generate mipmap levels by calling of glGenerateMipmapEXT. + * If it is not supported, then call the virtual allocateMipmap() method */ + void generateMipmap(State& state) const; + + /** Allocate mipmap levels of the texture by subsequent calling of glTexImage* function. */ + virtual void allocateMipmap(State& state) const = 0; + + /** Returns -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs. */ + int compareTexture(const Texture& rhs) const; + + /** Returns -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs. */ + int compareTextureObjects(const Texture& rhs) const; + + typedef buffered_value TexParameterDirtyList; + mutable TexParameterDirtyList _texParametersDirtyList; + mutable TexParameterDirtyList _texMipmapGenerationDirtyList; + + WrapMode _wrap_s; + WrapMode _wrap_t; + WrapMode _wrap_r; + + FilterMode _min_filter; + FilterMode _mag_filter; + float _maxAnisotropy; + Vec4i _swizzle; + bool _useHardwareMipMapGeneration; + bool _unrefImageDataAfterApply; + bool _clientStorageHint; + bool _resizeNonPowerOfTwoHint; + + Vec4d _borderColor; + GLint _borderWidth; + + InternalFormatMode _internalFormatMode; + mutable InternalFormatType _internalFormatType; + mutable GLint _internalFormat; + mutable GLenum _sourceFormat; + mutable GLenum _sourceType; + + bool _use_shadow_comparison; + ShadowCompareFunc _shadow_compare_func; + ShadowTextureMode _shadow_texture_mode; + float _shadow_ambient; + + ImageAttachment _imageAttachment; + + public: + + struct OSG_EXPORT TextureProfile + { + inline TextureProfile(GLenum target): + _target(target), + _numMipmapLevels(0), + _internalFormat(0), + _width(0), + _height(0), + _depth(0), + _border(0), + _size(0) {} + + inline TextureProfile(GLenum target, + GLint numMipmapLevels, + GLenum internalFormat, + GLsizei width, + GLsizei height, + GLsizei depth, + GLint border): + _target(target), + _numMipmapLevels(numMipmapLevels), + _internalFormat(internalFormat), + _width(width), + _height(height), + _depth(depth), + _border(border), + _size(0) { computeSize(); } + + + #define LESSTHAN(A,B) if (A > TextureObjectList; + + class OSG_EXPORT TextureObjectSet : public Referenced + { + public: + TextureObjectSet(TextureObjectManager* parent, const TextureProfile& profile); + + const TextureProfile& getProfile() const { return _profile; } + + void handlePendingOrphandedTextureObjects(); + + void deleteAllTextureObjects(); + void discardAllTextureObjects(); + void flushAllDeletedTextureObjects(); + void discardAllDeletedTextureObjects(); + void flushDeletedTextureObjects(double currentTime, double& availableTime); + + TextureObject* takeFromOrphans(Texture* texture); + TextureObject* takeOrGenerate(Texture* texture); + void moveToBack(TextureObject* to); + void addToBack(TextureObject* to); + void orphan(TextureObject* to); + void remove(TextureObject* to); + void moveToSet(TextureObject* to, TextureObjectSet* set); + + unsigned int size() const { return _profile._size * _numOfTextureObjects; } + + bool makeSpace(unsigned int& size); + + bool checkConsistency() const; + + TextureObjectManager* getParent() { return _parent; } + + unsigned int computeNumTextureObjectsInList() const; + unsigned int getNumOfTextureObjects() const { return _numOfTextureObjects; } + unsigned int getNumOrphans() const { return static_cast(_orphanedTextureObjects.size()); } + unsigned int getNumPendingOrphans() const { return static_cast(_pendingOrphanedTextureObjects.size()); } + + protected: + + virtual ~TextureObjectSet(); + + OpenThreads::Mutex _mutex; + + TextureObjectManager* _parent; + unsigned int _contextID; + TextureProfile _profile; + unsigned int _numOfTextureObjects; + TextureObjectList _orphanedTextureObjects; + TextureObjectList _pendingOrphanedTextureObjects; + + TextureObject* _head; + TextureObject* _tail; + + }; + + class OSG_EXPORT TextureObjectManager : public osg::Referenced + { + public: + TextureObjectManager(unsigned int contextID); + + unsigned int getContextID() const { return _contextID; } + + + + void setNumberActiveTextureObjects(unsigned int size) { _numActiveTextureObjects = size; } + unsigned int& getNumberActiveTextureObjects() { return _numActiveTextureObjects; } + unsigned int getNumberActiveTextureObjects() const { return _numActiveTextureObjects; } + + void setNumberOrphanedTextureObjects(unsigned int size) { _numOrphanedTextureObjects = size; } + unsigned int& getNumberOrphanedTextureObjects() { return _numOrphanedTextureObjects; } + unsigned int getNumberOrphanedTextureObjects() const { return _numOrphanedTextureObjects; } + + void setCurrTexturePoolSize(unsigned int size) { _currTexturePoolSize = size; } + unsigned int& getCurrTexturePoolSize() { return _currTexturePoolSize; } + unsigned int getCurrTexturePoolSize() const { return _currTexturePoolSize; } + + void setMaxTexturePoolSize(unsigned int size); + unsigned int getMaxTexturePoolSize() const { return _maxTexturePoolSize; } + + bool hasSpace(unsigned int size) const { return (_currTexturePoolSize+size)<=_maxTexturePoolSize; } + bool makeSpace(unsigned int size); + + TextureObject* generateTextureObject(const Texture* texture, GLenum target); + TextureObject* generateTextureObject(const Texture* texture, + GLenum target, + GLint numMipmapLevels, + GLenum internalFormat, + GLsizei width, + GLsizei height, + GLsizei depth, + GLint border); + void handlePendingOrphandedTextureObjects(); + void deleteAllTextureObjects(); + void discardAllTextureObjects(); + void flushAllDeletedTextureObjects(); + void discardAllDeletedTextureObjects(); + void flushDeletedTextureObjects(double currentTime, double& availableTime); + void releaseTextureObject(TextureObject* to); + + TextureObjectSet* getTextureObjectSet(const TextureProfile& profile); + + void newFrame(osg::FrameStamp* fs); + void resetStats(); + void reportStats(std::ostream& out); + void recomputeStats(std::ostream& out) const; + bool checkConsistency() const; + + unsigned int& getFrameNumber() { return _frameNumber; } + unsigned int& getNumberFrames() { return _numFrames; } + + unsigned int& getNumberDeleted() { return _numDeleted; } + double& getDeleteTime() { return _deleteTime; } + + unsigned int& getNumberGenerated() { return _numGenerated; } + double& getGenerateTime() { return _generateTime; } + + unsigned int& getNumberApplied() { return _numApplied; } + double& getApplyTime() { return _applyTime; } + + + protected: + + typedef std::map< TextureProfile, osg::ref_ptr > TextureSetMap; + unsigned int _contextID; + unsigned int _numActiveTextureObjects; + unsigned int _numOrphanedTextureObjects; + unsigned int _currTexturePoolSize; + unsigned int _maxTexturePoolSize; + TextureSetMap _textureSetMap; + + unsigned int _frameNumber; + + unsigned int _numFrames; + unsigned int _numDeleted; + double _deleteTime; + + unsigned int _numGenerated; + double _generateTime; + + unsigned int _numApplied; + double _applyTime; + + }; + + static osg::ref_ptr& getTextureObjectManager(unsigned int contextID); + + static TextureObject* generateTextureObject(const Texture* texture, unsigned int contextID,GLenum target); + + static TextureObject* generateTextureObject(const Texture* texture, + unsigned int contextID, + GLenum target, + GLint numMipmapLevels, + GLenum internalFormat, + GLsizei width, + GLsizei height, + GLsizei depth, + GLint border); + + static void deleteAllTextureObjects(unsigned int contextID); + static void discardAllTextureObjects(unsigned int contextID); + static void flushAllDeletedTextureObjects(unsigned int contextID); + static void discardAllDeletedTextureObjects(unsigned int contextID); + static void flushDeletedTextureObjects(unsigned int contextID,double currentTime, double& availableTime); + static void releaseTextureObject(unsigned int contextID, TextureObject* to); + + protected: + + typedef buffered_object< ref_ptr > TextureObjectBuffer; + mutable TextureObjectBuffer _textureObjectBuffer; + mutable ref_ptr _readPBuffer; + +}; + +} + +#endif diff --git a/libs/include/android/osg/Texture1D b/libs/include/android/osg/Texture1D new file mode 100755 index 0000000..65f48d6 --- /dev/null +++ b/libs/include/android/osg/Texture1D @@ -0,0 +1,162 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +// -*-c++-*- + +#ifndef OSG_TEXTURE1D +#define OSG_TEXTURE1D 1 + +#include + +#ifndef GL_TEXTURE_1D + #define GL_TEXTURE_1D 0x0DE0 +#endif + +namespace osg { + +/** Encapsulates OpenGL 1D texture functionality. Doesn't support cube maps, + * so ignore \a face parameters. +*/ +class OSG_EXPORT Texture1D : public Texture +{ + + public : + + Texture1D(); + + Texture1D(Image* image); + + /** Copy constructor using CopyOp to manage deep vs shallow copy. */ + Texture1D(const Texture1D& text,const CopyOp& copyop=CopyOp::SHALLOW_COPY); + + META_StateAttribute(osg, Texture1D,TEXTURE); + + /** Return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs. */ + virtual int compare(const StateAttribute& rhs) const; + + virtual GLenum getTextureTarget() const { return GL_TEXTURE_1D; } + + /** Sets the texture image. */ + void setImage(Image* image); + + /** Gets the texture image. */ + Image* getImage() { return _image.get(); } + + /** Gets the const texture image. */ + inline const Image* getImage() const { return _image.get(); } + + inline unsigned int& getModifiedCount(unsigned int contextID) const + { + // get the modified count for the current contextID. + return _modifiedCount[contextID]; + } + + + /** Sets the texture image, ignoring face. */ + virtual void setImage(unsigned int, Image* image) { setImage(image); } + + /** Gets the texture image, ignoring face. */ + virtual Image* getImage(unsigned int) { return _image.get(); } + + /** Gets the const texture image, ignoring face. */ + virtual const Image* getImage(unsigned int) const { return _image.get(); } + + /** Gets the number of images that can be assigned to the Texture. */ + virtual unsigned int getNumImages() const { return 1; } + + + /** Sets the texture width. If width is zero, calculate the value + * from the source image width. */ + inline void setTextureWidth(int width) { _textureWidth = width; } + + /** Gets the texture width. */ + virtual int getTextureWidth() const { return _textureWidth; } + virtual int getTextureHeight() const { return 1; } + virtual int getTextureDepth() const { return 1; } + + + class OSG_EXPORT SubloadCallback : public Referenced + { + public: + virtual void load(const Texture1D& texture,State& state) const = 0; + virtual void subload(const Texture1D& texture,State& state) const = 0; + }; + + void setSubloadCallback(SubloadCallback* cb) { _subloadCallback = cb;; } + + SubloadCallback* getSubloadCallback() { return _subloadCallback.get(); } + + const SubloadCallback* getSubloadCallback() const { return _subloadCallback.get(); } + + + /** Helper function. Sets the number of mipmap levels created for this + * texture. Should only be called within an osg::Texture::apply(), or + * during a custom OpenGL texture load. */ + void setNumMipmapLevels(unsigned int num) const { _numMipmapLevels=num; } + + /** Gets the number of mipmap levels created. */ + unsigned int getNumMipmapLevels() const { return _numMipmapLevels; } + + + /** Copies pixels into a 1D texture image, as per glCopyTexImage1D. + * Creates an OpenGL texture object from the current OpenGL background + * framebuffer contents at position \a x, \a y with width \a width. + * \a width must be a power of two. */ + void copyTexImage1D(State& state, int x, int y, int width); + + /** Copies a one-dimensional texture subimage, as per + * glCopyTexSubImage1D. Updates a portion of an existing OpenGL + * texture object from the current OpenGL background framebuffer + * contents at position \a x, \a y with width \a width. */ + void copyTexSubImage1D(State& state, int xoffset, int x, int y, int width); + + + /** Bind the texture object. If the texture object hasn't already been + * compiled, create the texture mipmap levels. */ + virtual void apply(State& state) const; + + protected : + + virtual ~Texture1D(); + + virtual void computeInternalFormat() const; + void allocateMipmap(State& state) const; + + /** Helper method. Create the texture without setting or using a + * texture binding. */ + void applyTexImage1D(GLenum target, Image* image, State& state, GLsizei& width, GLsizei& numMipmapLevels) const; + + + /** It's not ideal that _image is mutable, but it's required since + * Image::ensureDimensionsArePowerOfTwo() can only be called in a + * valid OpenGL context, and therefore within Texture::apply, which + * is const. */ + mutable ref_ptr _image; + + /** Subloaded images can have different texture and image sizes. */ + mutable GLsizei _textureWidth; + + /** Number of mipmap levels created. */ + mutable GLsizei _numMipmapLevels; + + ref_ptr _subloadCallback; + + typedef buffered_value ImageModifiedCount; + mutable ImageModifiedCount _modifiedCount; + + +}; + +} + +#endif diff --git a/libs/include/android/osg/Texture2D b/libs/include/android/osg/Texture2D new file mode 100755 index 0000000..199e557 --- /dev/null +++ b/libs/include/android/osg/Texture2D @@ -0,0 +1,172 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_TEXTURE2D +#define OSG_TEXTURE2D 1 + +#include + +namespace osg { + +/** Encapsulates OpenGL 2D texture functionality. Doesn't support cube maps, + * so ignore \a face parameters. +*/ +class OSG_EXPORT Texture2D : public Texture +{ + + public : + + Texture2D(); + + Texture2D(Image* image); + + /** Copy constructor using CopyOp to manage deep vs shallow copy. */ + Texture2D(const Texture2D& text,const CopyOp& copyop=CopyOp::SHALLOW_COPY); + + META_StateAttribute(osg, Texture2D,TEXTURE); + + /** Return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs. */ + virtual int compare(const StateAttribute& rhs) const; + + virtual GLenum getTextureTarget() const { return GL_TEXTURE_2D; } + + /** Sets the texture image. */ + void setImage(Image* image); + + /** Gets the texture image. */ + Image* getImage() { return _image.get(); } + + /** Gets the const texture image. */ + inline const Image* getImage() const { return _image.get(); } + + inline unsigned int& getModifiedCount(unsigned int contextID) const + { + // get the modified count for the current contextID. + return _modifiedCount[contextID]; + } + + + /** Sets the texture image, ignoring face. */ + virtual void setImage(unsigned int, Image* image) { setImage(image); } + + /** Gets the texture image, ignoring face. */ + virtual Image* getImage(unsigned int) { return _image.get(); } + + /** Gets the const texture image, ignoring face. */ + virtual const Image* getImage(unsigned int) const { return _image.get(); } + + /** Gets the number of images that can be assigned to the Texture. */ + virtual unsigned int getNumImages() const { return 1; } + + + /** Sets the texture width and height. If width or height are zero, + * calculate the respective value from the source image size. */ + inline void setTextureSize(int width, int height) const + { + _textureWidth = width; + _textureHeight = height; + } + + void setTextureWidth(int width) { _textureWidth=width; } + void setTextureHeight(int height) { _textureHeight=height; } + + virtual int getTextureWidth() const { return _textureWidth; } + virtual int getTextureHeight() const { return _textureHeight; } + virtual int getTextureDepth() const { return 1; } + + class OSG_EXPORT SubloadCallback : public Referenced + { + public: + + virtual bool textureObjectValid(const Texture2D& texture, State& state) const + { + return texture.textureObjectValid(state); + } + + virtual TextureObject* generateTextureObject(const Texture2D& texture, State& state) const + { + return osg::Texture::generateTextureObject(&texture, state.getContextID(), GL_TEXTURE_2D); + } + + virtual void load(const Texture2D& texture,State& state) const = 0; + virtual void subload(const Texture2D& texture,State& state) const = 0; + }; + + void setSubloadCallback(SubloadCallback* cb) { _subloadCallback = cb;; } + + SubloadCallback* getSubloadCallback() { return _subloadCallback.get(); } + + const SubloadCallback* getSubloadCallback() const { return _subloadCallback.get(); } + + + /** Helper function. Sets the number of mipmap levels created for this + * texture. Should only be called within an osg::Texture::apply(), or + * during a custom OpenGL texture load. */ + void setNumMipmapLevels(unsigned int num) const { _numMipmapLevels=num; } + + /** Gets the number of mipmap levels created. */ + unsigned int getNumMipmapLevels() const { return _numMipmapLevels; } + + + /** Copies pixels into a 2D texture image, as per glCopyTexImage2D. + * Creates an OpenGL texture object from the current OpenGL background + * framebuffer contents at position \a x, \a y with width \a width and + * height \a height. \a width and \a height must be a power of two. */ + void copyTexImage2D(State& state, int x, int y, int width, int height ); + + /** Copies a two-dimensional texture subimage, as per + * glCopyTexSubImage2D. Updates a portion of an existing OpenGL + * texture object from the current OpenGL background framebuffer + * contents at position \a x, \a y with width \a width and height + * \a height. Loads framebuffer data into the texture using offsets + * \a xoffset and \a yoffset. \a width and \a height must be powers + * of two. */ + void copyTexSubImage2D(State& state, int xoffset, int yoffset, int x, int y, int width, int height ); + + + /** Bind the texture object. If the texture object hasn't already been + * compiled, create the texture mipmap levels. */ + virtual void apply(State& state) const; + + + + protected : + + virtual ~Texture2D(); + + virtual void computeInternalFormat() const; + void allocateMipmap(State& state) const; + + /** Return true of the TextureObject assigned to the context associate with osg::State object is valid.*/ + bool textureObjectValid(State& state) const; + + friend class SubloadCallback; + + ref_ptr _image; + + /** Subloaded images can have different texture and image sizes. */ + mutable GLsizei _textureWidth, _textureHeight; + + /** Number of mipmap levels created. */ + mutable GLsizei _numMipmapLevels; + + ref_ptr _subloadCallback; + + typedef buffered_value ImageModifiedCount; + mutable ImageModifiedCount _modifiedCount; + +}; + +} + +#endif diff --git a/libs/include/android/osg/Texture2DArray b/libs/include/android/osg/Texture2DArray new file mode 100755 index 0000000..b6ed4a6 --- /dev/null +++ b/libs/include/android/osg/Texture2DArray @@ -0,0 +1,230 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_TEXTURE2DARRAY +#define OSG_TEXTURE2DARRAY 1 + +#include +#include + +namespace osg { + +/** Texture2DArray state class which encapsulates OpenGL 2D array texture functionality. + * Texture arrays were introduced with Shader Model 4.0 hardware. + * + * A 2D texture array does contain textures sharing the same properties (e.g. size, bitdepth,...) + * in a layered structure. See http://www.opengl.org/registry/specs/EXT/texture_array.txt for more info. + */ +class OSG_EXPORT Texture2DArray : public Texture +{ + + public : + + Texture2DArray(); + + /** Copy constructor using CopyOp to manage deep vs shallow copy. */ + Texture2DArray(const Texture2DArray& cm,const CopyOp& copyop=CopyOp::SHALLOW_COPY); + + META_StateAttribute(osg, Texture2DArray, TEXTURE); + + /** Return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs. */ + virtual int compare(const StateAttribute& rhs) const; + + virtual GLenum getTextureTarget() const { return GL_TEXTURE_2D_ARRAY_EXT; } + + /** Set the texture image for specified layer. */ + virtual void setImage(unsigned int layer, Image* image); + + /** Get the texture image for specified layer. */ + virtual Image* getImage(unsigned int layer); + + /** Get the const texture image for specified layer. */ + virtual const Image* getImage(unsigned int layer) const; + + /** Get the number of images that are assigned to the Texture. + * The number is equal to the texture depth. To get the maximum possible + * image/layer count, you have to use the extension subclass, since it provides + * graphic context dependent information. + */ + virtual unsigned int getNumImages() const { return getTextureDepth(); } + + /** Check how often was a certain layer in the given context modified */ + inline unsigned int& getModifiedCount(unsigned int layer, unsigned int contextID) const + { + // get the modified count for the current contextID. + return _modifiedCount[layer][contextID]; + } + + /** Set the texture width and height. If width or height are zero then + * the respective size value is calculated from the source image sizes. + * Depth parameter specifies the number of layers to be used. + */ + void setTextureSize(int width, int height, int depth); + + void setTextureWidth(int width) { _textureWidth=width; } + void setTextureHeight(int height) { _textureHeight=height; } + void setTextureDepth(int depth); + + virtual int getTextureWidth() const { return _textureWidth; } + virtual int getTextureHeight() const { return _textureHeight; } + virtual int getTextureDepth() const { return _textureDepth; } + + class OSG_EXPORT SubloadCallback : public Referenced + { + public: + virtual void load(const Texture2DArray& texture,State& state) const = 0; + virtual void subload(const Texture2DArray& texture,State& state) const = 0; + }; + + + void setSubloadCallback(SubloadCallback* cb) { _subloadCallback = cb;; } + + SubloadCallback* getSubloadCallback() { return _subloadCallback.get(); } + + const SubloadCallback* getSubloadCallback() const { return _subloadCallback.get(); } + + + + /** Set the number of mip map levels the the texture has been created with. + * Should only be called within an osg::Texture::apply() and custom OpenGL texture load. + */ + void setNumMipmapLevels(unsigned int num) const { _numMipmapLevels=num; } + + /** Get the number of mip map levels the the texture has been created with. */ + unsigned int getNumMipmapLevels() const { return _numMipmapLevels; } + + /** Copies a two-dimensional texture subimage, as per + * glCopyTexSubImage3D. Updates a portion of an existing OpenGL + * texture object from the current OpenGL background framebuffer + * contents at position \a x, \a y with width \a width and height + * \a height. Loads framebuffer data into the texture using offsets + * \a xoffset and \a yoffset. \a zoffset specifies the layer of the texture + * array to which the result is copied. + */ + void copyTexSubImage2DArray(State& state, int xoffset, int yoffset, int zoffset, int x, int y, int width, int height ); + + /** Bind the texture if already compiled. Otherwise recompile. + */ + virtual void apply(State& state) const; + + + /** Extensions class which encapsulates the querying of extensions and + * associated function pointers, and provides convenience wrappers to + * check for the extensions or use the associated functions. + */ + class OSG_EXPORT Extensions : public osg::Referenced + { + public: + Extensions(unsigned int contextID); + + Extensions(const Extensions& rhs); + + void lowestCommonDenominator(const Extensions& rhs); + + void setupGLExtensions(unsigned int contextID); + + void setTexture2DArraySupported(bool flag) { _isTexture2DArraySupported=flag; } + bool isTexture2DArraySupported() const { return _isTexture2DArraySupported; } + + void setTexture3DSupported(bool flag) { _isTexture3DSupported=flag; } + bool isTexture3DSupported() const { return _isTexture3DSupported; } + + void setMaxLayerCount(GLint count) { _maxLayerCount = count; } + GLint maxLayerCount() const { return _maxLayerCount; } + + void setMax2DSize(GLint size) { _max2DSize = size; } + GLint max2DSize() const { return _max2DSize; } + + void glTexImage3D( GLenum target, GLint level, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid *pixels) const; + + void glTexSubImage3D( GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const GLvoid *pixels) const; + + void glCopyTexSubImage3D( GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height ) const; + + bool isCompressedTexImage3DSupported() const { return _glCompressedTexImage3D!=0; } + void glCompressedTexImage3D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const GLvoid *data) const; + + bool isCompressedTexSubImage3DSupported() const { return _glCompressedTexSubImage3D!=0; } + void glCompressedTexSubImage3D( GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const GLvoid *data ) const; + + protected: + + ~Extensions() {} + + bool _isTexture2DArraySupported; + bool _isTexture3DSupported; + + GLint _maxLayerCount; + GLint _max2DSize; + + typedef void (GL_APIENTRY * GLTexImage3DProc) ( GLenum target, GLint level, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid *pixels); + typedef void (GL_APIENTRY * GLTexSubImage3DProc) ( GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const GLvoid *pixels); + typedef void (GL_APIENTRY * CompressedTexImage3DArbProc) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const GLvoid *data); + typedef void (GL_APIENTRY * CompressedTexSubImage3DArbProc) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const GLvoid *data); + typedef void (GL_APIENTRY * GLCopyTexSubImageProc) ( GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height ); + + GLTexImage3DProc _glTexImage3D; + GLTexSubImage3DProc _glTexSubImage3D; + CompressedTexImage3DArbProc _glCompressedTexImage3D; + CompressedTexSubImage3DArbProc _glCompressedTexSubImage3D; + GLCopyTexSubImageProc _glCopyTexSubImage3D; + + }; + + /** Function to call to get the extension of a specified context. + * If the Extension object for that context has not yet been created + * and the 'createIfNotInitalized' flag been set to false then returns NULL. + * If 'createIfNotInitalized' is true then the Extensions object is + * automatically created. However, in this case the extension object will + * only be created with the graphics context associated with ContextID. + */ + static Extensions* getExtensions(unsigned int contextID,bool createIfNotInitalized); + + /** The setExtensions method allows users to override the extensions across graphics contexts. + * Typically used when you have different extensions supported across graphics pipes + * but need to ensure that they all use the same low common denominator extensions. + */ + static void setExtensions(unsigned int contextID,Extensions* extensions); + + + protected : + + virtual ~Texture2DArray(); + + bool imagesValid() const; + + virtual void computeInternalFormat() const; + void allocateMipmap(State& state) const; + + void applyTexImage2DArray_subload(State& state, Image* image, GLsizei inwidth, GLsizei inheight, GLsizei indepth, GLint inInternalFormat, GLsizei& numMipmapLevels) const; + + /** + * Use std::vector to encapsulate referenced pointers to images of different layers. + * Vectors gives us a random access iterator. The overhead of non-used elements is negligible */ + std::vector > _images; + + // subloaded images can have different texture and image sizes. + mutable GLsizei _textureWidth, _textureHeight, _textureDepth; + + // number of mip map levels the the texture has been created with, + mutable GLsizei _numMipmapLevels; + + ref_ptr _subloadCallback; + + typedef buffered_value ImageModifiedCount; + mutable std::vector _modifiedCount; +}; + +} + +#endif diff --git a/libs/include/android/osg/Texture2DMultisample b/libs/include/android/osg/Texture2DMultisample new file mode 100755 index 0000000..fa19dee --- /dev/null +++ b/libs/include/android/osg/Texture2DMultisample @@ -0,0 +1,95 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2010 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. + * + * Texture2DMultisample codes Copyright (C) 2010 Marcin Hajder + * Thanks to to my company http://www.ai.com.pl for allowing me free this work. +*/ + +#ifndef OSG_TEXTURE2DMS +#define OSG_TEXTURE2DMS 1 + +#include + +namespace osg { + + /** Texture2DMultisample state class which encapsulates OpenGL 2D multisampled texture functionality. + * Multisampled texture were introduced with OpenGL 3.1 and extension GL_ARB_texture_multisample. + * See http://www.opengl.org/registry/specs/ARB/texture_multisample.txt for more info. + */ + +class OSG_EXPORT Texture2DMultisample : public Texture +{ + public : + + Texture2DMultisample(); + + Texture2DMultisample(GLsizei numSamples, GLboolean fixedsamplelocations); + + /** Copy constructor using CopyOp to manage deep vs shallow copy. */ + Texture2DMultisample(const Texture2DMultisample& text,const CopyOp& copyop=CopyOp::SHALLOW_COPY); + + META_StateAttribute(osg, Texture2DMultisample,TEXTURE); + + /** Return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs. */ + virtual int compare(const StateAttribute& rhs) const; + + virtual GLenum getTextureTarget() const + { + return GL_TEXTURE_2D_MULTISAMPLE; + } + + /** Sets the texture width and height. If width or height are zero, + * calculate the respective value from the source image size. */ + inline void setTextureSize(int width, int height) const + { + _textureWidth = width; + _textureHeight = height; + } + + inline void setNumSamples( int samples ) { _numSamples = samples; } + + // unnecessary for Texture2DMultisample + virtual void setImage(unsigned int /*face*/, Image* /*image*/) {} + virtual Image* getImage(unsigned int /*face*/) { return NULL; } + virtual const Image* getImage(unsigned int /*face*/) const { return NULL; } + virtual unsigned int getNumImages() const {return 0; } + virtual void allocateMipmap(State& /*state*/) const {} + + void setTextureWidth(int width) { _textureWidth=width; } + void setTextureHeight(int height) { _textureHeight=height; } + + virtual int getTextureWidth() const { return _textureWidth; } + virtual int getTextureHeight() const { return _textureHeight; } + virtual int getTextureDepth() const { return 1; } + + /** Bind the texture object. If the texture object hasn't already been + * compiled, create the texture mipmap levels. */ + virtual void apply(State& state) const; + + protected : + + virtual ~Texture2DMultisample(); + + virtual void computeInternalFormat() const; + + /** Subloaded images can have different texture and image sizes. */ + mutable GLsizei _textureWidth, _textureHeight; + + mutable GLsizei _numSamples; + + mutable GLboolean _fixedsamplelocations; + +}; + +} + +#endif diff --git a/libs/include/android/osg/Texture3D b/libs/include/android/osg/Texture3D new file mode 100755 index 0000000..4af0c5d --- /dev/null +++ b/libs/include/android/osg/Texture3D @@ -0,0 +1,230 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_TEXTURE3D +#define OSG_TEXTURE3D 1 + +#include + +#ifndef GL_MAX_3D_TEXTURE_SIZE + #define GL_MAX_3D_TEXTURE_SIZE 0x8073 +#endif + +namespace osg { + +/** Encapsulates OpenGL 3D texture functionality. Doesn't support cube maps, + * so ignore \a face parameters. +*/ +class OSG_EXPORT Texture3D : public Texture +{ + + public : + + Texture3D(); + + Texture3D(Image* image); + + /** Copy constructor using CopyOp to manage deep vs shallow copy. */ + Texture3D(const Texture3D& text,const CopyOp& copyop=CopyOp::SHALLOW_COPY); + + META_StateAttribute(osg, Texture3D,TEXTURE); + + /** Return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs. */ + virtual int compare(const StateAttribute& rhs) const; + + virtual GLenum getTextureTarget() const { return GL_TEXTURE_3D; } + + /** Sets the texture image. */ + void setImage(Image* image); + + /** Gets the texture image. */ + Image* getImage() { return _image.get(); } + + /** Gets the const texture image. */ + inline const Image* getImage() const { return _image.get(); } + + inline unsigned int& getModifiedCount(unsigned int contextID) const + { + // get the modified count for the current contextID. + return _modifiedCount[contextID]; + } + + /** Sets the texture image, ignoring face. */ + virtual void setImage(unsigned int, Image* image) { setImage(image); } + + /** Gets the texture image, ignoring face. */ + virtual Image* getImage(unsigned int) { return _image.get(); } + + /** Gets the const texture image, ignoring face. */ + virtual const Image* getImage(unsigned int) const { return _image.get(); } + + /** Gets the number of images that can be assigned to the Texture. */ + virtual unsigned int getNumImages() const { return 1; } + + + /** Sets the texture width, height, and depth. If width, height, or + * depth are zero, calculate the respective value from the source + * image size. */ + inline void setTextureSize(int width, int height, int depth) const + { + _textureWidth = width; + _textureHeight = height; + _textureDepth = depth; + } + + /** Gets the texture subload width. */ + inline void getTextureSize(int& width, int& height, int& depth) const + { + width = _textureWidth; + height = _textureHeight; + depth = _textureDepth; + } + + void setTextureWidth(int width) { _textureWidth=width; } + void setTextureHeight(int height) { _textureHeight=height; } + void setTextureDepth(int depth) { _textureDepth=depth; } + + virtual int getTextureWidth() const { return _textureWidth; } + virtual int getTextureHeight() const { return _textureHeight; } + virtual int getTextureDepth() const { return _textureDepth; } + + + class OSG_EXPORT SubloadCallback : public Referenced + { + public: + virtual void load(const Texture3D& texture,State& state) const = 0; + virtual void subload(const Texture3D& texture,State& state) const = 0; + }; + + void setSubloadCallback(SubloadCallback* cb) { _subloadCallback = cb;; } + + SubloadCallback* getSubloadCallback() { return _subloadCallback.get(); } + + const SubloadCallback* getSubloadCallback() const { return _subloadCallback.get(); } + + + /** Helper function. Sets the number of mipmap levels created for this + * texture. Should only be called within an osg::Texture::apply(), or + * during a custom OpenGL texture load. */ + void setNumMipmapLevels(unsigned int num) const { _numMipmapLevels=num; } + + /** Gets the number of mipmap levels created. */ + unsigned int getNumMipmapLevels() const { return _numMipmapLevels; } + + + /** Copies a two-dimensional texture subimage, as per + * glCopyTexSubImage3D. Updates a portion of an existing OpenGL + * texture object from the current OpenGL background framebuffer + * contents at position \a x, \a y with width \a width and height + * \a height. Loads framebuffer data into the texture using offsets + * \a xoffset, \a yoffset, and \a zoffset. \a width and \a height + * must be powers of two. */ + void copyTexSubImage3D(State& state, int xoffset, int yoffset, int zoffset, int x, int y, int width, int height); + + + /** Bind the texture object. If the texture object hasn't already been + * compiled, create the texture mipmap levels. */ + virtual void apply(State& state) const; + + + /** Encapsulates queries of extension availability, obtains extension + * function pointers, and provides convenience wrappers for + * calling extension functions. */ + class OSG_EXPORT Extensions : public osg::Referenced + { + public: + Extensions(unsigned int contextID); + + Extensions(const Extensions& rhs); + + void lowestCommonDenominator(const Extensions& rhs); + + void setupGLExtensions(unsigned int contextID); + + void setTexture3DSupported(bool flag) { _isTexture3DSupported=flag; } + bool isTexture3DSupported() const { return _isTexture3DSupported; } + + void setTexture3DFast(bool flag) { _isTexture3DFast=flag; } + bool isTexture3DFast() const { return _isTexture3DFast; } + + void setMaxTexture3DSize(GLint maxsize) { _maxTexture3DSize=maxsize; } + GLint maxTexture3DSize() const { return _maxTexture3DSize; } + + bool isCompressedTexImage3DSupported() const { return glCompressedTexImage3D!=0; } + + bool isCompressedTexSubImage3DSupported() const { return glCompressedTexSubImage3D!=0; } + + typedef void (GL_APIENTRY * GLTexImage3DProc) ( GLenum target, GLint level, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid *pixels); + typedef void (GL_APIENTRY * GLTexSubImage3DProc) ( GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const GLvoid *pixels); + typedef void (GL_APIENTRY * CompressedTexImage3DArbProc) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const GLvoid *data); + typedef void (GL_APIENTRY * CompressedTexSubImage3DArbProc) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const GLvoid *data); + typedef void (GL_APIENTRY * GLCopyTexSubImageProc) ( GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height ); + + GLTexImage3DProc glTexImage3D; + GLTexSubImage3DProc glTexSubImage3D; + CompressedTexImage3DArbProc glCompressedTexImage3D; + CompressedTexSubImage3DArbProc glCompressedTexSubImage3D; + GLCopyTexSubImageProc glCopyTexSubImage3D; + + protected: + + ~Extensions() {} + + bool _isTexture3DSupported; + bool _isTexture3DFast; + GLint _maxTexture3DSize; + }; + + /** Encapsulates queries of extension availability, obtains extension + * function pointers, and provides convenience wrappers for + * calling extension functions. */ + static Extensions* getExtensions(unsigned int contextID,bool createIfNotInitalized); + + /** Overrides Extensions objects across graphics contexts. Typically + * used to ensure the same lowest common denominator of extensions + * on systems with different graphics pipes. */ + static void setExtensions(unsigned int contextID,Extensions* extensions); + + protected : + + virtual ~Texture3D(); + + void computeRequiredTextureDimensions(State& state, const osg::Image& image,GLsizei& width, GLsizei& height,GLsizei& depth, GLsizei& numMipmapLevels) const; + + virtual void computeInternalFormat() const; + void allocateMipmap(State& state) const; + + void applyTexImage3D(GLenum target, Image* image, State& state, GLsizei& inwidth, GLsizei& inheight, GLsizei& indepth, GLsizei& numMipmapLevels) const; + + /** It's not ideal that _image is mutable, but it's required since + * Image::ensureDimensionsArePowerOfTwo() can only be called in a + * valid OpenGL context, and therefore within Texture::apply, which + * is const. */ + mutable ref_ptr _image; + + /** Subloaded images can have different texture and image sizes. */ + mutable GLsizei _textureWidth, _textureHeight, _textureDepth; + + /** Number of mip map levels the the texture has been created with, */ + mutable GLsizei _numMipmapLevels; + + ref_ptr _subloadCallback; + + typedef buffered_value ImageModifiedCount; + mutable ImageModifiedCount _modifiedCount; + +}; + +} + +#endif diff --git a/libs/include/android/osg/TextureBuffer b/libs/include/android/osg/TextureBuffer new file mode 100755 index 0000000..ef067a2 --- /dev/null +++ b/libs/include/android/osg/TextureBuffer @@ -0,0 +1,146 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2013 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +// -*-c++-*- + +#ifndef OSG_TEXTUREBUFFEROBJECT +#define OSG_TEXTUREBUFFEROBJECT 1 + +#include +#include + +#ifndef GL_ARB_texture_buffer_object + #define GL_TEXTURE_BUFFER_ARB 0x8C2A + #define GL_MAX_TEXTURE_BUFFER_SIZE_ARB 0x8C2B + #define GL_TEXTURE_BINDING_BUFFER_ARB 0x8C2C + #define GL_TEXTURE_BUFFER_DATA_STORE_BINDING_ARB 0x8C2D + #define GL_TEXTURE_BUFFER_FORMAT_ARB 0x8C2E +#endif + +namespace osg { + +/** Encapsulates OpenGL texture buffer functionality. +*/ +class OSG_EXPORT TextureBuffer : public Texture +{ + + public : + + TextureBuffer(); + + TextureBuffer(Image* image); + + /** Copy constructor using CopyOp to manage deep vs shallow copy. */ + TextureBuffer(const TextureBuffer& text,const CopyOp& copyop=CopyOp::SHALLOW_COPY); + + META_StateAttribute(osg, TextureBuffer, TEXTURE); + + /** Return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs. */ + virtual int compare(const StateAttribute& rhs) const; + + virtual GLenum getTextureTarget() const { return GL_TEXTURE_BUFFER_ARB; } + + /** Sets the texture image. */ + void setImage(Image* image); + + /** Gets the texture image. */ + Image* getImage() { return _image.get(); } + + /** Gets the const texture image. */ + inline const Image* getImage() const { return _image.get(); } + + inline unsigned int& getModifiedCount(unsigned int contextID) const + { + // get the modified count for the current contextID. + return _modifiedCount[contextID]; + } + + + /** Sets the texture image, ignoring face. */ + virtual void setImage(unsigned int, Image* image) { setImage(image); } + + /** Gets the texture image, ignoring face. */ + virtual Image* getImage(unsigned int) { return _image.get(); } + + /** Gets the const texture image, ignoring face. */ + virtual const Image* getImage(unsigned int) const { return _image.get(); } + + /** Gets the number of images that can be assigned to the Texture. */ + virtual unsigned int getNumImages() const { return 1; } + + + /** Sets the texture width. If width is zero, calculate the value + * from the source image width. */ + inline void setTextureWidth(int width) { _textureWidth = width; } + + /** Gets the texture width. */ + virtual int getTextureWidth() const { return _textureWidth; } + virtual int getTextureHeight() const { return 1; } + virtual int getTextureDepth() const { return 1; } + + inline void setUsageHint( GLenum usageHint ) { _usageHint=usageHint; } + inline GLenum getUsageHint() const { return _usageHint; } + + virtual void allocateMipmap(State& /*state*/) const {}; + + /** Bind the texture buffer.*/ + virtual void apply(State& state) const; + + /** Bind buffer to different target. */ + void bindBufferAs(unsigned int contextID, GLenum target); + void unbindBufferAs(unsigned int contextID, GLenum target); + + protected : + + virtual ~TextureBuffer(); + + virtual void computeInternalFormat() const; + + ref_ptr _image; + + mutable GLsizei _textureWidth; + GLenum _usageHint; + + typedef buffered_value ImageModifiedCount; + mutable ImageModifiedCount _modifiedCount; + + class TextureBufferObject : public osg::Referenced + { + public: + TextureBufferObject(unsigned int contextID, GLenum usageHint) : + _id(0), + _usageHint(usageHint) + { + _extensions = osg::GLBufferObject::getExtensions(contextID, true); + } + + void bindBuffer(GLenum target); + void unbindBuffer(GLenum target); + + void texBuffer(GLenum internalFormat); + void bufferData( osg::Image* image ); + void bufferSubData( osg::Image* image ); + + public: + GLuint _id; + GLenum _usageHint; + osg::GLBufferObject::Extensions* _extensions; + }; + + typedef osg::buffered_object > TextureBufferObjectList; + mutable TextureBufferObjectList _textureBufferObjects; +}; + +} + +#endif diff --git a/libs/include/android/osg/TextureCubeMap b/libs/include/android/osg/TextureCubeMap new file mode 100755 index 0000000..99956bf --- /dev/null +++ b/libs/include/android/osg/TextureCubeMap @@ -0,0 +1,188 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_TEXTURECUBEMAP +#define OSG_TEXTURECUBEMAP 1 + +#include + + +namespace osg { + +/** TextureCubeMap state class which encapsulates OpenGL texture cubemap functionality. */ +class OSG_EXPORT TextureCubeMap : public Texture +{ + + public : + + TextureCubeMap(); + + /** Copy constructor using CopyOp to manage deep vs shallow copy. */ + TextureCubeMap(const TextureCubeMap& cm,const CopyOp& copyop=CopyOp::SHALLOW_COPY); + + META_StateAttribute(osg, TextureCubeMap,TEXTURE); + + /** Return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs. */ + virtual int compare(const StateAttribute& rhs) const; + + virtual GLenum getTextureTarget() const { return GL_TEXTURE_CUBE_MAP; } + + enum Face { + POSITIVE_X=0, + NEGATIVE_X=1, + POSITIVE_Y=2, + NEGATIVE_Y=3, + POSITIVE_Z=4, + NEGATIVE_Z=5 + }; + + /** Set the texture image for specified face. */ + virtual void setImage(unsigned int face, Image* image); + + /** Get the texture image for specified face. */ + virtual Image* getImage(unsigned int face); + + /** Get the const texture image for specified face. */ + virtual const Image* getImage(unsigned int face) const; + + /** Get the number of images that can be assigned to the Texture. */ + virtual unsigned int getNumImages() const { return 6; } + + inline unsigned int& getModifiedCount(unsigned int face,unsigned int contextID) const + { + // get the modified count for the current contextID. + return _modifiedCount[face][contextID]; + } + + /** Set the texture width and height. If width or height are zero then + * the respective size value is calculated from the source image sizes. + */ + inline void setTextureSize(int width, int height) const + { + _textureWidth = width; + _textureHeight = height; + } + + void setTextureWidth(int width) { _textureWidth=width; } + void setTextureHeight(int height) { _textureHeight=height; } + + virtual int getTextureWidth() const { return _textureWidth; } + virtual int getTextureHeight() const { return _textureHeight; } + virtual int getTextureDepth() const { return 1; } + + class OSG_EXPORT SubloadCallback : public Referenced + { + public: + virtual void load(const TextureCubeMap& texture,State& state) const = 0; + virtual void subload(const TextureCubeMap& texture,State& state) const = 0; + }; + + void setSubloadCallback(SubloadCallback* cb) { _subloadCallback = cb;; } + + SubloadCallback* getSubloadCallback() { return _subloadCallback.get(); } + + const SubloadCallback* getSubloadCallback() const { return _subloadCallback.get(); } + + + /** Set the number of mip map levels the the texture has been created with. + * Should only be called within an osg::Texuture::apply() and custom OpenGL texture load. + */ + void setNumMipmapLevels(unsigned int num) const { _numMipmapLevels=num; } + + /** Get the number of mip map levels the the texture has been created with. */ + unsigned int getNumMipmapLevels() const { return _numMipmapLevels; } + + /** Copies a two-dimensional texture subimage, as per + * glCopyTexSubImage2D. Updates a portion of an existing OpenGL + * texture object from the current OpenGL background framebuffer + * contents at position \a x, \a y with width \a width and height + * \a height. Loads framebuffer data into the texture using offsets + * \a xoffset and \a yoffset. \a width and \a height must be powers + * of two. */ + void copyTexSubImageCubeMap(State& state, int face, int xoffset, int yoffset, int x, int y, int width, int height ); + + + /** On first apply (unless already compiled), create the mipmapped + * texture and bind it. Subsequent apply will simple bind to texture. + */ + virtual void apply(State& state) const; + + + /** Extensions class which encapsulates the querying of extensions and + * associated function pointers, and provides convenience wrappers to + * check for the extensions or use the associated functions. + */ + class OSG_EXPORT Extensions : public osg::Referenced + { + public: + Extensions(unsigned int contextID); + + Extensions(const Extensions& rhs); + + void lowestCommonDenominator(const Extensions& rhs); + + void setupGLExtensions(unsigned int contextID); + + void setCubeMapSupported(bool flag) { _isCubeMapSupported=flag; } + bool isCubeMapSupported() const { return _isCubeMapSupported; } + + protected: + + ~Extensions() {} + + bool _isCubeMapSupported; + + }; + + /** Function to call to get the extension of a specified context. + * If the Extensions object for that context has not yet been created + * and the 'createIfNotInitalized' flag been set to false then returns NULL. + * If 'createIfNotInitalized' is true then the Extensions object is + * automatically created. However, in this case the extension object will + * only be created with the graphics context associated with ContextID. + */ + static Extensions* getExtensions(unsigned int contextID,bool createIfNotInitalized); + + /** The setExtensions method allows users to override the extensions across graphics contexts. + * Typically used when you have different extensions supported across graphics pipes + * but need to ensure that they all use the same low common denominator extensions. + */ + static void setExtensions(unsigned int contextID,Extensions* extensions); + + + protected : + + virtual ~TextureCubeMap(); + + bool imagesValid() const; + + virtual void computeInternalFormat() const; + void allocateMipmap(State& state) const; + + ref_ptr _images[6]; + + // subloaded images can have different texture and image sizes. + mutable GLsizei _textureWidth, _textureHeight; + + // number of mip map levels the the texture has been created with, + mutable GLsizei _numMipmapLevels; + + ref_ptr _subloadCallback; + + typedef buffered_value ImageModifiedCount; + mutable ImageModifiedCount _modifiedCount[6]; +}; + +} + +#endif diff --git a/libs/include/android/osg/TextureRectangle b/libs/include/android/osg/TextureRectangle new file mode 100755 index 0000000..d633215 --- /dev/null +++ b/libs/include/android/osg/TextureRectangle @@ -0,0 +1,148 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_TEXTURERECTANGLE +#define OSG_TEXTURERECTANGLE 1 + +#include + +#ifndef GL_TEXTURE_RECTANGLE_NV +#define GL_TEXTURE_RECTANGLE_NV 0x84F5 +#endif + +#ifndef GL_TEXTURE_RECTANGLE +#define GL_TEXTURE_RECTANGLE GL_TEXTURE_RECTANGLE_NV +#endif + +namespace osg { + +/** Texture state class which encapsulates OpenGL texture functionality. */ +class OSG_EXPORT TextureRectangle : public Texture +{ + + public : + + TextureRectangle(); + + TextureRectangle(Image* image); + + /** Copy constructor using CopyOp to manage deep vs shallow copy. */ + TextureRectangle(const TextureRectangle& text,const CopyOp& copyop=CopyOp::SHALLOW_COPY); + + META_StateAttribute(osg, TextureRectangle, TEXTURE); + + /** Return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs. */ + virtual int compare(const StateAttribute& rhs) const; + + virtual GLenum getTextureTarget() const { return GL_TEXTURE_RECTANGLE; } + + /** Set the texture image. */ + void setImage(Image* image); + + /** Get the texture image. */ + Image* getImage() { return _image.get(); } + + /** Get the const texture image. */ + inline const Image* getImage() const { return _image.get(); } + + inline unsigned int& getModifiedCount(unsigned int contextID) const + { + // get the modified count for the current contextID. + return _modifiedCount[contextID]; + } + + + /** Set the texture image, ignoring face value as there is only one image. */ + virtual void setImage(unsigned int, Image* image) { setImage(image); } + + /** Get the texture image, ignoring face value as there is only one image. */ + virtual Image* getImage(unsigned int) { return _image.get(); } + + /** Get the const texture image, ignoring face value as there is only one image. */ + virtual const Image* getImage(unsigned int) const { return _image.get(); } + + /** Get the number of images that can be assigned to the Texture. */ + virtual unsigned int getNumImages() const { return 1; } + + + /** Set the texture width and height. If width or height are zero then + * the respective size value is calculated from the source image sizes. + */ + inline void setTextureSize(int width, int height) const + { + _textureWidth = width; + _textureHeight = height; + } + + void setTextureWidth(int width) { _textureWidth=width; } + void setTextureHeight(int height) { _textureHeight=height; } + + virtual int getTextureWidth() const { return _textureWidth; } + virtual int getTextureHeight() const { return _textureHeight; } + virtual int getTextureDepth() const { return 1; } + + class SubloadCallback : public Referenced + { + public: + virtual void load(const TextureRectangle&, State&) const = 0; + virtual void subload(const TextureRectangle&, State&) const = 0; + }; + + void setSubloadCallback(SubloadCallback* cb) { _subloadCallback = cb;; } + SubloadCallback* getSubloadCallback() { return _subloadCallback.get(); } + const SubloadCallback* getSubloadCallback() const { return _subloadCallback.get(); } + + /** Copies pixels into a 2D texture image, as per glCopyTexImage2D. + * Creates an OpenGL texture object from the current OpenGL background + * framebuffer contents at position \a x, \a y with width \a width and + * height \a height. \a width and \a height must be a power of two. */ + void copyTexImage2D(State& state, int x, int y, int width, int height ); + + /** Copies a two-dimensional texture subimage, as per + * glCopyTexSubImage2D. Updates a portion of an existing OpenGL + * texture object from the current OpenGL background framebuffer + * contents at position \a x, \a y with width \a width and height + * \a height. Loads framebuffer data into the texture using offsets + * \a xoffset and \a yoffset. \a width and \a height must be powers + * of two. */ + void copyTexSubImage2D(State& state, int xoffset, int yoffset, int x, int y, int width, int height ); + + /** On first apply (unless already compiled), create and bind the + * texture, subsequent apply will simply bind to texture. + */ + virtual void apply(State& state) const; + + protected : + + virtual ~TextureRectangle(); + + virtual void computeInternalFormat() const; + void allocateMipmap(State& state) const; + + void applyTexImage_load(GLenum target, Image* image, State& state, GLsizei& inwidth, GLsizei& inheight) const; + void applyTexImage_subload(GLenum target, Image* image, State& state, GLsizei& inwidth, GLsizei& inheight, GLint& inInternalFormat) const; + + ref_ptr _image; + + // subloaded images can have different texture and image sizes. + mutable GLsizei _textureWidth, _textureHeight; + + ref_ptr _subloadCallback; + + typedef buffered_value ImageModifiedCount; + mutable ImageModifiedCount _modifiedCount; +}; + +} + +#endif diff --git a/libs/include/android/osg/Timer b/libs/include/android/osg/Timer new file mode 100755 index 0000000..bf1c8c7 --- /dev/null +++ b/libs/include/android/osg/Timer @@ -0,0 +1,153 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_TIMER +#define OSG_TIMER 1 + +#include + +namespace osg { + +#if defined(_MSC_VER) + typedef __int64 Timer_t; +#else + typedef unsigned long long Timer_t; +#endif + +/** Timer class is used for measuring elapsed time or time between two points. */ +class OSG_EXPORT Timer { + + public: + + Timer(); + ~Timer() {} + + static Timer* instance(); + + /** Get the timers tick value.*/ + Timer_t tick() const; + + /** Set the start.*/ + void setStartTick() { _startTick = tick(); } + void setStartTick(Timer_t t) { _startTick = t; } + Timer_t getStartTick() const { return _startTick; } + + + /** Get elapsed time in seconds.*/ + inline double time_s() const { return delta_s(_startTick, tick()); } + + /** Get elapsed time in milliseconds.*/ + inline double time_m() const { return delta_m(_startTick, tick()); } + + /** Get elapsed time in microseconds.*/ + inline double time_u() const { return delta_u(_startTick, tick()); } + + /** Get elapsed time in nanoseconds.*/ + inline double time_n() const { return delta_n(_startTick, tick()); } + + /** Get the time in seconds between timer ticks t1 and t2.*/ + inline double delta_s( Timer_t t1, Timer_t t2 ) const { return (double)(t2 - t1)*_secsPerTick; } + + /** Get the time in milliseconds between timer ticks t1 and t2.*/ + inline double delta_m( Timer_t t1, Timer_t t2 ) const { return delta_s(t1,t2)*1e3; } + + /** Get the time in microseconds between timer ticks t1 and t2.*/ + inline double delta_u( Timer_t t1, Timer_t t2 ) const { return delta_s(t1,t2)*1e6; } + + /** Get the time in nanoseconds between timer ticks t1 and t2.*/ + inline double delta_n( Timer_t t1, Timer_t t2 ) const { return delta_s(t1,t2)*1e9; } + + /** Get the the number of seconds per tick. */ + inline double getSecondsPerTick() const { return _secsPerTick; } + + protected : + + Timer_t _startTick; + double _secsPerTick; +}; + +/** Helper class for timing sections of code. */ +class ElapsedTime +{ + public: + inline ElapsedTime(double* elapsedTime, osg::Timer* timer = 0): + _time(elapsedTime) + { + init(timer); + } + + inline ElapsedTime(osg::Timer* timer = 0): + _time(0) + { + init(timer); + } + + inline ~ElapsedTime() + { + finish(); + } + + inline void reset() + { + _startTick = _timer->tick(); + } + + /** elapsed time in seconds. */ + inline double elapsedTime() const + { + return _timer->delta_s(_startTick, _timer->tick()); + } + + /** elapsed time in milliseconds. */ + inline double elapsedTime_m() const + { + return _timer->delta_m(_startTick, _timer->tick()); + } + + /** elapsed time in microseconds. */ + inline double elapsedTime_u() const + { + return _timer->delta_u(_startTick, _timer->tick()); + } + + /** elapsed time in nanoseconds. */ + inline double elapsedTime_n() const + { + return _timer->delta_n(_startTick, _timer->tick()); + } + + inline void finish() + { + Timer_t endTick = _timer->tick(); + if (_time) *_time += _timer->delta_s(_startTick, endTick); + _startTick = endTick; + } + + protected: + + inline void init(osg::Timer* timer) + { + if (timer) _timer = timer; + else _timer = osg::Timer::instance(); + + _startTick = _timer->tick(); + } + + double* _time; + Timer* _timer; + Timer_t _startTick; + +}; + +} +#endif diff --git a/libs/include/android/osg/TransferFunction b/libs/include/android/osg/TransferFunction new file mode 100755 index 0000000..85cab77 --- /dev/null +++ b/libs/include/android/osg/TransferFunction @@ -0,0 +1,128 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_TRANSFERFUNCTION +#define OSG_TRANSFERFUNCTION 1 + +#include +#include + +#include + +namespace osg { + + +/** TransferFunction is a class that provide a 1D,2D or 3D colour look up table + * that can be used on the GPU as a 1D, 2D or 3D texture. + * Typically uses include mapping heights to colours when contouring terrain, + * or mapping intensities to colours when volume rendering. +*/ +class OSG_EXPORT TransferFunction : public osg::Object +{ + public : + + TransferFunction(); + + /** Copy constructor using CopyOp to manage deep vs shallow copy.*/ + TransferFunction(const TransferFunction& tf, const CopyOp& copyop=CopyOp::SHALLOW_COPY); + + META_Object(osg, TransferFunction) + + /** Get the image that is used for passing the transfer function data to the GPU.*/ + osg::Image* getImage() { return _image.get(); } + + /** Get the const image that is used for passing the transfer function data to the GPU.*/ + const osg::Image* getImage() const { return _image.get(); } + + protected: + + virtual ~TransferFunction(); + + osg::ref_ptr _image; +}; + +/** 1D variant of TransferFunction. */ +class OSG_EXPORT TransferFunction1D : public osg::TransferFunction +{ + public: + + TransferFunction1D(); + + /** Copy constructor using CopyOp to manage deep vs shallow copy.*/ + TransferFunction1D(const TransferFunction1D& tf, const CopyOp& copyop=CopyOp::SHALLOW_COPY); + + META_Object(osg, TransferFunction1D) + + /** Get the minimum transfer function value.*/ + float getMinimum() const { return _colorMap.empty() ? 0.0f : _colorMap.begin()->first; } + + /** Get the maximum transfer function value.*/ + float getMaximum() const { return _colorMap.empty() ? 0.0f : _colorMap.rbegin()->first; } + + /** allocate the osg::Image with specified dimension. The Image tracks the color map, and is used to represent the + * transfer function when download to GPU.*/ + void allocate(unsigned int numImageCells); + + /** Clear the whole range to just represent a single color.*/ + void clear(const osg::Vec4& color = osg::Vec4(1.0f,1.0f,1.0f,1.0f)); + + /** Get pixel value from the image. */ + osg::Vec4 getPixelValue(unsigned int i) const + { + if (_image.valid() && i(_image->s())) + { + return *reinterpret_cast(_image->data(i)); + } + else + { + return osg::Vec4(1.0f,1.0f,1.0f,1.0f); + } + } + + /** Get the number of image cells that are assigned to the represent the transfer function when download to the GPU.*/ + unsigned int getNumberImageCells() const { return _image.valid() ? _image->s() : 0; } + + /** Set the color for a specified transfer function value. + * updateImage defaults to true, and tells the setColor function to update the associate osg::Image that + * tracks the color map. Pass in false as the updateImage parameter if you are setting up many values + * at once to avoid recomputation of the image data, then once all setColor calls are made explictly call + * updateImage() to bring the osg::Image back into sync with the color map. */ + void setColor(float v, const osg::Vec4& color, bool updateImage=true); + + /** Get the color for a specified transfer function value, interpolating the value if no exact match is found.*/ + osg::Vec4 getColor(float v) const; + + typedef std::map ColorMap; + + /** Get the color map that stores the mapping between the the transfer function value and the colour it maps to.*/ + ColorMap& getColorMap() { return _colorMap; } + + /** Get the const color map that stores the mapping between the the transfer function value and the colour it maps to.*/ + const ColorMap& getColorMap() const { return _colorMap; } + + /** Assign a color map and automatically update the image to make sure they are in sync.*/ + void assign(const ColorMap& vcm); + + /** Manually update the associate osg::Image to represent the colors assigned in the color map.*/ + void updateImage(); + + protected: + + ColorMap _colorMap; + + void assignToImage(float lower_v, const osg::Vec4& lower_c, float upper_v, const osg::Vec4& upper_c); +}; + +} + +#endif diff --git a/libs/include/android/osg/Transform b/libs/include/android/osg/Transform new file mode 100755 index 0000000..f8f20ce --- /dev/null +++ b/libs/include/android/osg/Transform @@ -0,0 +1,167 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_TRANSFORM +#define OSG_TRANSFORM 1 + +#include +#include + +#ifndef GL_RESCALE_NORMAL +#define GL_RESCALE_NORMAL 0x803A +#endif + +#ifndef GL_NORMALIZE +#define GL_NORMALIZE 0x0BA1 +#endif + +namespace osg { + + + +/** Compute the matrix which transforms objects in local coords to world coords, + * by accumulating the Transform local to world matrices along the specified node path. +*/ +extern OSG_EXPORT Matrix computeLocalToWorld(const NodePath& nodePath, bool ignoreCameras = true); + +/** Compute the matrix which transforms objects in world coords to local coords, + * by accumulating the Transform world to local matrices along the specified node path. +*/ +extern OSG_EXPORT Matrix computeWorldToLocal(const NodePath& nodePath, bool ignoreCameras = true); + +/** Compute the matrix which transforms objects in local coords to eye coords, + * by accumulating the Transform local to world matrices along the specified node path + * and multiplying by the supplied initial camera modelview. +*/ +extern OSG_EXPORT Matrix computeLocalToEye(const Matrix& modelview, const NodePath& nodePath, bool ignoreCameras = true); + +/** Compute the matrix which transforms objects in eye coords to local coords, + * by accumulating the Transform world to local matrices along the specified node path + * and multiplying by the inverse of the supplied initial camera modelview. +*/ +extern OSG_EXPORT Matrix computeEyeToLocal(const Matrix& modelview, const NodePath& nodePath, bool ignoreCameras = true); + + +/** A Transform is a group node for which all children are transformed by + * a 4x4 matrix. It is often used for positioning objects within a scene, + * producing trackball functionality or for animation. + * + * Transform itself does not provide set/get functions, only the interface + * for defining what the 4x4 transformation is. Subclasses, such as + * MatrixTransform and PositionAttitudeTransform support the use of an + * osg::Matrix or a osg::Vec3/osg::Quat respectively. + * + * Note: If the transformation matrix scales the subgraph then the normals + * of the underlying geometry will need to be renormalized to be unit + * vectors once more. This can be done transparently through OpenGL's + * use of either GL_NORMALIZE and GL_RESCALE_NORMAL modes. For further + * background reading see the glNormalize documentation in the OpenGL + * Reference Guide (the blue book). To enable it in the OSG, you simply + * need to attach a local osg::StateSet to the osg::Transform, and set + * the appropriate mode to ON via + * stateset->setMode(GL_NORMALIZE, osg::StateAttribute::ON); +*/ +class OSG_EXPORT Transform : public Group +{ + public : + + Transform(); + + /** Copy constructor using CopyOp to manage deep vs shallow copy. */ + Transform(const Transform&,const CopyOp& copyop=CopyOp::SHALLOW_COPY); + + META_Node(osg, Transform); + + virtual Transform* asTransform() { return this; } + virtual const Transform* asTransform() const { return this; } + + virtual MatrixTransform* asMatrixTransform() { return 0; } + virtual const MatrixTransform* asMatrixTransform() const { return 0; } + + virtual PositionAttitudeTransform* asPositionAttitudeTransform() { return 0; } + virtual const PositionAttitudeTransform* asPositionAttitudeTransform() const { return 0; } + + enum ReferenceFrame + { + RELATIVE_RF, + ABSOLUTE_RF, + ABSOLUTE_RF_INHERIT_VIEWPOINT + }; + + /** Set the transform's ReferenceFrame, either to be relative to its + * parent reference frame, or relative to an absolute coordinate + * frame. RELATIVE_RF is the default. + * Note: Setting the ReferenceFrame to be ABSOLUTE_RF will + * also set the CullingActive flag on the transform, and hence all + * of its parents, to false, thereby disabling culling of it and + * all its parents. This is necessary to prevent inappropriate + * culling, but may impact cull times if the absolute transform is + * deep in the scene graph. It is therefore recommended to only use + * absolute Transforms at the top of the scene, for such things as + * heads up displays. + * ABSOLUTE_RF_INHERIT_VIEWPOINT is the same as ABSOLUTE_RF except it + * adds the ability to use the parents view points position in world coordinates + * as its local viewpoint in the new coordinates frame. This is useful for + * Render to texture Cameras that wish to use the main views LOD range computation + * (which uses the viewpoint rather than the eye point) rather than use the local + * eye point defined by the this Transforms' absolute view matrix. + */ + void setReferenceFrame(ReferenceFrame rf); + + ReferenceFrame getReferenceFrame() const { return _referenceFrame; } + + virtual bool computeLocalToWorldMatrix(Matrix& matrix,NodeVisitor*) const + { + if (_referenceFrame==RELATIVE_RF) + { + return false; + } + else // absolute + { + matrix.makeIdentity(); + return true; + } + } + + virtual bool computeWorldToLocalMatrix(Matrix& matrix,NodeVisitor*) const + { + if (_referenceFrame==RELATIVE_RF) + { + return false; + } + else // absolute + { + matrix.makeIdentity(); + return true; + } + } + + /** Overrides Group's computeBound. + * There is no need to override in subclasses from osg::Transform + * since this computeBound() uses the underlying matrix (calling + * computeMatrix if required). + */ + virtual BoundingSphere computeBound() const; + + protected : + + virtual ~Transform(); + + + ReferenceFrame _referenceFrame; + +}; + +} + +#endif diff --git a/libs/include/android/osg/TriangleFunctor b/libs/include/android/osg/TriangleFunctor new file mode 100755 index 0000000..a60af09 --- /dev/null +++ b/libs/include/android/osg/TriangleFunctor @@ -0,0 +1,397 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_TRIANGLEFUNCTOR +#define OSG_TRIANGLEFUNCTOR 1 + +#include +#include + +namespace osg { + + +/** Provides access to the triangles that compose an \c osg::Drawable. If the \c + * Drawable is not composed of triangles, the \c TriangleFunctor will convert + * the primitives to triangles whenever possible. + *

Notice that \c TriangleFunctor is a class template, and that it inherits + * from its template parameter \c T. This template parameter must implement + * T::operator() (const osg::Vec3 v1, const osg::Vec3 v2, const osg::Vec3 + * v3, bool treatVertexDataAsTemporary), which will be called for every + * triangle when the functor is applied to a \c Drawable. Parameters \c v1, \c + * v2, and \c v3 are the triangle vertices. The fourth parameter, \c + * treatVertexDataAsTemporary, indicates whether these vertices are coming from + * a "real" vertex array, or from a temporary vertex array, created by the \c + * TriangleFunctor from some other geometry representation. + * @see \c PrimitiveFunctor for general usage hints. + */ +template +class TriangleFunctor : public PrimitiveFunctor, public T +{ +public: + + TriangleFunctor() + { + _vertexArraySize=0; + _vertexArrayPtr=0; + _modeCache=0; + _treatVertexDataAsTemporary=false; + } + + virtual ~TriangleFunctor() {} + + void setTreatVertexDataAsTemporary(bool treatVertexDataAsTemporary) { _treatVertexDataAsTemporary=treatVertexDataAsTemporary; } + bool getTreatVertexDataAsTemporary() const { return _treatVertexDataAsTemporary; } + + virtual void setVertexArray(unsigned int,const Vec2*) + { + notify(WARN)<<"Triangle Functor does not support Vec2* vertex arrays"<operator()(*(vptr),*(vptr+1),*(vptr+2),_treatVertexDataAsTemporary); + break; + } + case(GL_TRIANGLE_STRIP): + { + const Vec3* vptr = &_vertexArrayPtr[first]; + for(GLsizei i=2;ioperator()(*(vptr),*(vptr+2),*(vptr+1),_treatVertexDataAsTemporary); + else this->operator()(*(vptr),*(vptr+1),*(vptr+2),_treatVertexDataAsTemporary); + } + break; + } + case(GL_QUADS): + { + const Vec3* vptr = &_vertexArrayPtr[first]; + for(GLsizei i=3;ioperator()(*(vptr),*(vptr+1),*(vptr+2),_treatVertexDataAsTemporary); + this->operator()(*(vptr),*(vptr+2),*(vptr+3),_treatVertexDataAsTemporary); + } + break; + } + case(GL_QUAD_STRIP): + { + const Vec3* vptr = &_vertexArrayPtr[first]; + for(GLsizei i=3;ioperator()(*(vptr),*(vptr+1),*(vptr+2),_treatVertexDataAsTemporary); + this->operator()(*(vptr+1),*(vptr+3),*(vptr+2),_treatVertexDataAsTemporary); + } + break; + } + case(GL_POLYGON): // treat polygons as GL_TRIANGLE_FAN + case(GL_TRIANGLE_FAN): + { + const Vec3* vfirst = &_vertexArrayPtr[first]; + const Vec3* vptr = vfirst+1; + for(GLsizei i=2;ioperator()(*(vfirst),*(vptr),*(vptr+1),_treatVertexDataAsTemporary); + } + break; + } + case(GL_POINTS): + case(GL_LINES): + case(GL_LINE_STRIP): + case(GL_LINE_LOOP): + default: + // can't be converted into to triangles. + break; + } + } + + virtual void drawElements(GLenum mode,GLsizei count,const GLubyte* indices) + { + if (indices==0 || count==0) return; + + typedef const GLubyte* IndexPointer; + + switch(mode) + { + case(GL_TRIANGLES): + { + IndexPointer ilast = &indices[count]; + for(IndexPointer iptr=indices;iptroperator()(_vertexArrayPtr[*iptr],_vertexArrayPtr[*(iptr+1)],_vertexArrayPtr[*(iptr+2)],_treatVertexDataAsTemporary); + break; + } + case(GL_TRIANGLE_STRIP): + { + IndexPointer iptr = indices; + for(GLsizei i=2;ioperator()(_vertexArrayPtr[*(iptr)],_vertexArrayPtr[*(iptr+2)],_vertexArrayPtr[*(iptr+1)],_treatVertexDataAsTemporary); + else this->operator()(_vertexArrayPtr[*(iptr)],_vertexArrayPtr[*(iptr+1)],_vertexArrayPtr[*(iptr+2)],_treatVertexDataAsTemporary); + } + break; + } + case(GL_QUADS): + { + IndexPointer iptr = indices; + for(GLsizei i=3;ioperator()(_vertexArrayPtr[*(iptr)],_vertexArrayPtr[*(iptr+1)],_vertexArrayPtr[*(iptr+2)],_treatVertexDataAsTemporary); + this->operator()(_vertexArrayPtr[*(iptr)],_vertexArrayPtr[*(iptr+2)],_vertexArrayPtr[*(iptr+3)],_treatVertexDataAsTemporary); + } + break; + } + case(GL_QUAD_STRIP): + { + IndexPointer iptr = indices; + for(GLsizei i=3;ioperator()(_vertexArrayPtr[*(iptr)],_vertexArrayPtr[*(iptr+1)],_vertexArrayPtr[*(iptr+2)],_treatVertexDataAsTemporary); + this->operator()(_vertexArrayPtr[*(iptr+1)],_vertexArrayPtr[*(iptr+3)],_vertexArrayPtr[*(iptr+2)],_treatVertexDataAsTemporary); + } + break; + } + case(GL_POLYGON): // treat polygons as GL_TRIANGLE_FAN + case(GL_TRIANGLE_FAN): + { + IndexPointer iptr = indices; + const Vec3& vfirst = _vertexArrayPtr[*iptr]; + ++iptr; + for(GLsizei i=2;ioperator()(vfirst,_vertexArrayPtr[*(iptr)],_vertexArrayPtr[*(iptr+1)],_treatVertexDataAsTemporary); + } + break; + } + case(GL_POINTS): + case(GL_LINES): + case(GL_LINE_STRIP): + case(GL_LINE_LOOP): + default: + // can't be converted into to triangles. + break; + } + } + + virtual void drawElements(GLenum mode,GLsizei count,const GLushort* indices) + { + if (indices==0 || count==0) return; + + typedef const GLushort* IndexPointer; + + switch(mode) + { + case(GL_TRIANGLES): + { + IndexPointer ilast = &indices[count]; + for(IndexPointer iptr=indices;iptroperator()(_vertexArrayPtr[*iptr],_vertexArrayPtr[*(iptr+1)],_vertexArrayPtr[*(iptr+2)],_treatVertexDataAsTemporary); + } + break; + } + case(GL_TRIANGLE_STRIP): + { + IndexPointer iptr = indices; + for(GLsizei i=2;ioperator()(_vertexArrayPtr[*(iptr)],_vertexArrayPtr[*(iptr+2)],_vertexArrayPtr[*(iptr+1)],_treatVertexDataAsTemporary); + else this->operator()(_vertexArrayPtr[*(iptr)],_vertexArrayPtr[*(iptr+1)],_vertexArrayPtr[*(iptr+2)],_treatVertexDataAsTemporary); + } + break; + } + case(GL_QUADS): + { + IndexPointer iptr = indices; + for(GLsizei i=3;ioperator()(_vertexArrayPtr[*(iptr)],_vertexArrayPtr[*(iptr+1)],_vertexArrayPtr[*(iptr+2)],_treatVertexDataAsTemporary); + this->operator()(_vertexArrayPtr[*(iptr)],_vertexArrayPtr[*(iptr+2)],_vertexArrayPtr[*(iptr+3)],_treatVertexDataAsTemporary); + } + break; + } + case(GL_QUAD_STRIP): + { + IndexPointer iptr = indices; + for(GLsizei i=3;ioperator()(_vertexArrayPtr[*(iptr)],_vertexArrayPtr[*(iptr+1)],_vertexArrayPtr[*(iptr+2)],_treatVertexDataAsTemporary); + this->operator()(_vertexArrayPtr[*(iptr+1)],_vertexArrayPtr[*(iptr+3)],_vertexArrayPtr[*(iptr+2)],_treatVertexDataAsTemporary); + } + break; + } + case(GL_POLYGON): // treat polygons as GL_TRIANGLE_FAN + case(GL_TRIANGLE_FAN): + { + IndexPointer iptr = indices; + const Vec3& vfirst = _vertexArrayPtr[*iptr]; + ++iptr; + for(GLsizei i=2;ioperator()(vfirst,_vertexArrayPtr[*(iptr)],_vertexArrayPtr[*(iptr+1)],_treatVertexDataAsTemporary); + } + break; + } + case(GL_POINTS): + case(GL_LINES): + case(GL_LINE_STRIP): + case(GL_LINE_LOOP): + default: + // can't be converted into to triangles. + break; + } + } + + virtual void drawElements(GLenum mode,GLsizei count,const GLuint* indices) + { + if (indices==0 || count==0) return; + + typedef const GLuint* IndexPointer; + + switch(mode) + { + case(GL_TRIANGLES): + { + IndexPointer ilast = &indices[count]; + for(IndexPointer iptr=indices;iptroperator()(_vertexArrayPtr[*iptr],_vertexArrayPtr[*(iptr+1)],_vertexArrayPtr[*(iptr+2)],_treatVertexDataAsTemporary); + break; + } + case(GL_TRIANGLE_STRIP): + { + IndexPointer iptr = indices; + for(GLsizei i=2;ioperator()(_vertexArrayPtr[*(iptr)],_vertexArrayPtr[*(iptr+2)],_vertexArrayPtr[*(iptr+1)],_treatVertexDataAsTemporary); + else this->operator()(_vertexArrayPtr[*(iptr)],_vertexArrayPtr[*(iptr+1)],_vertexArrayPtr[*(iptr+2)],_treatVertexDataAsTemporary); + } + break; + } + case(GL_QUADS): + { + IndexPointer iptr = indices; + for(GLsizei i=3;ioperator()(_vertexArrayPtr[*(iptr)],_vertexArrayPtr[*(iptr+1)],_vertexArrayPtr[*(iptr+2)],_treatVertexDataAsTemporary); + this->operator()(_vertexArrayPtr[*(iptr)],_vertexArrayPtr[*(iptr+2)],_vertexArrayPtr[*(iptr+3)],_treatVertexDataAsTemporary); + } + break; + } + case(GL_QUAD_STRIP): + { + IndexPointer iptr = indices; + for(GLsizei i=3;ioperator()(_vertexArrayPtr[*(iptr)],_vertexArrayPtr[*(iptr+1)],_vertexArrayPtr[*(iptr+2)],_treatVertexDataAsTemporary); + this->operator()(_vertexArrayPtr[*(iptr+1)],_vertexArrayPtr[*(iptr+3)],_vertexArrayPtr[*(iptr+2)],_treatVertexDataAsTemporary); + } + break; + } + case(GL_POLYGON): // treat polygons as GL_TRIANGLE_FAN + case(GL_TRIANGLE_FAN): + { + IndexPointer iptr = indices; + const Vec3& vfirst = _vertexArrayPtr[*iptr]; + ++iptr; + for(GLsizei i=2;ioperator()(vfirst,_vertexArrayPtr[*(iptr)],_vertexArrayPtr[*(iptr+1)],_treatVertexDataAsTemporary); + } + break; + } + case(GL_POINTS): + case(GL_LINES): + case(GL_LINE_STRIP): + case(GL_LINE_LOOP): + default: + // can't be converted into to triangles. + break; + } + } + + + + /** Note: + * begin(..),vertex(..) & end() are convenience methods for adapting + * non vertex array primitives to vertex array based primitives. + * This is done to simplify the implementation of primitive functor + * subclasses - users only need override drawArray and drawElements. + */ + virtual void begin(GLenum mode) + { + _modeCache = mode; + _vertexCache.clear(); + } + + virtual void vertex(const Vec2& vert) { _vertexCache.push_back(osg::Vec3(vert[0],vert[1],0.0f)); } + virtual void vertex(const Vec3& vert) { _vertexCache.push_back(vert); } + virtual void vertex(const Vec4& vert) { _vertexCache.push_back(osg::Vec3(vert[0],vert[1],vert[2])/vert[3]); } + virtual void vertex(float x,float y) { _vertexCache.push_back(osg::Vec3(x,y,0.0f)); } + virtual void vertex(float x,float y,float z) { _vertexCache.push_back(osg::Vec3(x,y,z)); } + virtual void vertex(float x,float y,float z,float w) { _vertexCache.push_back(osg::Vec3(x,y,z)/w); } + virtual void end() + { + if (!_vertexCache.empty()) + { + setVertexArray(_vertexCache.size(),&_vertexCache.front()); + _treatVertexDataAsTemporary = true; + drawArrays(_modeCache,0,_vertexCache.size()); + } + } + +protected: + + + unsigned int _vertexArraySize; + const Vec3* _vertexArrayPtr; + + GLenum _modeCache; + std::vector _vertexCache; + bool _treatVertexDataAsTemporary; +}; + + +} + +#endif diff --git a/libs/include/android/osg/TriangleIndexFunctor b/libs/include/android/osg/TriangleIndexFunctor new file mode 100755 index 0000000..91926ef --- /dev/null +++ b/libs/include/android/osg/TriangleIndexFunctor @@ -0,0 +1,344 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_TRIANGLEINDEXFUNCTOR +#define OSG_TRIANGLEINDEXFUNCTOR 1 + +#include +#include + +namespace osg { + +template +class TriangleIndexFunctor : public PrimitiveIndexFunctor, public T +{ +public: + + + virtual void setVertexArray(unsigned int,const Vec2*) + { + } + + virtual void setVertexArray(unsigned int ,const Vec3* ) + { + } + + virtual void setVertexArray(unsigned int,const Vec4* ) + { + } + + virtual void setVertexArray(unsigned int,const Vec2d*) + { + } + + virtual void setVertexArray(unsigned int ,const Vec3d* ) + { + } + + virtual void setVertexArray(unsigned int,const Vec4d* ) + { + } + + virtual void begin(GLenum mode) + { + _modeCache = mode; + _indexCache.clear(); + } + + virtual void vertex(unsigned int vert) + { + _indexCache.push_back(vert); + } + + virtual void end() + { + if (!_indexCache.empty()) + { + drawElements(_modeCache,_indexCache.size(),&_indexCache.front()); + } + } + + virtual void drawArrays(GLenum mode,GLint first,GLsizei count) + { + switch(mode) + { + case(GL_TRIANGLES): + { + unsigned int pos=first; + for(GLsizei i=2;ioperator()(pos,pos+1,pos+2); + } + break; + } + case(GL_TRIANGLE_STRIP): + { + unsigned int pos=first; + for(GLsizei i=2;ioperator()(pos,pos+2,pos+1); + else this->operator()(pos,pos+1,pos+2); + } + break; + } + case(GL_QUADS): + { + unsigned int pos=first; + for(GLsizei i=3;ioperator()(pos,pos+1,pos+2); + this->operator()(pos,pos+2,pos+3); + } + break; + } + case(GL_QUAD_STRIP): + { + unsigned int pos=first; + for(GLsizei i=3;ioperator()(pos,pos+1,pos+2); + this->operator()(pos+1,pos+3,pos+2); + } + break; + } + case(GL_POLYGON): // treat polygons as GL_TRIANGLE_FAN + case(GL_TRIANGLE_FAN): + { + unsigned int pos=first+1; + for(GLsizei i=2;ioperator()(first,pos,pos+1); + } + break; + } + case(GL_POINTS): + case(GL_LINES): + case(GL_LINE_STRIP): + case(GL_LINE_LOOP): + default: + // can't be converted into to triangles. + break; + } + } + + virtual void drawElements(GLenum mode,GLsizei count,const GLubyte* indices) + { + if (indices==0 || count==0) return; + + typedef GLubyte Index; + typedef const Index* IndexPointer; + + switch(mode) + { + case(GL_TRIANGLES): + { + IndexPointer ilast = &indices[count]; + for(IndexPointer iptr=indices;iptroperator()(*iptr,*(iptr+1),*(iptr+2)); + break; + } + case(GL_TRIANGLE_STRIP): + { + IndexPointer iptr = indices; + for(GLsizei i=2;ioperator()(*(iptr),*(iptr+2),*(iptr+1)); + else this->operator()(*(iptr),*(iptr+1),*(iptr+2)); + } + break; + } + case(GL_QUADS): + { + IndexPointer iptr = indices; + for(GLsizei i=3;ioperator()(*(iptr),*(iptr+1),*(iptr+2)); + this->operator()(*(iptr),*(iptr+2),*(iptr+3)); + } + break; + } + case(GL_QUAD_STRIP): + { + IndexPointer iptr = indices; + for(GLsizei i=3;ioperator()(*(iptr),*(iptr+1),*(iptr+2)); + this->operator()(*(iptr+1),*(iptr+3),*(iptr+2)); + } + break; + } + case(GL_POLYGON): // treat polygons as GL_TRIANGLE_FAN + case(GL_TRIANGLE_FAN): + { + IndexPointer iptr = indices; + Index first = *iptr; + ++iptr; + for(GLsizei i=2;ioperator()(first,*(iptr),*(iptr+1)); + } + break; + } + case(GL_POINTS): + case(GL_LINES): + case(GL_LINE_STRIP): + case(GL_LINE_LOOP): + default: + // can't be converted into to triangles. + break; + } + } + + virtual void drawElements(GLenum mode,GLsizei count,const GLushort* indices) + { + if (indices==0 || count==0) return; + + typedef GLushort Index; + typedef const Index* IndexPointer; + + switch(mode) + { + case(GL_TRIANGLES): + { + IndexPointer ilast = &indices[count]; + for(IndexPointer iptr=indices;iptroperator()(*iptr,*(iptr+1),*(iptr+2)); + break; + } + case(GL_TRIANGLE_STRIP): + { + IndexPointer iptr = indices; + for(GLsizei i=2;ioperator()(*(iptr),*(iptr+2),*(iptr+1)); + else this->operator()(*(iptr),*(iptr+1),*(iptr+2)); + } + break; + } + case(GL_QUADS): + { + IndexPointer iptr = indices; + for(GLsizei i=3;ioperator()(*(iptr),*(iptr+1),*(iptr+2)); + this->operator()(*(iptr),*(iptr+2),*(iptr+3)); + } + break; + } + case(GL_QUAD_STRIP): + { + IndexPointer iptr = indices; + for(GLsizei i=3;ioperator()(*(iptr),*(iptr+1),*(iptr+2)); + this->operator()(*(iptr+1),*(iptr+3),*(iptr+2)); + } + break; + } + case(GL_POLYGON): // treat polygons as GL_TRIANGLE_FAN + case(GL_TRIANGLE_FAN): + { + IndexPointer iptr = indices; + Index first = *iptr; + ++iptr; + for(GLsizei i=2;ioperator()(first,*(iptr),*(iptr+1)); + } + break; + } + case(GL_POINTS): + case(GL_LINES): + case(GL_LINE_STRIP): + case(GL_LINE_LOOP): + default: + // can't be converted into to triangles. + break; + } + } + + virtual void drawElements(GLenum mode,GLsizei count,const GLuint* indices) + { + if (indices==0 || count==0) return; + + typedef GLuint Index; + typedef const Index* IndexPointer; + + switch(mode) + { + case(GL_TRIANGLES): + { + IndexPointer ilast = &indices[count]; + for(IndexPointer iptr=indices;iptroperator()(*iptr,*(iptr+1),*(iptr+2)); + break; + } + case(GL_TRIANGLE_STRIP): + { + IndexPointer iptr = indices; + for(GLsizei i=2;ioperator()(*(iptr),*(iptr+2),*(iptr+1)); + else this->operator()(*(iptr),*(iptr+1),*(iptr+2)); + } + break; + } + case(GL_QUADS): + { + IndexPointer iptr = indices; + for(GLsizei i=3;ioperator()(*(iptr),*(iptr+1),*(iptr+2)); + this->operator()(*(iptr),*(iptr+2),*(iptr+3)); + } + break; + } + case(GL_QUAD_STRIP): + { + IndexPointer iptr = indices; + for(GLsizei i=3;ioperator()(*(iptr),*(iptr+1),*(iptr+2)); + this->operator()(*(iptr+1),*(iptr+3),*(iptr+2)); + } + break; + } + case(GL_POLYGON): // treat polygons as GL_TRIANGLE_FAN + case(GL_TRIANGLE_FAN): + { + IndexPointer iptr = indices; + Index first = *iptr; + ++iptr; + for(GLsizei i=2;ioperator()(first,*(iptr),*(iptr+1)); + } + break; + } + case(GL_POINTS): + case(GL_LINES): + case(GL_LINE_STRIP): + case(GL_LINE_LOOP): + default: + // can't be converted into to triangles. + break; + } + } + + GLenum _modeCache; + std::vector _indexCache; +}; + +} + +#endif diff --git a/libs/include/android/osg/Uniform b/libs/include/android/osg/Uniform new file mode 100755 index 0000000..f7dbab4 --- /dev/null +++ b/libs/include/android/osg/Uniform @@ -0,0 +1,934 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * Copyright (C) 2003-2005 3Dlabs Inc. Ltd. + * Copyright (C) 2008 Zebra Imaging + * Copyright (C) 2012 David Callu + * + * This application is open source and may be redistributed and/or modified + * freely and without restriction, both in commercial and non commercial + * applications, as long as this copyright notice is maintained. + * + * This application is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. +*/ + +/* file: include/osg/Uniform + * author: Mike Weiblen 2008-01-02 +*/ + +#ifndef OSG_UNIFORM +#define OSG_UNIFORM 1 + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include // for memset +#include +#include + + +namespace osg { + +// forward declare +class NodeVisitor; + +/////////////////////////////////////////////////////////////////////////// +// C++ classes to represent the GLSL-specific types. +// +// Warning : +// OSG is Row major +// GLSL is Column Major +// +// If you define an Uniform with type Uniform::FLOAT_MAT4X2 and so use a Matrix4x2 to setup your Uniform, +// like this : +// 1 2 +// 3 4 +// 5 6 +// 7 8 +// +// you will get in your shader a Column Major Matrix like this : +// 1 3 5 7 +// 2 4 6 8 +// +// In simple term, you matrix in OSG will be a transposed matrix in GLSL +// +// +// You can avoid this behaviours starting GLSL version 1.40 with uniform layout : +// +// +// layout(row_major) uniform matrix4x2 myVariable; +// +// +// +template +class MatrixTemplate +{ + public: + enum { col_count = ColN }; + enum { row_count = RowN }; + enum { value_count = ColN * RowN }; + + typedef T value_type; + + + public: + MatrixTemplate() {} + ~MatrixTemplate() {} + + value_type& operator()(int row, int col) { return _mat[row][col]; } + value_type operator()(int row, int col) const { return _mat[row][col]; } + + MatrixTemplate& operator = (const MatrixTemplate& rhs) + { + if( &rhs == this ) return *this; + set(rhs.ptr()); + return *this; + } + + void set(const MatrixTemplate& rhs) { set(rhs.ptr()); } + + void set(value_type const * const ptr) + { + value_type* local_ptr = (value_type*)_mat; + for(int i=0;i +class Matrix2Template : public MatrixTemplate +{ + public: + typedef MatrixTemplate base_class; + typedef typename base_class::value_type value_type; + + + public: + Matrix2Template() { makeIdentity(); } + Matrix2Template( const Matrix2Template& mat ) { set(mat.ptr()); } + Matrix2Template( value_type a00, value_type a01, + value_type a10, value_type a11 ) + { + set( a00, a01, + a10, a11 ); + } + ~Matrix2Template() {} + + using base_class::set; + + void set(value_type a00, value_type a01, + value_type a10, value_type a11 ) + { + base_class::_mat[0][0]=a00; base_class::_mat[0][1]=a01; + base_class::_mat[1][0]=a10; base_class::_mat[1][1]=a11; + } + + void makeIdentity() + { + set( 1, 0, + 0, 1 ); + } +}; + +template +class Matrix2x3Template : public MatrixTemplate +{ + public: + typedef MatrixTemplate base_class; + typedef typename base_class::value_type value_type; + + + public: + Matrix2x3Template() { base_class::reset(); } + Matrix2x3Template( const Matrix2x3Template& mat ) { set(mat.ptr()); } + Matrix2x3Template( value_type a00, value_type a01, value_type a02, + value_type a10, value_type a11, value_type a12 ) + { + set( a00, a01, a02, + a10, a11, a12 ); + } + ~Matrix2x3Template() {} + + using base_class::set; + + void set( value_type a00, value_type a01, value_type a02, + value_type a10, value_type a11, value_type a12 ) + { + base_class::_mat[0][0]=a00; base_class::_mat[0][1]=a01; base_class::_mat[0][2]=a02; + base_class::_mat[1][0]=a10; base_class::_mat[1][1]=a11; base_class::_mat[1][2]=a12; + } +}; + +template +class Matrix2x4Template : public MatrixTemplate +{ + public: + typedef MatrixTemplate base_class; + typedef typename base_class::value_type value_type; + + + public: + Matrix2x4Template() { base_class::reset(); } + Matrix2x4Template( const Matrix2x4Template& mat ) { set(mat.ptr()); } + Matrix2x4Template( value_type a00, value_type a01, value_type a02, value_type a03, + value_type a10, value_type a11, value_type a12, value_type a13 ) + { + set( a00, a01, a02, a03, + a10, a11, a12, a13 ); + } + ~Matrix2x4Template() {} + + using base_class::set; + + void set( value_type a00, value_type a01, value_type a02, value_type a03, + value_type a10, value_type a11, value_type a12, value_type a13 ) + { + base_class::_mat[0][0]=a00; base_class::_mat[0][1]=a01; base_class::_mat[0][2]=a02; base_class::_mat[0][3]=a03; + base_class::_mat[1][0]=a10; base_class::_mat[1][1]=a11; base_class::_mat[1][2]=a12; base_class::_mat[1][3]=a13; + } +}; + +template +class Matrix3x2Template : public MatrixTemplate +{ + public: + typedef MatrixTemplate base_class; + typedef typename base_class::value_type value_type; + + public: + Matrix3x2Template() { base_class::reset(); } + Matrix3x2Template( const Matrix3x2Template& mat ) { set(mat.ptr()); } + Matrix3x2Template( value_type a00, value_type a01, + value_type a10, value_type a11, + value_type a20, value_type a21 ) + { + set( a00, a01, + a10, a11, + a20, a21 ); + } + ~Matrix3x2Template() {} + + using base_class::set; + + void set( value_type a00, value_type a01, + value_type a10, value_type a11, + value_type a20, value_type a21 ) + { + base_class::_mat[0][0]=a00; base_class::_mat[0][1]=a01; + base_class::_mat[1][0]=a10; base_class::_mat[1][1]=a11; + base_class::_mat[2][0]=a20; base_class::_mat[2][1]=a21; + } +}; + +template +class Matrix3Template : public MatrixTemplate +{ + public: + typedef MatrixTemplate base_class; + typedef typename base_class::value_type value_type; + + public: + Matrix3Template() { base_class::reset(); } + Matrix3Template( const Matrix3Template& mat ) { set(mat.ptr()); } + Matrix3Template( value_type a00, value_type a01, value_type a02, + value_type a10, value_type a11, value_type a12, + value_type a20, value_type a21, value_type a22 ) + { + set( a00, a01, a02, + a10, a11, a12, + a20, a21, a22 ); + } + ~Matrix3Template() {} + + using base_class::set; + + void set( value_type a00, value_type a01, value_type a02, + value_type a10, value_type a11, value_type a12, + value_type a20, value_type a21, value_type a22 ) + { + base_class::_mat[0][0]=a00; base_class::_mat[0][1]=a01; base_class::_mat[0][2]=a02; + base_class::_mat[1][0]=a10; base_class::_mat[1][1]=a11; base_class::_mat[1][2]=a12; + base_class::_mat[2][0]=a20; base_class::_mat[2][1]=a21; base_class::_mat[2][2]=a22; + } + + void makeIdentity() + { + set( 1, 0, 0, + 0, 1, 0, + 0, 0, 1 ); + } +}; + +template +class Matrix3x4Template : public MatrixTemplate +{ + public: + typedef MatrixTemplate base_class; + typedef typename base_class::value_type value_type; + + public: + Matrix3x4Template() { base_class::reset(); } + Matrix3x4Template( const Matrix3x4Template& mat ) { set(mat.ptr()); } + Matrix3x4Template( value_type a00, value_type a01, value_type a02, value_type a03, + value_type a10, value_type a11, value_type a12, value_type a13, + value_type a20, value_type a21, value_type a22, value_type a23 ) + { + set( a00, a01, a02, a03, + a10, a11, a12, a13, + a20, a21, a22, a23 ); + } + ~Matrix3x4Template() {} + + using base_class::set; + + void set( value_type a00, value_type a01, value_type a02, value_type a03, + value_type a10, value_type a11, value_type a12, value_type a13, + value_type a20, value_type a21, value_type a22, value_type a23 ) + { + base_class::_mat[0][0]=a00; base_class::_mat[0][1]=a01; base_class::_mat[0][2]=a02; base_class::_mat[0][3]=a03; + base_class::_mat[1][0]=a10; base_class::_mat[1][1]=a11; base_class::_mat[1][2]=a12; base_class::_mat[1][3]=a13; + base_class::_mat[2][0]=a20; base_class::_mat[2][1]=a21; base_class::_mat[2][2]=a22; base_class::_mat[2][3]=a23; + } +}; + +template +class Matrix4x2Template : public MatrixTemplate +{ + public: + typedef MatrixTemplate base_class; + typedef typename base_class::value_type value_type; + + public: + Matrix4x2Template() { base_class::reset(); } + Matrix4x2Template( const Matrix4x2Template& mat ) { set(mat.ptr()); } + Matrix4x2Template( value_type a00, value_type a01, + value_type a10, value_type a11, + value_type a20, value_type a21, + value_type a30, value_type a31 ) + { + set( a00, a01, + a10, a11, + a20, a21, + a30, a31 ); + } + ~Matrix4x2Template() {} + + using base_class::set; + + void set( value_type a00, value_type a01, + value_type a10, value_type a11, + value_type a20, value_type a21, + value_type a30, value_type a31 ) + { + base_class::_mat[0][0]=a00; base_class::_mat[0][1]=a01; + base_class::_mat[1][0]=a10; base_class::_mat[1][1]=a11; + base_class::_mat[2][0]=a20; base_class::_mat[2][1]=a21; + base_class::_mat[3][0]=a30; base_class::_mat[3][1]=a31; + } +}; + +template +class Matrix4x3Template : public MatrixTemplate +{ + public: + typedef MatrixTemplate base_class; + typedef typename base_class::value_type value_type; + + public: + Matrix4x3Template() { base_class::reset(); } + Matrix4x3Template( const Matrix4x3Template& mat ) { set(mat.ptr()); } + Matrix4x3Template( value_type a00, value_type a01, value_type a02, + value_type a10, value_type a11, value_type a12, + value_type a20, value_type a21, value_type a22, + value_type a30, value_type a31, value_type a32 ) + { + set( a00, a01, a02, + a10, a11, a12, + a20, a21, a22, + a30, a31, a32 ); + } + ~Matrix4x3Template() {} + + using base_class::set; + + void set( value_type a00, value_type a01, value_type a02, + value_type a10, value_type a11, value_type a12, + value_type a20, value_type a21, value_type a22, + value_type a30, value_type a31, value_type a32 ) + { + base_class::_mat[0][0]=a00; base_class::_mat[0][1]=a01; base_class::_mat[0][2]=a02; + base_class::_mat[1][0]=a10; base_class::_mat[1][1]=a11; base_class::_mat[1][2]=a12; + base_class::_mat[2][0]=a20; base_class::_mat[2][1]=a21; base_class::_mat[2][2]=a22; + base_class::_mat[3][0]=a30; base_class::_mat[3][1]=a31; base_class::_mat[3][2]=a32; + } +}; + +typedef Matrix2Template Matrix2; +typedef Matrix2x3Template Matrix2x3; +typedef Matrix2x4Template Matrix2x4; + +typedef Matrix3x2Template Matrix3x2; +typedef Matrix3Template Matrix3; +typedef Matrix3x4Template Matrix3x4; + +typedef Matrix4x2Template Matrix4x2; +typedef Matrix4x3Template Matrix4x3; + + +typedef Matrix2Template Matrix2d; +typedef Matrix2x3Template Matrix2x3d; +typedef Matrix2x4Template Matrix2x4d; + +typedef Matrix3x2Template Matrix3x2d; +typedef Matrix3Template Matrix3d; +typedef Matrix3x4Template Matrix3x4d; + +typedef Matrix4x2Template Matrix4x2d; +typedef Matrix4x3Template Matrix4x3d; + + + +/////////////////////////////////////////////////////////////////////////// + +/** Uniform encapsulates glUniform values */ +class OSG_EXPORT Uniform : public Object +{ + public: + enum Type { + FLOAT = GL_FLOAT, + FLOAT_VEC2 = GL_FLOAT_VEC2, + FLOAT_VEC3 = GL_FLOAT_VEC3, + FLOAT_VEC4 = GL_FLOAT_VEC4, + + DOUBLE = GL_DOUBLE, + DOUBLE_VEC2 = GL_DOUBLE_VEC2, + DOUBLE_VEC3 = GL_DOUBLE_VEC3, + DOUBLE_VEC4 = GL_DOUBLE_VEC4, + + INT = GL_INT, + INT_VEC2 = GL_INT_VEC2, + INT_VEC3 = GL_INT_VEC3, + INT_VEC4 = GL_INT_VEC4, + + UNSIGNED_INT = GL_UNSIGNED_INT, + UNSIGNED_INT_VEC2 = GL_UNSIGNED_INT_VEC2_EXT, + UNSIGNED_INT_VEC3 = GL_UNSIGNED_INT_VEC3_EXT, + UNSIGNED_INT_VEC4 = GL_UNSIGNED_INT_VEC4_EXT, + + BOOL = GL_BOOL, + BOOL_VEC2 = GL_BOOL_VEC2, + BOOL_VEC3 = GL_BOOL_VEC3, + BOOL_VEC4 = GL_BOOL_VEC4, + + FLOAT_MAT2 = GL_FLOAT_MAT2, + FLOAT_MAT3 = GL_FLOAT_MAT3, + FLOAT_MAT4 = GL_FLOAT_MAT4, + FLOAT_MAT2x3 = GL_FLOAT_MAT2x3, + FLOAT_MAT2x4 = GL_FLOAT_MAT2x4, + FLOAT_MAT3x2 = GL_FLOAT_MAT3x2, + FLOAT_MAT3x4 = GL_FLOAT_MAT3x4, + FLOAT_MAT4x2 = GL_FLOAT_MAT4x2, + FLOAT_MAT4x3 = GL_FLOAT_MAT4x3, + + DOUBLE_MAT2 = GL_DOUBLE_MAT2, + DOUBLE_MAT3 = GL_DOUBLE_MAT3, + DOUBLE_MAT4 = GL_DOUBLE_MAT4, + DOUBLE_MAT2x3 = GL_DOUBLE_MAT2x3, + DOUBLE_MAT2x4 = GL_DOUBLE_MAT2x4, + DOUBLE_MAT3x2 = GL_DOUBLE_MAT3x2, + DOUBLE_MAT3x4 = GL_DOUBLE_MAT3x4, + DOUBLE_MAT4x2 = GL_DOUBLE_MAT4x2, + DOUBLE_MAT4x3 = GL_DOUBLE_MAT4x3, + + SAMPLER_1D = GL_SAMPLER_1D, + SAMPLER_2D = GL_SAMPLER_2D, + SAMPLER_3D = GL_SAMPLER_3D, + SAMPLER_CUBE = GL_SAMPLER_CUBE, + SAMPLER_1D_SHADOW = GL_SAMPLER_1D_SHADOW, + SAMPLER_2D_SHADOW = GL_SAMPLER_2D_SHADOW, + SAMPLER_1D_ARRAY = GL_SAMPLER_1D_ARRAY_EXT, + SAMPLER_2D_ARRAY = GL_SAMPLER_2D_ARRAY_EXT, + SAMPLER_CUBE_MAP_ARRAY = GL_SAMPLER_CUBE_MAP_ARRAY, + SAMPLER_1D_ARRAY_SHADOW = GL_SAMPLER_1D_ARRAY_SHADOW_EXT, + SAMPLER_2D_ARRAY_SHADOW = GL_SAMPLER_2D_ARRAY_SHADOW_EXT, + SAMPLER_2D_MULTISAMPLE = GL_SAMPLER_2D_MULTISAMPLE, + SAMPLER_2D_MULTISAMPLE_ARRAY = GL_SAMPLER_2D_MULTISAMPLE_ARRAY, + SAMPLER_CUBE_SHADOW = GL_SAMPLER_CUBE_SHADOW_EXT, + SAMPLER_CUBE_MAP_ARRAY_SHADOW = GL_SAMPLER_CUBE_MAP_ARRAY_SHADOW, + SAMPLER_BUFFER = GL_SAMPLER_BUFFER_EXT, + SAMPLER_2D_RECT = GL_SAMPLER_2D_RECT, + SAMPLER_2D_RECT_SHADOW = GL_SAMPLER_2D_RECT_SHADOW, + + INT_SAMPLER_1D = GL_INT_SAMPLER_1D_EXT, + INT_SAMPLER_2D = GL_INT_SAMPLER_2D_EXT, + INT_SAMPLER_3D = GL_INT_SAMPLER_3D_EXT, + INT_SAMPLER_CUBE = GL_INT_SAMPLER_CUBE_EXT, + INT_SAMPLER_1D_ARRAY = GL_INT_SAMPLER_1D_ARRAY_EXT, + INT_SAMPLER_2D_ARRAY = GL_INT_SAMPLER_2D_ARRAY_EXT, + INT_SAMPLER_CUBE_MAP_ARRAY = GL_INT_SAMPLER_CUBE_MAP_ARRAY, + INT_SAMPLER_2D_MULTISAMPLE = GL_INT_SAMPLER_2D_MULTISAMPLE, + INT_SAMPLER_2D_MULTISAMPLE_ARRAY = GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY, + INT_SAMPLER_BUFFER = GL_INT_SAMPLER_BUFFER_EXT, + INT_SAMPLER_2D_RECT = GL_INT_SAMPLER_2D_RECT_EXT, + + UNSIGNED_INT_SAMPLER_1D = GL_UNSIGNED_INT_SAMPLER_1D_EXT, + UNSIGNED_INT_SAMPLER_2D = GL_UNSIGNED_INT_SAMPLER_2D_EXT, + UNSIGNED_INT_SAMPLER_3D = GL_UNSIGNED_INT_SAMPLER_3D_EXT, + UNSIGNED_INT_SAMPLER_CUBE = GL_UNSIGNED_INT_SAMPLER_CUBE_EXT, + UNSIGNED_INT_SAMPLER_1D_ARRAY = GL_UNSIGNED_INT_SAMPLER_1D_ARRAY_EXT, + UNSIGNED_INT_SAMPLER_2D_ARRAY = GL_UNSIGNED_INT_SAMPLER_2D_ARRAY_EXT, + UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAY = GL_UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAY, + UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE = GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE, + UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY = GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY, + UNSIGNED_INT_SAMPLER_BUFFER = GL_UNSIGNED_INT_SAMPLER_BUFFER_EXT, + UNSIGNED_INT_SAMPLER_2D_RECT = GL_UNSIGNED_INT_SAMPLER_2D_RECT_EXT, + + IMAGE_1D = GL_IMAGE_1D, + IMAGE_2D = GL_IMAGE_2D, + IMAGE_3D = GL_IMAGE_3D, + IMAGE_2D_RECT = GL_IMAGE_2D_RECT, + IMAGE_CUBE = GL_IMAGE_CUBE, + IMAGE_BUFFER = GL_IMAGE_BUFFER, + IMAGE_1D_ARRAY = GL_IMAGE_1D_ARRAY, + IMAGE_2D_ARRAY = GL_IMAGE_2D_ARRAY, + IMAGE_CUBE_MAP_ARRAY = GL_IMAGE_CUBE_MAP_ARRAY, + IMAGE_2D_MULTISAMPLE = GL_IMAGE_2D_MULTISAMPLE, + IMAGE_2D_MULTISAMPLE_ARRAY = GL_IMAGE_2D_MULTISAMPLE_ARRAY, + + INT_IMAGE_1D = GL_INT_IMAGE_1D, + INT_IMAGE_2D = GL_INT_IMAGE_2D, + INT_IMAGE_3D = GL_INT_IMAGE_3D, + INT_IMAGE_2D_RECT = GL_INT_IMAGE_2D_RECT, + INT_IMAGE_CUBE = GL_INT_IMAGE_CUBE, + INT_IMAGE_BUFFER = GL_INT_IMAGE_BUFFER, + INT_IMAGE_1D_ARRAY = GL_INT_IMAGE_1D_ARRAY, + INT_IMAGE_2D_ARRAY = GL_INT_IMAGE_2D_ARRAY, + INT_IMAGE_CUBE_MAP_ARRAY = GL_INT_IMAGE_CUBE_MAP_ARRAY, + INT_IMAGE_2D_MULTISAMPLE = GL_INT_IMAGE_2D_MULTISAMPLE, + INT_IMAGE_2D_MULTISAMPLE_ARRAY = GL_INT_IMAGE_2D_MULTISAMPLE_ARRAY, + + UNSIGNED_INT_IMAGE_1D = GL_UNSIGNED_INT_IMAGE_1D, + UNSIGNED_INT_IMAGE_2D = GL_UNSIGNED_INT_IMAGE_2D, + UNSIGNED_INT_IMAGE_3D = GL_UNSIGNED_INT_IMAGE_3D, + UNSIGNED_INT_IMAGE_2D_RECT = GL_UNSIGNED_INT_IMAGE_2D_RECT, + UNSIGNED_INT_IMAGE_CUBE = GL_UNSIGNED_INT_IMAGE_CUBE, + UNSIGNED_INT_IMAGE_BUFFER = GL_UNSIGNED_INT_IMAGE_BUFFER, + UNSIGNED_INT_IMAGE_1D_ARRAY = GL_UNSIGNED_INT_IMAGE_1D_ARRAY, + UNSIGNED_INT_IMAGE_2D_ARRAY = GL_UNSIGNED_INT_IMAGE_2D_ARRAY, + UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY = GL_UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY, + UNSIGNED_INT_IMAGE_2D_MULTISAMPLE = GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE, + UNSIGNED_INT_IMAGE_2D_MULTISAMPLE_ARRAY = GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE_ARRAY, + + UNDEFINED = 0x0 + }; + + public: + + Uniform(); + Uniform( Type type, const std::string& name, int numElements=1 ); + + /** Copy constructor using CopyOp to manage deep vs shallow copy. */ + Uniform(const Uniform& rhs, const CopyOp& copyop=CopyOp::SHALLOW_COPY); + + META_Object(osg, Uniform); + + + /** Set the type of glUniform, ensuring it is only set once.*/ + bool setType( Type t ); + + /** Get the type of glUniform as enum. */ + Type getType() const { return _type; } + + /** Set the name of the glUniform, ensuring it is only set once.*/ + virtual void setName( const std::string& name ); + + /** Set the length of a uniform, ensuring it is only set once (1==scalar)*/ + void setNumElements( unsigned int numElements ); + + /** Get the number of GLSL elements of the osg::Uniform (1==scalar) */ + unsigned int getNumElements() const { return _numElements; } + + /** Get the number of elements required for the internal data array. + * Returns 0 if the osg::Uniform is not properly configured. */ + unsigned int getInternalArrayNumElements() const; + + /** Return the name of a Type enum as string. */ + static const char* getTypename( Type t ); + + /** Return the the number of components for a GLSL type. */ + static int getTypeNumComponents( Type t ); + + /** Return the Type enum of a Uniform typename string */ + static Uniform::Type getTypeId( const std::string& tname ); + + /** Return the GL API type corresponding to a GLSL type */ + static Type getGlApiType( Type t ); + + /** Return the internal data array type corresponding to a GLSL type */ + static GLenum getInternalArrayType( Type t ); + + /** Return the number that the name maps to uniquely */ + static unsigned int getNameID(const std::string& name); + + /** convenient scalar (non-array) constructors w/ assignment */ + explicit Uniform( const char* name, float f ); + explicit Uniform( const char* name, double d ); + explicit Uniform( const char* name, int i ); + explicit Uniform( const char* name, unsigned int ui ); + explicit Uniform( const char* name, bool b ); + Uniform( const char* name, const osg::Vec2& v2 ); + Uniform( const char* name, const osg::Vec3& v3 ); + Uniform( const char* name, const osg::Vec4& v4 ); + Uniform( const char* name, const osg::Vec2d& v2 ); + Uniform( const char* name, const osg::Vec3d& v3 ); + Uniform( const char* name, const osg::Vec4d& v4 ); + Uniform( const char* name, const osg::Matrix2& m2 ); + Uniform( const char* name, const osg::Matrix3& m3 ); + Uniform( const char* name, const osg::Matrixf& m4 ); + Uniform( const char* name, const osg::Matrix2x3& m2x3 ); + Uniform( const char* name, const osg::Matrix2x4& m2x4 ); + Uniform( const char* name, const osg::Matrix3x2& m3x2 ); + Uniform( const char* name, const osg::Matrix3x4& m3x4 ); + Uniform( const char* name, const osg::Matrix4x2& m4x2 ); + Uniform( const char* name, const osg::Matrix4x3& m4x3 ); + Uniform( const char* name, const osg::Matrix2d& m2 ); + Uniform( const char* name, const osg::Matrix3d& m3 ); + Uniform( const char* name, const osg::Matrixd& m4 ); + Uniform( const char* name, const osg::Matrix2x3d& m2x3 ); + Uniform( const char* name, const osg::Matrix2x4d& m2x4 ); + Uniform( const char* name, const osg::Matrix3x2d& m3x2 ); + Uniform( const char* name, const osg::Matrix3x4d& m3x4 ); + Uniform( const char* name, const osg::Matrix4x2d& m4x2 ); + Uniform( const char* name, const osg::Matrix4x3d& m4x3 ); + Uniform( const char* name, int i0, int i1 ); + Uniform( const char* name, int i0, int i1, int i2 ); + Uniform( const char* name, int i0, int i1, int i2, int i3 ); + Uniform( const char* name, unsigned int ui0, unsigned int ui1 ); + Uniform( const char* name, unsigned int ui0, unsigned int ui1, unsigned int ui2 ); + Uniform( const char* name, unsigned int ui0, unsigned int ui1, unsigned int ui2, unsigned int ui3 ); + Uniform( const char* name, bool b0, bool b1 ); + Uniform( const char* name, bool b0, bool b1, bool b2 ); + Uniform( const char* name, bool b0, bool b1, bool b2, bool b3 ); + + /** return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs. */ + virtual int compare(const Uniform& rhs) const; + virtual int compareData(const Uniform& rhs) const; + + bool operator < (const Uniform& rhs) const { return compare(rhs)<0; } + bool operator == (const Uniform& rhs) const { return compare(rhs)==0; } + bool operator != (const Uniform& rhs) const { return compare(rhs)!=0; } + + void copyData( const Uniform& rhs ); + + + /** A vector of osg::StateSet pointers which is used to store the parent(s) of this Uniform, the parents could be osg::Node or osg::Drawable.*/ + typedef std::vector ParentList; + + /** Get the parent list of this Uniform. */ + inline const ParentList& getParents() const { return _parents; } + + /** Get the a copy of parent list of node. A copy is returned to + * prevent modification of the parent list.*/ + inline ParentList getParents() { return _parents; } + + inline StateSet* getParent(unsigned int i) { return _parents[i]; } + /** + * Get a single const parent of this Uniform. + * @param i index of the parent to get. + * @return the parent i. + */ + inline const StateSet* getParent(unsigned int i) const { return _parents[i]; } + + /** + * Get the number of parents of this Uniform. + * @return the number of parents of this Uniform. + */ + inline unsigned int getNumParents() const { return static_cast(_parents.size()); } + + + /** convenient scalar (non-array) value assignment */ + bool set( float f ); + bool set( double d ); + bool set( int i ); + bool set( unsigned int ui ); + bool set( bool b ); + bool set( const osg::Vec2& v2 ); + bool set( const osg::Vec3& v3 ); + bool set( const osg::Vec4& v4 ); + bool set( const osg::Vec2d& v2 ); + bool set( const osg::Vec3d& v3 ); + bool set( const osg::Vec4d& v4 ); + bool set( const osg::Matrix2& m2 ); + bool set( const osg::Matrix3& m3 ); + bool set( const osg::Matrixf& m4 ); + bool set( const osg::Matrix2x3& m2x3 ); + bool set( const osg::Matrix2x4& m2x4 ); + bool set( const osg::Matrix3x2& m3x2 ); + bool set( const osg::Matrix3x4& m3x4 ); + bool set( const osg::Matrix4x2& m4x2 ); + bool set( const osg::Matrix4x3& m4x3 ); + bool set( const osg::Matrix2d& m2 ); + bool set( const osg::Matrix3d& m3 ); + bool set( const osg::Matrixd& m4 ); + bool set( const osg::Matrix2x3d& m2x3 ); + bool set( const osg::Matrix2x4d& m2x4 ); + bool set( const osg::Matrix3x2d& m3x2 ); + bool set( const osg::Matrix3x4d& m3x4 ); + bool set( const osg::Matrix4x2d& m4x2 ); + bool set( const osg::Matrix4x3d& m4x3 ); + bool set( int i0, int i1 ); + bool set( int i0, int i1, int i2 ); + bool set( int i0, int i1, int i2, int i3 ); + bool set( unsigned int ui0, unsigned int ui1 ); + bool set( unsigned int ui0, unsigned int ui1, unsigned int ui2 ); + bool set( unsigned int ui0, unsigned int ui1, unsigned int ui2, unsigned int ui3 ); + bool set( bool b0, bool b1 ); + bool set( bool b0, bool b1, bool b2 ); + bool set( bool b0, bool b1, bool b2, bool b3 ); + + /** convenient scalar (non-array) value query */ + bool get( float& f ) const; + bool get( double& d ) const; + bool get( int& i ) const; + bool get( unsigned int& ui ) const; + bool get( bool& b ) const; + bool get( osg::Vec2& v2 ) const; + bool get( osg::Vec3& v3 ) const; + bool get( osg::Vec4& v4 ) const; + bool get( osg::Vec2d& v2 ) const; + bool get( osg::Vec3d& v3 ) const; + bool get( osg::Vec4d& v4 ) const; + bool get( osg::Matrix2& m2 ) const; + bool get( osg::Matrix3& m3 ) const; + bool get( osg::Matrixf& m4 ) const; + bool get( osg::Matrix2x3& m2x3 ) const; + bool get( osg::Matrix2x4& m2x4 ) const; + bool get( osg::Matrix3x2& m3x2 ) const; + bool get( osg::Matrix3x4& m3x4 ) const; + bool get( osg::Matrix4x2& m4x2 ) const; + bool get( osg::Matrix4x3& m4x3 ) const; + bool get( osg::Matrix2d& m2 ) const; + bool get( osg::Matrix3d& m3 ) const; + bool get( osg::Matrixd& m4 ) const; + bool get( osg::Matrix2x3d& m2x3 ) const; + bool get( osg::Matrix2x4d& m2x4 ) const; + bool get( osg::Matrix3x2d& m3x2 ) const; + bool get( osg::Matrix3x4d& m3x4 ) const; + bool get( osg::Matrix4x2d& m4x2 ) const; + bool get( osg::Matrix4x3d& m4x3 ) const; + bool get( int& i0, int& i1 ) const; + bool get( int& i0, int& i1, int& i2 ) const; + bool get( int& i0, int& i1, int& i2, int& i3 ) const; + bool get( unsigned int& ui0, unsigned int& ui1 ) const; + bool get( unsigned int& ui0, unsigned int& ui1, unsigned int& ui2 ) const; + bool get( unsigned int& ui0, unsigned int& ui1, unsigned int& ui2, unsigned int& ui3 ) const; + bool get( bool& b0, bool& b1 ) const; + bool get( bool& b0, bool& b1, bool& b2 ) const; + bool get( bool& b0, bool& b1, bool& b2, bool& b3 ) const; + + /** value assignment for array uniforms */ + bool setElement( unsigned int index, float f ); + bool setElement( unsigned int index, double d ); + bool setElement( unsigned int index, int i ); + bool setElement( unsigned int index, unsigned int ui ); + bool setElement( unsigned int index, bool b ); + bool setElement( unsigned int index, const osg::Vec2& v2 ); + bool setElement( unsigned int index, const osg::Vec3& v3 ); + bool setElement( unsigned int index, const osg::Vec4& v4 ); + bool setElement( unsigned int index, const osg::Vec2d& v2 ); + bool setElement( unsigned int index, const osg::Vec3d& v3 ); + bool setElement( unsigned int index, const osg::Vec4d& v4 ); + bool setElement( unsigned int index, const osg::Matrix2& m2 ); + bool setElement( unsigned int index, const osg::Matrix3& m3 ); + bool setElement( unsigned int index, const osg::Matrixf& m4 ); + bool setElement( unsigned int index, const osg::Matrix2x3& m2x3 ); + bool setElement( unsigned int index, const osg::Matrix2x4& m2x4 ); + bool setElement( unsigned int index, const osg::Matrix3x2& m3x2 ); + bool setElement( unsigned int index, const osg::Matrix3x4& m3x4 ); + bool setElement( unsigned int index, const osg::Matrix4x2& m4x2 ); + bool setElement( unsigned int index, const osg::Matrix4x3& m4x3 ); + bool setElement( unsigned int index, const osg::Matrix2d& m2 ); + bool setElement( unsigned int index, const osg::Matrix3d& m3 ); + bool setElement( unsigned int index, const osg::Matrixd& m4 ); + bool setElement( unsigned int index, const osg::Matrix2x3d& m2x3 ); + bool setElement( unsigned int index, const osg::Matrix2x4d& m2x4 ); + bool setElement( unsigned int index, const osg::Matrix3x2d& m3x2 ); + bool setElement( unsigned int index, const osg::Matrix3x4d& m3x4 ); + bool setElement( unsigned int index, const osg::Matrix4x2d& m4x2 ); + bool setElement( unsigned int index, const osg::Matrix4x3d& m4x3 ); + bool setElement( unsigned int index, int i0, int i1 ); + bool setElement( unsigned int index, int i0, int i1, int i2 ); + bool setElement( unsigned int index, int i0, int i1, int i2, int i3 ); + bool setElement( unsigned int index, unsigned int ui0, unsigned int ui1 ); + bool setElement( unsigned int index, unsigned int ui0, unsigned int ui1, unsigned int ui2 ); + bool setElement( unsigned int index, unsigned int ui0, unsigned int ui1, unsigned int ui2, unsigned int ui3 ); + bool setElement( unsigned int index, bool b0, bool b1 ); + bool setElement( unsigned int index, bool b0, bool b1, bool b2 ); + bool setElement( unsigned int index, bool b0, bool b1, bool b2, bool b3 ); + + /** value query for array uniforms */ + bool getElement( unsigned int index, float& f ) const; + bool getElement( unsigned int index, double& d ) const; + bool getElement( unsigned int index, int& i ) const; + bool getElement( unsigned int index, unsigned int& ui ) const; + bool getElement( unsigned int index, bool& b ) const; + bool getElement( unsigned int index, osg::Vec2& v2 ) const; + bool getElement( unsigned int index, osg::Vec3& v3 ) const; + bool getElement( unsigned int index, osg::Vec4& v4 ) const; + bool getElement( unsigned int index, osg::Vec2d& v2 ) const; + bool getElement( unsigned int index, osg::Vec3d& v3 ) const; + bool getElement( unsigned int index, osg::Vec4d& v4 ) const; + bool getElement( unsigned int index, osg::Matrix2& m2 ) const; + bool getElement( unsigned int index, osg::Matrix3& m3 ) const; + bool getElement( unsigned int index, osg::Matrixf& m4 ) const; + bool getElement( unsigned int index, osg::Matrix2x3& m2x3 ) const; + bool getElement( unsigned int index, osg::Matrix2x4& m2x4 ) const; + bool getElement( unsigned int index, osg::Matrix3x2& m3x2 ) const; + bool getElement( unsigned int index, osg::Matrix3x4& m3x4 ) const; + bool getElement( unsigned int index, osg::Matrix4x2& m4x2 ) const; + bool getElement( unsigned int index, osg::Matrix4x3& m4x3 ) const; + bool getElement( unsigned int index, osg::Matrix2d& m2 ) const; + bool getElement( unsigned int index, osg::Matrix3d& m3 ) const; + bool getElement( unsigned int index, osg::Matrixd& m4 ) const; + bool getElement( unsigned int index, osg::Matrix2x3d& m2x3 ) const; + bool getElement( unsigned int index, osg::Matrix2x4d& m2x4 ) const; + bool getElement( unsigned int index, osg::Matrix3x2d& m3x2 ) const; + bool getElement( unsigned int index, osg::Matrix3x4d& m3x4 ) const; + bool getElement( unsigned int index, osg::Matrix4x2d& m4x2 ) const; + bool getElement( unsigned int index, osg::Matrix4x3d& m4x3 ) const; + bool getElement( unsigned int index, int& i0, int& i1 ) const; + bool getElement( unsigned int index, int& i0, int& i1, int& i2 ) const; + bool getElement( unsigned int index, int& i0, int& i1, int& i2, int& i3 ) const; + bool getElement( unsigned int index, unsigned int& ui0, unsigned int& ui1 ) const; + bool getElement( unsigned int index, unsigned int& ui0, unsigned int& ui1, unsigned int& ui2 ) const; + bool getElement( unsigned int index, unsigned int& ui0, unsigned int& ui1, unsigned int& ui2, unsigned int& ui3 ) const; + bool getElement( unsigned int index, bool& b0, bool& b1 ) const; + bool getElement( unsigned int index, bool& b0, bool& b1, bool& b2 ) const; + bool getElement( unsigned int index, bool& b0, bool& b1, bool& b2, bool& b3 ) const; + + + struct Callback : public virtual osg::Object + { + Callback() {} + + Callback(const Callback&,const CopyOp&) {} + + META_Object(osg,Callback); + + /** do customized update code.*/ + virtual void operator () (Uniform*, NodeVisitor*) {} + }; + + /** Set the UpdateCallback which allows users to attach customize the updating of an object during the update traversal.*/ + void setUpdateCallback(Callback* uc); + + /** Get the non const UpdateCallback.*/ + Callback* getUpdateCallback() { return _updateCallback.get(); } + + /** Get the const UpdateCallback.*/ + const Callback* getUpdateCallback() const { return _updateCallback.get(); } + + + /** Set the EventCallback which allows users to attach customize the updating of an object during the Event traversal.*/ + void setEventCallback(Callback* ec); + + /** Get the non const EventCallback.*/ + Callback* getEventCallback() { return _eventCallback.get(); } + + /** Get the const EventCallback.*/ + const Callback* getEventCallback() const { return _eventCallback.get(); } + + /** Increment the modified count on the Uniform so Programs watching it know it update themselves. + * NOTE: automatically called during osg::Uniform::set*(); + * you must call if modifying the internal data array directly. */ + inline void dirty() { ++_modifiedCount; } + + /** Set the internal data array for a osg::Uniform */ + bool setArray( FloatArray* array ); + bool setArray( DoubleArray* array ); + bool setArray( IntArray* array ); + bool setArray( UIntArray* array ); + + /** Get the internal data array for a float osg::Uniform. */ + FloatArray* getFloatArray() { return _floatArray.get(); } + const FloatArray* getFloatArray() const { return _floatArray.get(); } + + /** Get the internal data array for a double osg::Uniform. */ + DoubleArray* getDoubleArray() { return _doubleArray.get(); } + const DoubleArray* getDoubleArray() const { return _doubleArray.get(); } + + /** Get the internal data array for an int osg::Uniform. */ + IntArray* getIntArray() { return _intArray.get(); } + const IntArray* getIntArray() const { return _intArray.get(); } + + /** Get the internal data array for an unsigned int osg::Uniform. */ + UIntArray* getUIntArray() { return _uintArray.get(); } + const UIntArray* getUIntArray() const { return _uintArray.get(); } + + inline void setModifiedCount(unsigned int mc) { _modifiedCount = mc; } + inline unsigned int getModifiedCount() const { return _modifiedCount; } + + /** Get the number that the Uniform's name maps to uniquely */ + unsigned int getNameID() const; + + void apply(const GL2Extensions* ext, GLint location) const; + + + protected: + + virtual ~Uniform(); + Uniform& operator=(const Uniform&) { return *this; } + + bool isCompatibleType( Type t ) const; + // for backward compatibility only + // see getElement(index, osg::Matrixd &) + // see setElement(index, osg::Matrixd &) + bool isCompatibleType( Type t1, Type t2 ) const; + bool isScalar() const { return _numElements==1; } + void allocateDataArray(); + + void addParent(osg::StateSet* object); + void removeParent(osg::StateSet* object); + + ParentList _parents; + friend class osg::StateSet; + + Type _type; + unsigned int _numElements; + unsigned int _nameID; + + + // The internal data for osg::Uniforms are stored as an array of + // getInternalArrayType() of length getInternalArrayNumElements(). + ref_ptr _floatArray; + ref_ptr _doubleArray; + ref_ptr _intArray; + ref_ptr _uintArray; + + ref_ptr _updateCallback; + ref_ptr _eventCallback; + + unsigned int _modifiedCount; +}; + +} + +#endif diff --git a/libs/include/android/osg/UserDataContainer b/libs/include/android/osg/UserDataContainer new file mode 100755 index 0000000..6b1bc01 --- /dev/null +++ b/libs/include/android/osg/UserDataContainer @@ -0,0 +1,192 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_USERDATACONTAINER +#define OSG_USERDATACONTAINER 1 + +#include + +#include +#include + +namespace osg { + +/** Internal structure for storing all user data.*/ +class OSG_EXPORT UserDataContainer : public osg::Object +{ + public: + UserDataContainer(); + UserDataContainer(const UserDataContainer& udc, const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY); + + virtual bool isSameKindAs(const Object* obj) const { return dynamic_cast(obj)!=0; } + + /** return the name of the object's library. Must be defined + by derived classes. The OpenSceneGraph convention is that the + namespace of a library is the same as the library name.*/ + virtual const char* libraryName() const { return "osg"; } + + /** return the name of the object's class type. Must be defined + by derived classes.*/ + virtual const char* className() const { return "UserDataContainer"; } + + /** + * Set user data, data must be subclassed from Referenced to allow + * automatic memory handling. If your own data isn't directly + * subclassed from Referenced then create an adapter object + * which points to your own object and handles the memory addressing. + */ + virtual void setUserData(Referenced* obj) = 0; + + /** Get user data.*/ + virtual Referenced* getUserData() = 0; + + /** Get const user data.*/ + virtual const Referenced* getUserData() const = 0; + + /** Add user data object. Returns the index position of object added. */ + virtual unsigned int addUserObject(Object* obj) = 0; + + /** Add element to list of user data objects.*/ + virtual void setUserObject(unsigned int i, Object* obj) = 0; + + /** Remove element from the list of user data objects.*/ + virtual void removeUserObject(unsigned int i) = 0; + + + /** Get user data object as specified index position. */ + virtual Object* getUserObject(unsigned int i) = 0; + + /** Get const user data object as specified index position. */ + virtual const Object* getUserObject(unsigned int i) const = 0; + + /** Get number of user objects assigned to this object.*/ + virtual unsigned int getNumUserObjects() const = 0; + + /** Get the index position of specified user data object.*/ + virtual unsigned int getUserObjectIndex(const osg::Object* obj, unsigned int startPos=0) const = 0; + + /** Get the index position of first user data object that matches specified name.*/ + virtual unsigned int getUserObjectIndex(const std::string& name, unsigned int startPos=0) const = 0; + + + /** Get first user data object with specified name. */ + virtual Object* getUserObject(const std::string& name, unsigned int startPos=0); + + /** Get first const user data object with specified name. */ + virtual const Object* getUserObject(const std::string& name, unsigned int startPos=0) const; + + + typedef std::vector DescriptionList; + + /** Set the list of string descriptions.*/ + virtual void setDescriptions(const DescriptionList& descriptions) = 0; + + /** Get the description list.*/ + virtual DescriptionList& getDescriptions() = 0; + + /** Get the const description list.*/ + virtual const DescriptionList& getDescriptions() const = 0; + + /** Get number of description strings.*/ + virtual unsigned int getNumDescriptions() const = 0; + + /** Add a description string.*/ + virtual void addDescription(const std::string& desc) = 0; + + protected: + virtual ~UserDataContainer() {} +}; + +/** Internal structure for storing all user data.*/ +class OSG_EXPORT DefaultUserDataContainer : public osg::UserDataContainer +{ + public: + DefaultUserDataContainer(); + DefaultUserDataContainer(const DefaultUserDataContainer& udc, const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY); + + META_Object(osg, DefaultUserDataContainer) + + + virtual void setThreadSafeRefUnref(bool threadSafe); + + /** + * Set user data, data must be subclassed from Referenced to allow + * automatic memory handling. If your own data isn't directly + * subclassed from Referenced then create an adapter object + * which points to your own object and handles the memory addressing. + */ + virtual void setUserData(Referenced* obj); + + /** Get user data.*/ + virtual Referenced* getUserData(); + + /** Get const user data.*/ + virtual const Referenced* getUserData() const; + + /** Add user data object. Returns the index position of object added. */ + virtual unsigned int addUserObject(Object* obj); + + /** Add element to list of user data objects.*/ + virtual void setUserObject(unsigned int i, Object* obj); + + /** Remove element from the list of user data objects.*/ + virtual void removeUserObject(unsigned int i); + + + /** Get user data object as specified index position. */ + virtual Object* getUserObject(unsigned int i); + + /** Get const user data object as specified index position. */ + virtual const Object* getUserObject(unsigned int i) const; + + /** Get number of user objects assigned to this object.*/ + virtual unsigned int getNumUserObjects() const; + + /** Get the index position of specified user data object.*/ + virtual unsigned int getUserObjectIndex(const osg::Object* obj, unsigned int startPos=0) const; + + /** Get the index position of first user data object that matches specified name.*/ + virtual unsigned int getUserObjectIndex(const std::string& name, unsigned int startPos=0) const; + + + + + /** Set the list of string descriptions.*/ + virtual void setDescriptions(const DescriptionList& descriptions); + + /** Get the description list.*/ + virtual DescriptionList& getDescriptions(); + + /** Get the const description list.*/ + virtual const DescriptionList& getDescriptions() const; + + /** Get number of description strings.*/ + virtual unsigned int getNumDescriptions() const; + + /** Add a description string.*/ + virtual void addDescription(const std::string& desc); + +protected: + + virtual ~DefaultUserDataContainer() {} + + typedef std::vector< osg::ref_ptr > ObjectList; + + ref_ptr _userData; + DescriptionList _descriptionList; + ObjectList _objectList; +}; + +} + +#endif diff --git a/libs/include/android/osg/ValueObject b/libs/include/android/osg/ValueObject new file mode 100755 index 0000000..d6ec0bd --- /dev/null +++ b/libs/include/android/osg/ValueObject @@ -0,0 +1,210 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 2011 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_VALUEOBJECT +#define OSG_VALUEOBJECT 1 + +#include +#include + +namespace osg { + +// foward declare core OSG math classes +class Vec2f; +class Vec3f; +class Vec4f; +class Vec2d; +class Vec3d; +class Vec4d; +class Quat; +class Plane; +class Matrixf; +class Matrixd; + +class ValueObject : public Object +{ + public: + + ValueObject() : Object(true) {} + ValueObject(const std::string& name) : Object(true) { setName(name); } + ValueObject(const ValueObject& rhs, const osg::CopyOp copyop=osg::CopyOp::SHALLOW_COPY): Object(rhs,copyop) {} + + META_Object(osg, ValueObject) + + class GetValueVisitor + { + public: + virtual void apply(bool /*value*/) {} + virtual void apply(char /*value*/) {} + virtual void apply(unsigned char /*value*/) {} + virtual void apply(short /*value*/) {} + virtual void apply(unsigned short /*value*/) {} + virtual void apply(int /*value*/) {} + virtual void apply(unsigned int /*value*/) {} + virtual void apply(float /*value*/) {} + virtual void apply(double /*value*/) {} + virtual void apply(const std::string& /*value*/) {} + virtual void apply(const osg::Vec2f& /*value*/) {} + virtual void apply(const osg::Vec3f& /*value*/) {} + virtual void apply(const osg::Vec4f& /*value*/) {} + virtual void apply(const osg::Vec2d& /*value*/) {} + virtual void apply(const osg::Vec3d& /*value*/) {} + virtual void apply(const osg::Vec4d& /*value*/) {} + virtual void apply(const osg::Quat& /*value*/) {} + virtual void apply(const osg::Plane& /*value*/) {} + virtual void apply(const osg::Matrixf& /*value*/) {} + virtual void apply(const osg::Matrixd& /*value*/) {} + }; + + class SetValueVisitor + { + public: + virtual void apply(bool& /*value*/) {} + virtual void apply(char& /*value*/) {} + virtual void apply(unsigned char& /*value*/) {} + virtual void apply(short& /*value*/) {} + virtual void apply(unsigned short& /*value*/) {} + virtual void apply(int& /*value*/) {} + virtual void apply(unsigned int& /*value*/) {} + virtual void apply(float& /*value*/) {} + virtual void apply(double& /*value*/) {} + virtual void apply(std::string& /*value*/) {} + virtual void apply(osg::Vec2f& /*value*/) {} + virtual void apply(osg::Vec3f& /*value*/) {} + virtual void apply(osg::Vec4f& /*value*/) {} + virtual void apply(osg::Vec2d& /*value*/) {} + virtual void apply(osg::Vec3d& /*value*/) {} + virtual void apply(osg::Vec4d& /*value*/) {} + virtual void apply(osg::Quat& /*value*/) {} + virtual void apply(osg::Plane& /*value*/) {} + virtual void apply(osg::Matrixf& /*value*/) {} + virtual void apply(osg::Matrixd& /*value*/) {} + }; + + virtual bool get(GetValueVisitor& /*gvv*/) const { return false; } + virtual bool set(SetValueVisitor& /*gvv*/) { return false; } + protected: + virtual ~ValueObject() {} +}; + +template< typename T > +struct ValueObjectClassNameTrait +{ + static const char* className() { return "TemplateValueObject"; } +}; + + +template< typename T > +class TemplateValueObject : public ValueObject +{ + public: + + TemplateValueObject(): + ValueObject(), + _value() {} + + TemplateValueObject(const std::string& name, const T& value) : + ValueObject(name), + _value(value) {} + + TemplateValueObject(const TemplateValueObject& rhs, const osg::CopyOp copyop=osg::CopyOp::SHALLOW_COPY) : + ValueObject(rhs,copyop), + _value(rhs._value) {} + + virtual Object* cloneType() const { return new TemplateValueObject(); } + virtual Object* clone(const CopyOp& copyop) const { return new TemplateValueObject(*this, copyop); } + virtual bool isSameKindAs(const Object* obj) const { return dynamic_cast(obj)!=NULL; } + virtual const char* libraryName() const { return "osg"; } + virtual const char* className() const { return ValueObjectClassNameTrait::className(); } + + void setValue(const T& value) { _value = value; } + const T& getValue() const { return _value; } + + virtual bool get(GetValueVisitor& gvv) const { gvv.apply(_value); return true; } + virtual bool set(SetValueVisitor& svv) { svv.apply(_value); return true; } + +protected: + + virtual ~TemplateValueObject() {} + static const char* s_TemplateValueObject_className; + + T _value; +}; + +#define META_ValueObject(TYPE,NAME) \ + template<> struct ValueObjectClassNameTrait { static const char* className() { return #NAME; } }; \ + typedef TemplateValueObject NAME; + +META_ValueObject(std::string, StringValueObject) +META_ValueObject(bool, BoolValueObject) +META_ValueObject(char, CharValueObject) +META_ValueObject(unsigned char, UCharValueObject) +META_ValueObject(short, ShortValueObject) +META_ValueObject(unsigned short, UShortValueObject) +META_ValueObject(int, IntValueObject) +META_ValueObject(unsigned int, UIntValueObject) +META_ValueObject(float, FloatValueObject) +META_ValueObject(double, DoubleValueObject) +META_ValueObject(Vec2f, Vec2fValueObject) +META_ValueObject(Vec3f, Vec3fValueObject) +META_ValueObject(Vec4f, Vec4fValueObject) +META_ValueObject(Vec2d, Vec2dValueObject) +META_ValueObject(Vec3d, Vec3dValueObject) +META_ValueObject(Vec4d, Vec4dValueObject) +META_ValueObject(Quat, QuatValueObject) +META_ValueObject(Plane, PlaneValueObject) +META_ValueObject(Matrixf, MatrixfValueObject) +META_ValueObject(Matrixd, MatrixdValueObject) + +/** provide implementation of osg::Object::getUserValue(..) template*/ +template +bool osg::Object::getUserValue(const std::string& name, T& value) const +{ + typedef TemplateValueObject UserValueObject; + + const osg::UserDataContainer* udc = dynamic_cast(this); + if (!udc) udc = _userDataContainer; + + const UserValueObject* uvo = udc ? dynamic_cast(udc->getUserObject(name)) : 0; + if (uvo) + { + value = uvo->getValue(); + return true; + } + else + { + return false; + } +} + +/** provide implementation of osg::Object::setUserValue(..) template.*/ +template +void osg::Object::setUserValue(const std::string& name, const T& value) +{ + typedef TemplateValueObject UserValueObject; + + osg::UserDataContainer* udc = dynamic_cast(this); + if (!udc) + { + getOrCreateUserDataContainer(); + udc = _userDataContainer; + } + + unsigned int i = udc->getUserObjectIndex(name); + if (igetNumUserObjects()) udc->setUserObject(i, new UserValueObject(name,value)); + else udc->addUserObject(new UserValueObject(name,value)); +} + +} +#endif + diff --git a/libs/include/android/osg/Vec2 b/libs/include/android/osg/Vec2 new file mode 100755 index 0000000..d3cdb59 --- /dev/null +++ b/libs/include/android/osg/Vec2 @@ -0,0 +1,25 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_VEC2 +#define OSG_VEC2 1 + +#include + +namespace osg { + + typedef Vec2f Vec2; + +} + +#endif diff --git a/libs/include/android/osg/Vec2b b/libs/include/android/osg/Vec2b new file mode 100755 index 0000000..67f6cf6 --- /dev/null +++ b/libs/include/android/osg/Vec2b @@ -0,0 +1,155 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_VEC2B +#define OSG_VEC2B 1 + +namespace osg { + +/** General purpose float triple. + * Uses include representation of color coordinates. + * No support yet added for float * Vec2b - is it necessary? + * Need to define a non-member non-friend operator* etc. + * Vec2b * float is okay +*/ +class Vec2b +{ + public: + + // Methods are defined here so that they are implicitly inlined + + /** Data type of vector components.*/ + typedef signed char value_type; + + /** Number of vector components. */ + enum { num_components = 2 }; + + /** Vec member variable. */ + value_type _v[2]; + + /** Constructor that sets all components of the vector to zero */ + Vec2b() { _v[0]=0; _v[1]=0; } + + Vec2b(value_type r, value_type g) + { + _v[0]=r; _v[1]=g; + } + + inline bool operator == (const Vec2b& v) const { return _v[0]==v._v[0] && _v[1]==v._v[1]; } + + inline bool operator != (const Vec2b& v) const { return _v[0]!=v._v[0] || _v[1]!=v._v[1]; } + + inline bool operator < (const Vec2b& v) const + { + if (_v[0]v._v[0]) return false; + else return (_v[1] + +namespace osg { + +/** General purpose double pair, uses include representation of + * texture coordinates. + * No support yet added for double * Vec2d - is it necessary? + * Need to define a non-member non-friend operator* etc. + * BTW: Vec2d * double is okay +*/ + +class Vec2d +{ + public: + + /** Data type of vector components.*/ + typedef double value_type; + + /** Number of vector components. */ + enum { num_components = 2 }; + + value_type _v[2]; + + /** Constructor that sets all components of the vector to zero */ + Vec2d() {_v[0]=0.0; _v[1]=0.0;} + + Vec2d(value_type x,value_type y) { _v[0]=x; _v[1]=y; } + + inline Vec2d(const Vec2f& vec) { _v[0]=vec._v[0]; _v[1]=vec._v[1]; } + + inline operator Vec2f() const { return Vec2f(static_cast(_v[0]),static_cast(_v[1]));} + + + inline bool operator == (const Vec2d& v) const { return _v[0]==v._v[0] && _v[1]==v._v[1]; } + + inline bool operator != (const Vec2d& v) const { return _v[0]!=v._v[0] || _v[1]!=v._v[1]; } + + inline bool operator < (const Vec2d& v) const + { + if (_v[0]v._v[0]) return false; + else return (_v[1]0.0) + { + value_type inv = 1.0/norm; + _v[0] *= inv; + _v[1] *= inv; + } + return( norm ); + } + +}; // end of class Vec2d + + +/** multiply by vector components. */ +inline Vec2d componentMultiply(const Vec2d& lhs, const Vec2d& rhs) +{ + return Vec2d(lhs[0]*rhs[0], lhs[1]*rhs[1]); +} + +/** divide rhs components by rhs vector components. */ +inline Vec2d componentDivide(const Vec2d& lhs, const Vec2d& rhs) +{ + return Vec2d(lhs[0]/rhs[0], lhs[1]/rhs[1]); +} + +} // end of namespace osg +#endif diff --git a/libs/include/android/osg/Vec2f b/libs/include/android/osg/Vec2f new file mode 100755 index 0000000..6fee4a3 --- /dev/null +++ b/libs/include/android/osg/Vec2f @@ -0,0 +1,190 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_VEC2F +#define OSG_VEC2F 1 + +#include + +namespace osg { + +/** General purpose float pair. Uses include representation of + * texture coordinates. + * No support yet added for float * Vec2f - is it necessary? + * Need to define a non-member non-friend operator* etc. + * BTW: Vec2f * float is okay +*/ + +class Vec2f +{ + public: + + /** Data type of vector components.*/ + typedef float value_type; + + /** Number of vector components. */ + enum { num_components = 2 }; + + /** Vec member variable. */ + value_type _v[2]; + + + /** Constructor that sets all components of the vector to zero */ + Vec2f() {_v[0]=0.0; _v[1]=0.0;} + Vec2f(value_type x,value_type y) { _v[0]=x; _v[1]=y; } + + + inline bool operator == (const Vec2f& v) const { return _v[0]==v._v[0] && _v[1]==v._v[1]; } + + inline bool operator != (const Vec2f& v) const { return _v[0]!=v._v[0] || _v[1]!=v._v[1]; } + + inline bool operator < (const Vec2f& v) const + { + if (_v[0]v._v[0]) return false; + else return (_v[1]0.0) + { + value_type inv = 1.0f/norm; + _v[0] *= inv; + _v[1] *= inv; + } + return( norm ); + } + +}; // end of class Vec2f + +/** multiply by vector components. */ +inline Vec2f componentMultiply(const Vec2f& lhs, const Vec2f& rhs) +{ + return Vec2f(lhs[0]*rhs[0], lhs[1]*rhs[1]); +} + +/** divide rhs components by rhs vector components. */ +inline Vec2f componentDivide(const Vec2f& lhs, const Vec2f& rhs) +{ + return Vec2f(lhs[0]/rhs[0], lhs[1]/rhs[1]); +} + +} // end of namespace osg +#endif + diff --git a/libs/include/android/osg/Vec2i b/libs/include/android/osg/Vec2i new file mode 100755 index 0000000..6ec1605 --- /dev/null +++ b/libs/include/android/osg/Vec2i @@ -0,0 +1,114 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_VEC2I +#define OSG_VEC2I 1 + +namespace osg { + +/** General purpose integer pair. +*/ +class Vec2i +{ + public: + + /** Type of Vec class.*/ + typedef int value_type; + + /** Number of vector components. */ + enum { num_components = 2 }; + + /** Vec member varaible. */ + value_type _v[2]; + + Vec2i() { _v[0]=0; _v[1]=0; } + + Vec2i(value_type x, value_type y) { _v[0] = x; _v[1] = y; } + + inline bool operator == (const Vec2i& v) const { return _v[0]==v._v[0] && _v[1]==v._v[1]; } + inline bool operator != (const Vec2i& v) const { return _v[0]!=v._v[0] || _v[1]!=v._v[1]; } + inline bool operator < (const Vec2i& v) const + { + if (_v[0]v._v[0]) return false; + else return (_v[1]v._v[0]) return false; + else return (_v[1]v._v[0]) return false; + else return (_v[1]v._v[0]) return false; + else return (_v[1]v._v[0]) return false; + else return (_v[1] + +namespace osg { + + typedef Vec3f Vec3; + +} + +#endif diff --git a/libs/include/android/osg/Vec3b b/libs/include/android/osg/Vec3b new file mode 100755 index 0000000..1706e01 --- /dev/null +++ b/libs/include/android/osg/Vec3b @@ -0,0 +1,160 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_VEC3B +#define OSG_VEC3B 1 + +namespace osg { + +/** General purpose float triple. + * Uses include representation of color coordinates. + * No support yet added for float * Vec3b - is it necessary? + * Need to define a non-member non-friend operator* etc. + * Vec3b * float is okay +*/ +class Vec3b +{ + public: + + /** Data type of vector components.*/ + typedef signed char value_type; + + /** Number of vector components. */ + enum { num_components = 3 }; + + value_type _v[3]; + + /** Constructor that sets all components of the vector to zero */ + Vec3b() { _v[0]=0; _v[1]=0; _v[2]=0; } + + Vec3b(value_type r, value_type g, value_type b) { _v[0]=r; _v[1]=g; _v[2]=b; } + + inline bool operator == (const Vec3b& v) const { return _v[0]==v._v[0] && _v[1]==v._v[1] && _v[2]==v._v[2]; } + + inline bool operator != (const Vec3b& v) const { return _v[0]!=v._v[0] || _v[1]!=v._v[1] || _v[2]!=v._v[2]; } + + inline bool operator < (const Vec3b& v) const + { + if (_v[0]v._v[0]) return false; + else if (_v[1]v._v[1]) return false; + else return (_v[2] +#include + +namespace osg { + +/** General purpose double triple for use as vertices, vectors and normals. + * Provides general math operations from addition through to cross products. + * No support yet added for double * Vec3d - is it necessary? + * Need to define a non-member non-friend operator* etc. + * Vec3d * double is okay +*/ + +class Vec3d +{ + public: + + /** Data type of vector components.*/ + typedef double value_type; + + /** Number of vector components. */ + enum { num_components = 3 }; + + value_type _v[3]; + + /** Constructor that sets all components of the vector to zero */ + Vec3d() { _v[0]=0.0; _v[1]=0.0; _v[2]=0.0;} + + inline Vec3d(const Vec3f& vec) { _v[0]=vec._v[0]; _v[1]=vec._v[1]; _v[2]=vec._v[2];} + + inline operator Vec3f() const { return Vec3f(static_cast(_v[0]),static_cast(_v[1]),static_cast(_v[2]));} + + Vec3d(value_type x,value_type y,value_type z) { _v[0]=x; _v[1]=y; _v[2]=z; } + Vec3d(const Vec2d& v2,value_type zz) + { + _v[0] = v2[0]; + _v[1] = v2[1]; + _v[2] = zz; + } + + inline bool operator == (const Vec3d& v) const { return _v[0]==v._v[0] && _v[1]==v._v[1] && _v[2]==v._v[2]; } + + inline bool operator != (const Vec3d& v) const { return _v[0]!=v._v[0] || _v[1]!=v._v[1] || _v[2]!=v._v[2]; } + + inline bool operator < (const Vec3d& v) const + { + if (_v[0]v._v[0]) return false; + else if (_v[1]v._v[1]) return false; + else return (_v[2]0.0) + { + value_type inv = 1.0/norm; + _v[0] *= inv; + _v[1] *= inv; + _v[2] *= inv; + } + return( norm ); + } + +}; // end of class Vec3d + +/** multiply by vector components. */ +inline Vec3d componentMultiply(const Vec3d& lhs, const Vec3d& rhs) +{ + return Vec3d(lhs[0]*rhs[0], lhs[1]*rhs[1], lhs[2]*rhs[2]); +} + +/** divide rhs components by rhs vector components. */ +inline Vec3d componentDivide(const Vec3d& lhs, const Vec3d& rhs) +{ + return Vec3d(lhs[0]/rhs[0], lhs[1]/rhs[1], lhs[2]/rhs[2]); +} + +} // end of namespace osg + +#endif diff --git a/libs/include/android/osg/Vec3f b/libs/include/android/osg/Vec3f new file mode 100755 index 0000000..c388111 --- /dev/null +++ b/libs/include/android/osg/Vec3f @@ -0,0 +1,224 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_VEC3F +#define OSG_VEC3F 1 + +#include +#include + +namespace osg { + +/** General purpose float triple for use as vertices, vectors and normals. + * Provides general math operations from addition through to cross products. + * No support yet added for float * Vec3f - is it necessary? + * Need to define a non-member non-friend operator* etc. + * Vec3f * float is okay +*/ +class Vec3f +{ + public: + + /** Data type of vector components.*/ + typedef float value_type; + + /** Number of vector components. */ + enum { num_components = 3 }; + + value_type _v[3]; + + /** Constructor that sets all components of the vector to zero */ + Vec3f() { _v[0]=0.0f; _v[1]=0.0f; _v[2]=0.0f;} + Vec3f(value_type x,value_type y,value_type z) { _v[0]=x; _v[1]=y; _v[2]=z; } + Vec3f(const Vec2f& v2,value_type zz) + { + _v[0] = v2[0]; + _v[1] = v2[1]; + _v[2] = zz; + } + + + inline bool operator == (const Vec3f& v) const { return _v[0]==v._v[0] && _v[1]==v._v[1] && _v[2]==v._v[2]; } + + inline bool operator != (const Vec3f& v) const { return _v[0]!=v._v[0] || _v[1]!=v._v[1] || _v[2]!=v._v[2]; } + + inline bool operator < (const Vec3f& v) const + { + if (_v[0]v._v[0]) return false; + else if (_v[1]v._v[1]) return false; + else return (_v[2]0.0) + { + value_type inv = 1.0f/norm; + _v[0] *= inv; + _v[1] *= inv; + _v[2] *= inv; + } + return( norm ); + } + +}; // end of class Vec3f + +/** multiply by vector components. */ +inline Vec3f componentMultiply(const Vec3f& lhs, const Vec3f& rhs) +{ + return Vec3f(lhs[0]*rhs[0], lhs[1]*rhs[1], lhs[2]*rhs[2]); +} + +/** divide rhs components by rhs vector components. */ +inline Vec3f componentDivide(const Vec3f& lhs, const Vec3f& rhs) +{ + return Vec3f(lhs[0]/rhs[0], lhs[1]/rhs[1], lhs[2]/rhs[2]); +} + +const Vec3f X_AXIS(1.0,0.0,0.0); +const Vec3f Y_AXIS(0.0,1.0,0.0); +const Vec3f Z_AXIS(0.0,0.0,1.0); + +} // end of namespace osg + +#endif + diff --git a/libs/include/android/osg/Vec3i b/libs/include/android/osg/Vec3i new file mode 100755 index 0000000..fe0a0c7 --- /dev/null +++ b/libs/include/android/osg/Vec3i @@ -0,0 +1,120 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_VEC3I +#define OSG_VEC3I 1 + +namespace osg { + +/** General purpose integer triple +**/ +class Vec3i +{ + public: + + /** Type of Vec class.*/ + typedef int value_type; + + /** Number of vector components. */ + enum { num_components = 3 }; + + /** Vec member varaible. */ + value_type _v[3]; + + Vec3i() { _v[0]=0; _v[1]=0; _v[2]=0; } + + Vec3i(value_type r, value_type g, value_type b) { _v[0]=r; _v[1]=g; _v[2]=b; } + + inline bool operator == (const Vec3i& v) const { return _v[0]==v._v[0] && _v[1]==v._v[1] && _v[2]==v._v[2]; } + inline bool operator != (const Vec3i& v) const { return _v[0]!=v._v[0] || _v[1]!=v._v[1] || _v[2]!=v._v[2]; } + inline bool operator < (const Vec3i& v) const + { + if (_v[0]v._v[0]) return false; + else if (_v[1]v._v[1]) return false; + else return (_v[2]v._v[0]) return false; + else if (_v[1]v._v[1]) return false; + else return (_v[2]v._v[0]) return false; + else if (_v[1]v._v[1]) return false; + else return (_v[2]v._v[0]) return false; + else if (_v[1]v._v[1]) return false; + else return (_v[2]v._v[0]) return false; + else if (_v[1]v._v[1]) return false; + else return (_v[2] + +namespace osg { + + typedef Vec4f Vec4; + +} + +#endif diff --git a/libs/include/android/osg/Vec4b b/libs/include/android/osg/Vec4b new file mode 100755 index 0000000..74b1261 --- /dev/null +++ b/libs/include/android/osg/Vec4b @@ -0,0 +1,170 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_VEC4B +#define OSG_VEC4B 1 + +namespace osg { + +/** General purpose float triple. + * Uses include representation of color coordinates. + * No support yet added for float * Vec4b - is it necessary? + * Need to define a non-member non-friend operator* etc. + * Vec4b * float is okay +*/ +class Vec4b +{ + public: + + /** Data type of vector components.*/ + typedef signed char value_type; + + /** Number of vector components. */ + enum { num_components = 4 }; + + value_type _v[4]; + + /** Constructor that sets all components of the vector to zero */ + Vec4b() { _v[0]=0; _v[1]=0; _v[2]=0; _v[3]=0; } + + Vec4b(value_type x, value_type y, value_type z, value_type w) + { + _v[0]=x; + _v[1]=y; + _v[2]=z; + _v[3]=w; + } + + inline bool operator == (const Vec4b& v) const { return _v[0]==v._v[0] && _v[1]==v._v[1] && _v[2]==v._v[2] && _v[3]==v._v[3]; } + + inline bool operator != (const Vec4b& v) const { return _v[0]!=v._v[0] || _v[1]!=v._v[1] || _v[2]!=v._v[2] || _v[3]!=v._v[3]; } + + inline bool operator < (const Vec4b& v) const + { + if (_v[0]v._v[0]) return false; + else if (_v[1]v._v[1]) return false; + else if (_v[2]v._v[2]) return false; + else return (_v[3] +#include + +namespace osg { + +/** General purpose double quad. Uses include representation + * of color coordinates. + * No support yet added for double * Vec4d - is it necessary? + * Need to define a non-member non-friend operator* etc. + * Vec4d * double is okay +*/ +class Vec4d +{ + public: + + /** Data type of vector components.*/ + typedef double value_type; + + /** Number of vector components. */ + enum { num_components = 4 }; + + value_type _v[4]; + + /** Constructor that sets all components of the vector to zero */ + Vec4d() { _v[0]=0.0; _v[1]=0.0; _v[2]=0.0; _v[3]=0.0; } + + Vec4d(value_type x, value_type y, value_type z, value_type w) + { + _v[0]=x; + _v[1]=y; + _v[2]=z; + _v[3]=w; + } + + Vec4d(const Vec3d& v3,value_type w) + { + _v[0]=v3[0]; + _v[1]=v3[1]; + _v[2]=v3[2]; + _v[3]=w; + } + + inline Vec4d(const Vec4f& vec) { _v[0]=vec._v[0]; _v[1]=vec._v[1]; _v[2]=vec._v[2]; _v[3]=vec._v[3];} + + inline operator Vec4f() const { return Vec4f(static_cast(_v[0]),static_cast(_v[1]),static_cast(_v[2]),static_cast(_v[3]));} + + + inline bool operator == (const Vec4d& v) const { return _v[0]==v._v[0] && _v[1]==v._v[1] && _v[2]==v._v[2] && _v[3]==v._v[3]; } + + inline bool operator != (const Vec4d& v) const { return _v[0]!=v._v[0] || _v[1]!=v._v[1] || _v[2]!=v._v[2] || _v[3]!=v._v[3]; } + + inline bool operator < (const Vec4d& v) const + { + if (_v[0]v._v[0]) return false; + else if (_v[1]v._v[1]) return false; + else if (_v[2]v._v[2]) return false; + else return (_v[3]0.0f) + { + value_type inv = 1.0/norm; + _v[0] *= inv; + _v[1] *= inv; + _v[2] *= inv; + _v[3] *= inv; + } + return( norm ); + } + +}; // end of class Vec4d + + + +/** Compute the dot product of a (Vec3,1.0) and a Vec4d. */ +inline Vec4d::value_type operator * (const Vec3d& lhs,const Vec4d& rhs) +{ + return lhs[0]*rhs[0]+lhs[1]*rhs[1]+lhs[2]*rhs[2]+rhs[3]; +} + +/** Compute the dot product of a (Vec3,1.0) and a Vec4d. */ +inline Vec4d::value_type operator * (const Vec3f& lhs,const Vec4d& rhs) +{ + return lhs[0]*rhs[0]+lhs[1]*rhs[1]+lhs[2]*rhs[2]+rhs[3]; +} + +/** Compute the dot product of a (Vec3,1.0) and a Vec4d. */ +inline Vec4d::value_type operator * (const Vec3d& lhs,const Vec4f& rhs) +{ + return lhs[0]*rhs[0]+lhs[1]*rhs[1]+lhs[2]*rhs[2]+rhs[3]; +} + + +/** Compute the dot product of a Vec4d and a (Vec3,1.0). */ +inline Vec4d::value_type operator * (const Vec4d& lhs,const Vec3d& rhs) +{ + return lhs[0]*rhs[0]+lhs[1]*rhs[1]+lhs[2]*rhs[2]+lhs[3]; +} + +/** Compute the dot product of a Vec4d and a (Vec3,1.0). */ +inline Vec4d::value_type operator * (const Vec4d& lhs,const Vec3f& rhs) +{ + return lhs[0]*rhs[0]+lhs[1]*rhs[1]+lhs[2]*rhs[2]+lhs[3]; +} + +/** Compute the dot product of a Vec4d and a (Vec3,1.0). */ +inline Vec4d::value_type operator * (const Vec4f& lhs,const Vec3d& rhs) +{ + return lhs[0]*rhs[0]+lhs[1]*rhs[1]+lhs[2]*rhs[2]+lhs[3]; +} + +/** multiply by vector components. */ +inline Vec4d componentMultiply(const Vec4d& lhs, const Vec4d& rhs) +{ + return Vec4d(lhs[0]*rhs[0], lhs[1]*rhs[1], lhs[2]*rhs[2], lhs[3]*rhs[3]); +} + +/** divide rhs components by rhs vector components. */ +inline Vec4d componentDivide(const Vec4d& lhs, const Vec4d& rhs) +{ + return Vec4d(lhs[0]/rhs[0], lhs[1]/rhs[1], lhs[2]/rhs[2], lhs[3]/rhs[3]); +} + +} // end of namespace osg + +#endif diff --git a/libs/include/android/osg/Vec4f b/libs/include/android/osg/Vec4f new file mode 100755 index 0000000..21a86f1 --- /dev/null +++ b/libs/include/android/osg/Vec4f @@ -0,0 +1,269 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_VEC4F +#define OSG_VEC4F 1 + +#include + +namespace osg { + +/** General purpose float quad. Uses include representation + * of color coordinates. + * No support yet added for float * Vec4f - is it necessary? + * Need to define a non-member non-friend operator* etc. + * Vec4f * float is okay +*/ +class Vec4f +{ + public: + + /** Data type of vector components.*/ + typedef float value_type; + + /** Number of vector components. */ + enum { num_components = 4 }; + + /** Vec member variable. */ + value_type _v[4]; + + // Methods are defined here so that they are implicitly inlined + + /** Constructor that sets all components of the vector to zero */ + Vec4f() { _v[0]=0.0f; _v[1]=0.0f; _v[2]=0.0f; _v[3]=0.0f;} + + Vec4f(value_type x, value_type y, value_type z, value_type w) + { + _v[0]=x; + _v[1]=y; + _v[2]=z; + _v[3]=w; + } + + Vec4f(const Vec3f& v3,value_type w) + { + _v[0]=v3[0]; + _v[1]=v3[1]; + _v[2]=v3[2]; + _v[3]=w; + } + + inline bool operator == (const Vec4f& v) const { return _v[0]==v._v[0] && _v[1]==v._v[1] && _v[2]==v._v[2] && _v[3]==v._v[3]; } + + inline bool operator != (const Vec4f& v) const { return _v[0]!=v._v[0] || _v[1]!=v._v[1] || _v[2]!=v._v[2] || _v[3]!=v._v[3]; } + + inline bool operator < (const Vec4f& v) const + { + if (_v[0]v._v[0]) return false; + else if (_v[1]v._v[1]) return false; + else if (_v[2]v._v[2]) return false; + else return (_v[3]0.0f) + { + value_type inv = 1.0f/norm; + _v[0] *= inv; + _v[1] *= inv; + _v[2] *= inv; + _v[3] *= inv; + } + return( norm ); + } + +}; // end of class Vec4f + +/** Compute the dot product of a (Vec3,1.0) and a Vec4f. */ +inline Vec4f::value_type operator * (const Vec3f& lhs,const Vec4f& rhs) +{ + return lhs[0]*rhs[0]+lhs[1]*rhs[1]+lhs[2]*rhs[2]+rhs[3]; +} + +/** Compute the dot product of a Vec4f and a (Vec3,1.0). */ +inline Vec4f::value_type operator * (const Vec4f& lhs,const Vec3f& rhs) +{ + return lhs[0]*rhs[0]+lhs[1]*rhs[1]+lhs[2]*rhs[2]+lhs[3]; +} + +/** multiply by vector components. */ +inline Vec4f componentMultiply(const Vec4f& lhs, const Vec4f& rhs) +{ + return Vec4f(lhs[0]*rhs[0], lhs[1]*rhs[1], lhs[2]*rhs[2], lhs[3]*rhs[3]); +} + +/** divide rhs components by rhs vector components. */ +inline Vec4f componentDivide(const Vec4f& lhs, const Vec4f& rhs) +{ + return Vec4f(lhs[0]/rhs[0], lhs[1]/rhs[1], lhs[2]/rhs[2], lhs[3]/rhs[3]); +} + +} // end of namespace osg + +#endif + diff --git a/libs/include/android/osg/Vec4i b/libs/include/android/osg/Vec4i new file mode 100755 index 0000000..d53ac8f --- /dev/null +++ b/libs/include/android/osg/Vec4i @@ -0,0 +1,126 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_VEC4I +#define OSG_VEC4I 1 + +namespace osg { + +/** General purpose integer quad +**/ +class Vec4i +{ + public: + + /** Type of Vec class.*/ + typedef int value_type; + + /** Number of vector components. */ + enum { num_components = 4 }; + + /** Vec member varaible. */ + value_type _v[4]; + + Vec4i() { _v[0]=0; _v[1]=0; _v[2]=0; _v[3]=0; } + + Vec4i(value_type x, value_type y, value_type z, value_type w) + { + _v[0]=x; + _v[1]=y; + _v[2]=z; + _v[3]=w; + } + + inline bool operator == (const Vec4i& v) const { return _v[0]==v._v[0] && _v[1]==v._v[1] && _v[2]==v._v[2] && _v[3]==v._v[3]; } + inline bool operator != (const Vec4i& v) const { return _v[0]!=v._v[0] || _v[1]!=v._v[1] || _v[2]!=v._v[2] || _v[3]!=v._v[3]; } + inline bool operator < (const Vec4i& v) const + { + if (_v[0]v._v[0]) return false; + else if (_v[1]v._v[1]) return false; + else if (_v[2]v._v[2]) return false; + else return (_v[3]v._v[0]) return false; + else if (_v[1]v._v[1]) return false; + else if (_v[2]v._v[2]) return false; + else return (_v[3] + +namespace osg { + +/** General purpose float quad. + * Uses include representation of color coordinates. + * No support yet added for float * Vec4ub - is it necessary? + * Need to define a non-member non-friend operator* etc. + * Vec4ub * float is okay +*/ +class Vec4ub +{ + public: + + /** Data type of vector components.*/ + typedef unsigned char value_type; + + /** Number of vector components. */ + enum { num_components = 4 }; + + /** Vec member variable. */ + value_type _v[4]; + + /** Constructor that sets all components of the vector to zero */ + Vec4ub() { _v[0]=0; _v[1]=0; _v[2]=0; _v[3]=0; } + + Vec4ub(value_type x, value_type y, value_type z, value_type w) + { + _v[0]=x; + _v[1]=y; + _v[2]=z; + _v[3]=w; + } + + inline bool operator == (const Vec4ub& v) const { return _v[0]==v._v[0] && _v[1]==v._v[1] && _v[2]==v._v[2] && _v[3]==v._v[3]; } + + inline bool operator != (const Vec4ub& v) const { return _v[0]!=v._v[0] || _v[1]!=v._v[1] || _v[2]!=v._v[2] || _v[3]!=v._v[3]; } + + inline bool operator < (const Vec4ub& v) const + { + if (_v[0]v._v[0]) return false; + else if (_v[1]v._v[1]) return false; + else if (_v[2]v._v[2]) return false; + else return (_v[3]v._v[0]) return false; + else if (_v[1]v._v[1]) return false; + else if (_v[2]v._v[2]) return false; + else return (_v[3]v._v[0]) return false; + else if (_v[1]v._v[1]) return false; + else if (_v[2]v._v[2]) return false; + else return (_v[3] + +extern "C" { + +#define OPENSCENEGRAPH_MAJOR_VERSION 3 +#define OPENSCENEGRAPH_MINOR_VERSION 2 +#define OPENSCENEGRAPH_PATCH_VERSION 2 +#define OPENSCENEGRAPH_SOVERSION 100 + +/* Convenience macro that can be used to decide whether a feature is present or not i.e. + * #if OSG_MIN_VERSION_REQUIRED(2,9,5) + * your code here + * #endif + */ +#define OSG_MIN_VERSION_REQUIRED(MAJOR, MINOR, PATCH) ((OPENSCENEGRAPH_MAJOR_VERSION>MAJOR) || (OPENSCENEGRAPH_MAJOR_VERSION==MAJOR && (OPENSCENEGRAPH_MINOR_VERSION>MINOR || (OPENSCENEGRAPH_MINOR_VERSION==MINOR && OPENSCENEGRAPH_PATCH_VERSION>=PATCH)))) +#define OSG_VERSION_LESS_THAN(MAJOR, MINOR, PATCH) ((OPENSCENEGRAPH_MAJOR_VERSIONMAJOR) || (OPENSCENEGRAPH_MAJOR_VERSION==MAJOR && (OPENSCENEGRAPH_MINOR_VERSION>MINOR || (OPENSCENEGRAPH_MINOR_VERSION==MINOR && OPENSCENEGRAPH_PATCH_VERSION>PATCH)))) +#define OSG_VERSION_GREATER_OR_EQUAL(MAJOR, MINOR, PATCH) ((OPENSCENEGRAPH_MAJOR_VERSION>MAJOR) || (OPENSCENEGRAPH_MAJOR_VERSION==MAJOR && (OPENSCENEGRAPH_MINOR_VERSION>MINOR || (OPENSCENEGRAPH_MINOR_VERSION==MINOR && OPENSCENEGRAPH_PATCH_VERSION>=PATCH)))) + + +/** + * osgGetVersion() returns the library version number. + * Numbering convention : OpenSceneGraph-1.0 will return 1.0 from osgGetVersion. + * + * This C function can be also used to check for the existence of the OpenSceneGraph + * library using autoconf and its m4 macro AC_CHECK_LIB. + * + * Here is the code to add to your configure.in: + \verbatim + # + # Check for the OpenSceneGraph (OSG) library + # + AC_CHECK_LIB(osg, osgGetVersion, , + [AC_MSG_ERROR(OpenSceneGraph library not found. See http://www.openscenegraph.org)],) + \endverbatim +*/ +extern OSG_EXPORT const char* osgGetVersion(); + +/** The osgGetSOVersion() method returns the OpenSceneGraph shared object version number. */ +extern OSG_EXPORT const char* osgGetSOVersion(); + +/** The osgGetLibraryName() method returns the library name in human-friendly form. */ +extern OSG_EXPORT const char* osgGetLibraryName(); + +// old defines for backwards compatibility. +#define OSG_VERSION_MAJOR OPENSCENEGRAPH_MAJOR_VERSION +#define OSG_VERSION_MINOR OPENSCENEGRAPH_MINOR_VERSION +#define OSG_VERSION_PATCH OPENSCENEGRAPH_PATCH_VERSION + +#define OSG_VERSION_RELEASE OSG_VERSION_PATCH +#define OSG_VERSION_REVISION 0 + + +} + +#endif diff --git a/libs/include/android/osg/VertexProgram b/libs/include/android/osg/VertexProgram new file mode 100755 index 0000000..24a8a57 --- /dev/null +++ b/libs/include/android/osg/VertexProgram @@ -0,0 +1,320 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_VERTEXPROGRAM +#define OSG_VERTEXPROGRAM 1 + +#include +#include +#include +#include + +#include +#include + +// if not defined by gl.h use the definition found in: +// http://oss.sgi.com/projects/ogl-sample/registry/ARB/vertex_program.txt +#ifndef GL_ARB_vertex_program +#define GL_VERTEX_PROGRAM_ARB 0x8620 +#define GL_VERTEX_PROGRAM_POINT_SIZE_ARB 0x8642 +#define GL_VERTEX_PROGRAM_TWO_SIDE_ARB 0x8643 +#define GL_COLOR_SUM_ARB 0x8458 +#define GL_PROGRAM_FORMAT_ASCII_ARB 0x8875 +#define GL_VERTEX_ATTRIB_ARRAY_ENABLED_ARB 0x8622 +#define GL_VERTEX_ATTRIB_ARRAY_SIZE_ARB 0x8623 +#define GL_VERTEX_ATTRIB_ARRAY_STRIDE_ARB 0x8624 +#define GL_VERTEX_ATTRIB_ARRAY_TYPE_ARB 0x8625 +#define GL_VERTEX_ATTRIB_ARRAY_NORMALIZED_ARB 0x886A +#define GL_CURRENT_VERTEX_ATTRIB_ARB 0x8626 +#define GL_VERTEX_ATTRIB_ARRAY_POINTER_ARB 0x8645 +#define GL_PROGRAM_LENGTH_ARB 0x8627 +#define GL_PROGRAM_FORMAT_ARB 0x8876 +#define GL_PROGRAM_BINDING_ARB 0x8677 +#define GL_PROGRAM_INSTRUCTIONS_ARB 0x88A0 +#define GL_MAX_PROGRAM_INSTRUCTIONS_ARB 0x88A1 +#define GL_PROGRAM_NATIVE_INSTRUCTIONS_ARB 0x88A2 +#define GL_MAX_PROGRAM_NATIVE_INSTRUCTIONS_ARB 0x88A3 +#define GL_PROGRAM_TEMPORARIES_ARB 0x88A4 +#define GL_MAX_PROGRAM_TEMPORARIES_ARB 0x88A5 +#define GL_PROGRAM_NATIVE_TEMPORARIES_ARB 0x88A6 +#define GL_MAX_PROGRAM_NATIVE_TEMPORARIES_ARB 0x88A7 +#define GL_PROGRAM_PARAMETERS_ARB 0x88A8 +#define GL_MAX_PROGRAM_PARAMETERS_ARB 0x88A9 +#define GL_PROGRAM_NATIVE_PARAMETERS_ARB 0x88AA +#define GL_MAX_PROGRAM_NATIVE_PARAMETERS_ARB 0x88AB +#define GL_PROGRAM_ATTRIBS_ARB 0x88AC +#define GL_MAX_PROGRAM_ATTRIBS_ARB 0x88AD +#define GL_PROGRAM_NATIVE_ATTRIBS_ARB 0x88AE +#define GL_MAX_PROGRAM_NATIVE_ATTRIBS_ARB 0x88AF +#define GL_PROGRAM_ADDRESS_REGISTERS_ARB 0x88B0 +#define GL_MAX_PROGRAM_ADDRESS_REGISTERS_ARB 0x88B1 +#define GL_PROGRAM_NATIVE_ADDRESS_REGISTERS_ARB 0x88B2 +#define GL_MAX_PROGRAM_NATIVE_ADDRESS_REGISTERS_ARB 0x88B3 +#define GL_MAX_PROGRAM_LOCAL_PARAMETERS_ARB 0x88B4 +#define GL_MAX_PROGRAM_ENV_PARAMETERS_ARB 0x88B5 +#define GL_PROGRAM_UNDER_NATIVE_LIMITS_ARB 0x88B6 +#define GL_PROGRAM_STRING_ARB 0x8628 +#define GL_PROGRAM_ERROR_POSITION_ARB 0x864B +#define GL_CURRENT_MATRIX_ARB 0x8641 +#define GL_TRANSPOSE_CURRENT_MATRIX_ARB 0x88B7 +#define GL_CURRENT_MATRIX_STACK_DEPTH_ARB 0x8640 +#define GL_MAX_VERTEX_ATTRIBS_ARB 0x8869 +#define GL_MAX_PROGRAM_MATRICES_ARB 0x862F +#define GL_MAX_PROGRAM_MATRIX_STACK_DEPTH_ARB 0x862E +#define GL_PROGRAM_ERROR_STRING_ARB 0x8874 +#define GL_MATRIX0_ARB 0x88C0 +#define GL_MATRIX1_ARB 0x88C1 +#define GL_MATRIX2_ARB 0x88C2 +#define GL_MATRIX3_ARB 0x88C3 +#define GL_MATRIX4_ARB 0x88C4 +#define GL_MATRIX5_ARB 0x88C5 +#define GL_MATRIX6_ARB 0x88C6 +#define GL_MATRIX7_ARB 0x88C7 +#define GL_MATRIX8_ARB 0x88C8 +#define GL_MATRIX9_ARB 0x88C9 +#define GL_MATRIX10_ARB 0x88CA +#define GL_MATRIX11_ARB 0x88CB +#define GL_MATRIX12_ARB 0x88CC +#define GL_MATRIX13_ARB 0x88CD +#define GL_MATRIX14_ARB 0x88CE +#define GL_MATRIX15_ARB 0x88CF +#define GL_MATRIX16_ARB 0x88D0 +#define GL_MATRIX17_ARB 0x88D1 +#define GL_MATRIX18_ARB 0x88D2 +#define GL_MATRIX19_ARB 0x88D3 +#define GL_MATRIX20_ARB 0x88D4 +#define GL_MATRIX21_ARB 0x88D5 +#define GL_MATRIX22_ARB 0x88D6 +#define GL_MATRIX23_ARB 0x88D7 +#define GL_MATRIX24_ARB 0x88D8 +#define GL_MATRIX25_ARB 0x88D9 +#define GL_MATRIX26_ARB 0x88DA +#define GL_MATRIX27_ARB 0x88DB +#define GL_MATRIX28_ARB 0x88DC +#define GL_MATRIX29_ARB 0x88DD +#define GL_MATRIX30_ARB 0x88DE +#define GL_MATRIX31_ARB 0x88DF +#endif + + +namespace osg { + + + +/** VertexProgram - encapsulates the OpenGL ARB vertex program state. */ +class OSG_EXPORT VertexProgram : public StateAttribute +{ + public: + + VertexProgram(); + + /** Copy constructor using CopyOp to manage deep vs shallow copy. */ + VertexProgram(const VertexProgram& vp,const CopyOp& copyop=CopyOp::SHALLOW_COPY); + + META_StateAttribute(osg, VertexProgram, VERTEXPROGRAM); + + /** Return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs. */ + virtual int compare(const osg::StateAttribute& sa) const + { + // check the types are equal and then create the rhs variable + // used by the COMPARE_StateAttribute_Parameter macros below. + COMPARE_StateAttribute_Types(VertexProgram,sa) + + // compare each parameter in turn against the rhs. + COMPARE_StateAttribute_Parameter(_vertexProgram) + + return 0; // passed all the above comparison macros, must be equal. + } + + virtual bool getModeUsage(StateAttribute::ModeUsage& usage) const + { + usage.usesMode(GL_VERTEX_PROGRAM_ARB); + return true; + } + + // data access methods. + + /** Get the handle to the vertex program ID for the current context. */ + inline GLuint& getVertexProgramID(unsigned int contextID) const + { + return _vertexProgramIDList[contextID]; + } + + + /** Set the vertex program using a C style string. */ + inline void setVertexProgram( const char* program ) + { + _vertexProgram = program; + dirtyVertexProgramObject(); + } + + /** Set the vertex program using C++ style string. */ + inline void setVertexProgram( const std::string& program ) + { + _vertexProgram = program; + dirtyVertexProgramObject(); + } + + /** Get the vertex program. */ + inline const std::string& getVertexProgram() const { return _vertexProgram; } + + /** Set Program Parameters */ + inline void setProgramLocalParameter(const GLuint index, const Vec4& p) + { + _programLocalParameters[index] = p; + } + + typedef std::map LocalParamList; + + /** Set list of Program Parameters */ + inline void setLocalParameters(const LocalParamList& lpl) { _programLocalParameters = lpl; } + + /** Get list of Program Parameters */ + inline LocalParamList& getLocalParameters() { return _programLocalParameters; } + + /** Get const list of Program Parameters */ + inline const LocalParamList& getLocalParameters() const { return _programLocalParameters; } + + /** Matrix */ + inline void setMatrix(const GLenum mode, const Matrix& matrix) + { + _matrixList[mode] = matrix; + } + + typedef std::map MatrixList; + + /** Set list of Matrices */ + inline void setMatrices(const MatrixList& matrices) { _matrixList = matrices; } + + /** Get list of Matrices */ + inline MatrixList& getMatrices() { return _matrixList; } + + /** Get list of Matrices */ + inline const MatrixList& getMatrices() const { return _matrixList; } + + /** Force a recompile on next apply() of associated OpenGL vertex program objects. */ + void dirtyVertexProgramObject(); + + /** Use deleteVertexProgramObject instead of glDeletePrograms to allow + * OpenGL Vertex Program objects to cached until they can be deleted + * by the OpenGL context in which they were created, specified + * by contextID. + */ + static void deleteVertexProgramObject(unsigned int contextID,GLuint handle); + + /** Flush all the cached vertex programs which need to be deleted + * in the OpenGL context related to contextID. + */ + static void flushDeletedVertexProgramObjects(unsigned int contextID,double currentTime, double& availableTime); + + /** discard all the cached vertex programs which need to be deleted + * in the OpenGL context related to contextID. + * Note, unlike flush no OpenGL calls are made, instead the handles are all removed. + * this call is useful for when an OpenGL context has been destroyed. + */ + static void discardDeletedVertexProgramObjects(unsigned int contextID); + + virtual void apply(State& state) const; + + virtual void compileGLObjects(State& state) const { apply(state); } + + /** Resize any per context GLObject buffers to specified size. */ + virtual void resizeGLObjectBuffers(unsigned int maxSize); + + /** Release any OpenGL objects in specified graphics context if State + * object is passed, otherwise release OpenGL objects for all graphics contexts if + * State object pointer is NULL. + */ + virtual void releaseGLObjects(State* state=0) const; + + /** Extensions class which encapsulates the querying of extensions and + * associated function pointers, and provide convenience wrappers to + * check for the extensions or use the associated functions. + */ + class OSG_EXPORT Extensions : public osg::Referenced + { + public: + Extensions(unsigned int contextID); + + Extensions(const Extensions& rhs); + + void lowestCommonDenominator(const Extensions& rhs); + + void setupGLExtensions(unsigned int contextID); + + void setVertexProgramSupported(bool flag) { _isVertexProgramSupported=flag; } + bool isVertexProgramSupported() const { return _isVertexProgramSupported; } + + void glBindProgram(GLenum target, GLuint id) const; + void glGenPrograms(GLsizei n, GLuint *programs) const; + void glDeletePrograms(GLsizei n, GLuint *programs) const; + void glProgramString(GLenum target, GLenum format, GLsizei len, const void *string) const; + void glProgramLocalParameter4fv(GLenum target, GLuint index, const GLfloat *params) const; + + protected: + + ~Extensions() {} + + bool _isVertexProgramSupported; + + typedef void (GL_APIENTRY * BindProgramProc) (GLenum target, GLuint id); + typedef void (GL_APIENTRY * GenProgramsProc) (GLsizei n, GLuint *programs); + typedef void (GL_APIENTRY * DeleteProgramsProc) (GLsizei n, GLuint *programs); + typedef void (GL_APIENTRY * ProgramStringProc) (GLenum target, GLenum format, GLsizei len, const void *string); + typedef void (GL_APIENTRY * ProgramLocalParameter4fvProc) (GLenum target, GLuint index, const GLfloat *params); + + BindProgramProc _glBindProgram; + GenProgramsProc _glGenPrograms; + DeleteProgramsProc _glDeletePrograms; + ProgramStringProc _glProgramString; + ProgramLocalParameter4fvProc _glProgramLocalParameter4fv; + + }; + + /** Function to call to get the extension of a specified context. + * If the Extension object for that context has not yet been created + * and the 'createIfNotInitalized' flag been set to false then returns NULL. + * If 'createIfNotInitalized' is true then the Extensions object is + * automatically created. However, in this case the extension object + * will only be created with the graphics context associated with ContextID. + */ + static Extensions* getExtensions(unsigned int contextID,bool createIfNotInitalized); + + /** The setExtensions method allows users to override the extensions across graphics contexts. + * Typically used when you have different extensions supported across graphics pipes + * but need to ensure that they all use the same low common denominator extensions. + */ + static void setExtensions(unsigned int contextID,Extensions* extensions); + + + protected: + + + virtual ~VertexProgram(); + + typedef buffered_value VertexProgramIDList; + mutable VertexProgramIDList _vertexProgramIDList; + + std::string _vertexProgram; + + LocalParamList _programLocalParameters; + + MatrixList _matrixList; +}; + + + +} + +#endif + diff --git a/libs/include/android/osg/View b/libs/include/android/osg/View new file mode 100755 index 0000000..d199b8f --- /dev/null +++ b/libs/include/android/osg/View @@ -0,0 +1,185 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_VIEW +#define OSG_VIEW 1 + +#include +#include +#include + +#include + +namespace osg { + +/** View - maintains a master camera view and a list of slave cameras that are relative to this master camera. + * Note, if no slave cameras are attached to the view then the master camera does both the control and implementation of the rendering of the scene, + * but if slave cameras are present then the master controls the view onto the scene, while the slaves implement the rendering of the scene. +*/ +class OSG_EXPORT View : public virtual osg::Object +{ + public : + + View(); + + View(const osg::View& view, const osg::CopyOp& copyop=CopyOp::SHALLOW_COPY); + + META_Object(osg,View); + + /** Take all the settings, Camera and Slaves from the passed in view, leaving it empty. */ + virtual void take(View& rhs); + + + /** Set the Stats object used for collect various frame related timing and scene graph stats.*/ + void setStats(osg::Stats* stats) { _stats = stats; } + + /** Get the Viewers Stats object.*/ + osg::Stats* getStats() { return _stats.get(); } + + /** Get the Viewers Stats object.*/ + const osg::Stats* getStats() const { return _stats.get(); } + + + /** Options for controlling the global lighting used for the view.*/ + enum LightingMode + { + NO_LIGHT, + HEADLIGHT, + SKY_LIGHT + }; + + /** Set the global lighting to use for this view. + * Defaults to headlight. */ + void setLightingMode(LightingMode lightingMode); + + /** Get the global lighting used for this view.*/ + LightingMode getLightingMode() const { return _lightingMode; } + + /** Get the global light.*/ + void setLight(osg::Light* light) { _light = light; } + + /** Get the global lighting if assigned.*/ + osg::Light* getLight() { return _light.get(); } + + /** Get the const global lighting if assigned.*/ + const osg::Light* getLight() const { return _light.get(); } + + /** Set the master camera of the view. */ + void setCamera(osg::Camera* camera); + + /** Get the master camera of the view. */ + osg::Camera* getCamera() { return _camera.get(); } + + /** Get the const master camera of the view. */ + const osg::Camera* getCamera() const { return _camera.get(); } + + /** Set the frame stamp of the view. */ + void setFrameStamp(osg::FrameStamp* fs) { _frameStamp = fs; } + + /** Get the frame stamp of the view. */ + osg::FrameStamp* getFrameStamp() { return _frameStamp.get(); } + + /** Get the frame stamp of the view. */ + const osg::FrameStamp* getFrameStamp() const { return _frameStamp.get(); } + + + /** Slave allows one to up a camera that follows the master with a local offset to the project and view matrices.*/ + struct OSG_EXPORT Slave + { + Slave(bool useMastersSceneData=true): + _useMastersSceneData(useMastersSceneData) {} + + Slave(osg::Camera* camera, const osg::Matrixd& projectionOffset, const osg::Matrixd& viewOffset, bool useMastersSceneData=true): + _camera(camera), + _projectionOffset(projectionOffset), + _viewOffset(viewOffset), + _useMastersSceneData(useMastersSceneData) {} + + Slave(const Slave& rhs) : + _camera(rhs._camera), + _projectionOffset(rhs._projectionOffset), + _viewOffset(rhs._viewOffset), + _useMastersSceneData(rhs._useMastersSceneData), + _updateSlaveCallback(rhs._updateSlaveCallback) {} + + virtual ~Slave() {} + + Slave& operator = (const Slave& rhs) + { + _camera = rhs._camera; + _projectionOffset = rhs._projectionOffset; + _viewOffset = rhs._viewOffset; + _useMastersSceneData = rhs._useMastersSceneData; + _updateSlaveCallback = rhs._updateSlaveCallback; + return *this; + } + + struct UpdateSlaveCallback : public virtual Referenced + { + virtual void updateSlave(osg::View& view, osg::View::Slave& slave) = 0; + }; + + void updateSlave(View& view) + { + if (_updateSlaveCallback.valid()) _updateSlaveCallback->updateSlave(view, *this); + else updateSlaveImplementation(view); + } + + virtual void updateSlaveImplementation(View& view); + + osg::ref_ptr _camera; + osg::Matrixd _projectionOffset; + osg::Matrixd _viewOffset; + bool _useMastersSceneData; + osg::ref_ptr _updateSlaveCallback; + }; + + bool addSlave(osg::Camera* camera, bool useMastersSceneData=true) { return addSlave(camera, osg::Matrix::identity(), osg::Matrix::identity(), useMastersSceneData); } + + bool addSlave(osg::Camera* camera, const osg::Matrix& projectionOffset, const osg::Matrix& viewOffset, bool useMastersSceneData=true); + + bool removeSlave(unsigned int pos); + + unsigned int getNumSlaves() const { return static_cast(_slaves.size()); } + + Slave& getSlave(unsigned int pos) { return _slaves[pos]; } + const Slave& getSlave(unsigned int pos) const { return _slaves[pos]; } + + unsigned int findSlaveIndexForCamera(osg::Camera* camera) const; + + Slave * findSlaveForCamera(osg::Camera* camera); + + void updateSlaves(); + + protected : + + virtual ~View(); + + virtual osg::GraphicsOperation* createRenderer(osg::Camera*) { return 0; } + + osg::ref_ptr _stats; + + LightingMode _lightingMode; + osg::ref_ptr _light; + + osg::ref_ptr _camera; + + typedef std::vector Slaves; + Slaves _slaves; + + osg::ref_ptr _frameStamp; +}; + +} + +#endif diff --git a/libs/include/android/osg/Viewport b/libs/include/android/osg/Viewport new file mode 100755 index 0000000..a32d4be --- /dev/null +++ b/libs/include/android/osg/Viewport @@ -0,0 +1,149 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_VIEWPORT +#define OSG_VIEWPORT 1 + +#include +#include + +namespace osg { + +/** Encapsulate OpenGL glViewport. */ +class OSG_EXPORT Viewport : public StateAttribute +{ + public : + +#if 0 + typedef int value_type; +#else + typedef double value_type; +#endif + Viewport(); + + Viewport(value_type x,value_type y,value_type width,value_type height): + _x(x), + _y(y), + _width(width), + _height(height) {} + + + /** Copy constructor using CopyOp to manage deep vs shallow copy. */ + Viewport(const Viewport& vp,const CopyOp& copyop=CopyOp::SHALLOW_COPY): + StateAttribute(vp,copyop), + _x(vp._x), + _y(vp._y), + _width(vp._width), + _height(vp._height) {} + + META_StateAttribute(osg, Viewport,VIEWPORT); + + /** Return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs. */ + virtual int compare(const StateAttribute& sa) const + { + // check the types are equal and then create the rhs variable + // used by the COMPARE_StateAttribute_Parameter macros below. + COMPARE_StateAttribute_Types(Viewport,sa) + + // compare each parameter in turn against the rhs. + COMPARE_StateAttribute_Parameter(_x) + COMPARE_StateAttribute_Parameter(_y) + COMPARE_StateAttribute_Parameter(_width) + COMPARE_StateAttribute_Parameter(_height) + + return 0; // passed all the above comparison macros, must be equal. + } + + Viewport& operator = (const Viewport& rhs) + { + if (&rhs==this) return *this; + + _x = rhs._x; + _y = rhs._y; + _width = rhs._width; + _height = rhs._height; + + return *this; + } + + inline void setViewport(value_type x,value_type y,value_type width,value_type height) + { + _x = x; + _y = y; + _width = width; + _height = height; + } + +#if 0 + void getViewport(int& x,int& y,int& width,int& height) const + { + x = _x; + y = _y; + width = _width; + height = _height; + } + + void getViewport(double& x,double& y,double& width,double& height) const + { + x = _x; + y = _y; + width = _width; + height = _height; + } +#endif + inline value_type& x() { return _x; } + inline value_type x() const { return _x; } + + inline value_type& y() { return _y; } + inline value_type y() const { return _y; } + + inline value_type& width() { return _width; } + inline value_type width() const { return _width; } + + inline value_type& height() { return _height; } + inline value_type height() const { return _height; } + + inline bool valid() const { return _width>0 && _height>0; } + + /** Return the aspectRatio of the viewport, which is equal to width/height. + * If height is zero, the potential division by zero is avoided by simply returning 1.0f. + */ + inline double aspectRatio() const { if (_height!=0) return (double)_width/(double)_height; else return 1.0; } + + /** Compute the Window Matrix which takes projected coords into Window coordinates. + * To convert local coordinates into window coordinates use v_window = v_local * MVPW matrix, + * where the MVPW matrix is ModelViewMatrix * ProjectionMatrix * WindowMatrix, the latter supplied by + * Viewport::computeWindowMatrix(), the ModelView and Projection Matrix can either be sourced from the + * current osg::State object, via osgUtil::SceneView or CullVisitor. + */ + inline const osg::Matrix computeWindowMatrix() const + { + return osg::Matrix::translate(1.0,1.0,1.0)*osg::Matrix::scale(0.5*width(),0.5*height(),0.5f)*osg::Matrix::translate(x(),y(),0.0f); + } + + virtual void apply(State& state) const; + + protected: + + virtual ~Viewport(); + + value_type _x; + value_type _y; + value_type _width; + value_type _height; + +}; + +} + +#endif diff --git a/libs/include/android/osg/buffered_value b/libs/include/android/osg/buffered_value new file mode 100755 index 0000000..53937f3 --- /dev/null +++ b/libs/include/android/osg/buffered_value @@ -0,0 +1,132 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_BUFFERED_VALUE +#define OSG_BUFFERED_VALUE 1 + +#include +#include + +namespace osg { + +/** Implements a simple buffered value for values that need to be buffered on + * a per graphics context basis. +*/ +template +class buffered_value +{ + public: + + inline buffered_value(): + _array(DisplaySettings::instance()->getMaxNumberOfGraphicsContexts(),0) + {} + + inline buffered_value(unsigned int size): + _array(size,0) + {} + + buffered_value& operator = (const buffered_value& rhs) + { + _array = rhs._array; + return *this; + } + + inline void setAllElementsTo(const T& t) { std::fill(_array.begin(),_array.end(),t); } + + inline void clear() { _array.clear(); } + + inline bool empty() const { return _array.empty(); } + + inline unsigned int size() const { return _array.size(); } + + inline void resize(unsigned int newSize) { _array.resize(newSize,0); } + + inline T& operator[] (unsigned int pos) + { + // automatically resize array. + if (_array.size()<=pos) + _array.resize(pos+1,0); + + return _array[pos]; + } + + inline T operator[] (unsigned int pos) const + { + // automatically resize array. + if (_array.size()<=pos) + _array.resize(pos+1,0); + + return _array[pos]; + } + + protected: + + mutable std::vector _array; +}; + +template +class buffered_object +{ + public: + + inline buffered_object(): + _array(DisplaySettings::instance()->getMaxNumberOfGraphicsContexts()) + {} + + inline buffered_object(unsigned int size): + _array(size) + {} + + buffered_object& operator = (const buffered_object& rhs) + { + _array = rhs._array; + return *this; + } + + inline void setAllElementsTo(const T& t) { std::fill(_array.begin(),_array.end(),t); } + + inline void clear() { _array.clear(); } + + inline bool empty() const { return _array.empty(); } + + inline unsigned int size() const { return _array.size(); } + + inline void resize(unsigned int newSize) { _array.resize(newSize); } + + inline T& operator[] (unsigned int pos) + { + // automatically resize array. + if (_array.size()<=pos) + _array.resize(pos+1); + + return _array[pos]; + } + + inline const T& operator[] (unsigned int pos) const + { + // automatically resize array. + if (_array.size()<=pos) + _array.resize(pos+1); + + return _array[pos]; + } + + + protected: + + mutable std::vector _array; +}; + +} + +#endif diff --git a/libs/include/android/osg/fast_back_stack b/libs/include/android/osg/fast_back_stack new file mode 100755 index 0000000..f92a5e9 --- /dev/null +++ b/libs/include/android/osg/fast_back_stack @@ -0,0 +1,97 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_FAST_BACK_STACK +#define OSG_FAST_BACK_STACK 1 + +#include + +namespace osg { + +/** Simple stack implementation that keeps the back() cached locally for fast access + * rather than at the back of the vector which is the traditional stack implementation. + * A conventional std::vector<> stores the rest of the stack. Although fast_back_stack + * contains a stl container it only implements the back push_back(),pop_back() + * and back() methods so is not as general purpose as stl stack implementation. + * The focus of the fast_back_stack is purely to maximize the speed at which the + * back can be accessed.*/ + +template +class fast_back_stack +{ + public: + + inline fast_back_stack():_value(),_stack(),_size(0) {} + + inline fast_back_stack(const fast_back_stack& fbs):_value(fbs._value),_stack(fbs._stack),_size(fbs._size) {} + + inline fast_back_stack(const T& value):_value(value),_stack(),_size(1) {} + + fast_back_stack& operator = (const fast_back_stack& fbs) + { + _value = fbs._value; + _stack = fbs._stack; + _size = fbs._size; + return *this; + } + + inline void clear() { _stack.clear(); _size = 0; } + + inline bool empty() const { return _size==0; } + + inline unsigned int size() const { return _size; } + + inline T& back() { return _value; } + + inline const T& back() const { return _value; } + + inline void push_back() + { + if (_size>0) + { + _stack.push_back(_value); + } + ++_size; + } + + inline void push_back(const T& value) + { + if (_size>0) + { + _stack.push_back(_value); + } + _value = value; + ++_size; + } + + inline void pop_back() + { + if (_size>0) + { + if (!_stack.empty()) + { + _value = _stack.back(); + _stack.pop_back(); + } + --_size; + } // else error condition. + } + + T _value; + std::vector _stack; + unsigned int _size; +}; + +} + +#endif diff --git a/libs/include/android/osg/io_utils b/libs/include/android/osg/io_utils new file mode 100755 index 0000000..ee42b30 --- /dev/null +++ b/libs/include/android/osg/io_utils @@ -0,0 +1,338 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_IO_UTILS +#define OSG_IO_UTILS 1 + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace osg { + + +////////////////////////////////////////////////////////////////////////// +// Vec2f streaming operators +inline std::ostream& operator << (std::ostream& output, const Vec2f& vec) +{ + output << vec._v[0] << " " << vec._v[1]; + return output; // to enable cascading +} + +inline std::istream& operator >> (std::istream& input, Vec2f& vec) +{ + input >> vec._v[0] >> std::ws >> vec._v[1]; + return input; +} + +////////////////////////////////////////////////////////////////////////// +// Vec2d steaming operators. +inline std::ostream& operator << (std::ostream& output, const Vec2d& vec) +{ + output << vec._v[0] << " " << vec._v[1]; + return output; // to enable cascading +} + +inline std::istream& operator >> (std::istream& input, Vec2d& vec) +{ + input >> vec._v[0] >> std::ws >> vec._v[1]; + return input; +} + +////////////////////////////////////////////////////////////////////////// +// Vec3f steaming operators. +inline std::ostream& operator << (std::ostream& output, const Vec3f& vec) +{ + output << vec._v[0] << " " + << vec._v[1] << " " + << vec._v[2]; + return output; // to enable cascading +} + +inline std::istream& operator >> (std::istream& input, Vec3f& vec) +{ + input >> vec._v[0] >> std::ws >> vec._v[1] >> std::ws >> vec._v[2]; + return input; +} + + +////////////////////////////////////////////////////////////////////////// +// Vec3d steaming operators. +inline std::ostream& operator << (std::ostream& output, const Vec3d& vec) +{ + output << vec._v[0] << " " + << vec._v[1] << " " + << vec._v[2]; + return output; // to enable cascading +} + +inline std::istream& operator >> (std::istream& input, Vec3d& vec) +{ + input >> vec._v[0] >> std::ws >> vec._v[1] >> std::ws >> vec._v[2]; + return input; +} + + +////////////////////////////////////////////////////////////////////////// +// Vec3f steaming operators. +inline std::ostream& operator << (std::ostream& output, const Vec4f& vec) +{ + output << vec._v[0] << " " + << vec._v[1] << " " + << vec._v[2] << " " + << vec._v[3]; + return output; // to enable cascading +} + +inline std::istream& operator >> (std::istream& input, Vec4f& vec) +{ + input >> vec._v[0] >> std::ws + >> vec._v[1] >> std::ws + >> vec._v[2] >> std::ws + >> vec._v[3]; + return input; +} + + + +////////////////////////////////////////////////////////////////////////// +// Vec4d steaming operators. +inline std::ostream& operator << (std::ostream& output, const Vec4d& vec) +{ + output << vec._v[0] << " " + << vec._v[1] << " " + << vec._v[2] << " " + << vec._v[3]; + return output; // to enable cascading +} +inline std::istream& operator >> (std::istream& input, Vec4d& vec) +{ + input >> vec._v[0] >> std::ws + >> vec._v[1] >> std::ws + >> vec._v[2] >> std::ws + >> vec._v[3]; + return input; +} + + +////////////////////////////////////////////////////////////////////////// +// Vec2b steaming operators. +inline std::ostream& operator << (std::ostream& output, const Vec2b& vec) +{ + output << (int)vec._v[0] << " " + << (int)vec._v[1]; + return output; // to enable cascading +} + +inline std::istream& operator >> (std::istream& input, Vec2b& vec) +{ + input >> vec._v[0] >> std::ws >> vec._v[1]; + return input; +} + +////////////////////////////////////////////////////////////////////////// +// Vec3b steaming operators. +inline std::ostream& operator << (std::ostream& output, const Vec3b& vec) +{ + output << (int)vec._v[0] << " " + << (int)vec._v[1] << " " + << (int)vec._v[2]; + return output; // to enable cascading +} + +inline std::istream& operator >> (std::istream& input, Vec3b& vec) +{ + input >> vec._v[0] >> std::ws >> vec._v[1] >> std::ws >> vec._v[2]; + return input; +} + +////////////////////////////////////////////////////////////////////////// +// Vec4b steaming operators. +inline std::ostream& operator << (std::ostream& output, const Vec4b& vec) +{ + output << (int)vec._v[0] << " " + << (int)vec._v[1] << " " + << (int)vec._v[2] << " " + << (int)vec._v[3]; + return output; // to enable cascading +} + +inline std::istream& operator >> (std::istream& input, Vec4b& vec) +{ + input >> vec._v[0] >> std::ws + >> vec._v[1] >> std::ws + >> vec._v[2] >> std::ws + >> vec._v[3]; + return input; +} + + +////////////////////////////////////////////////////////////////////////// +// Vec2s steaming operators. +inline std::ostream& operator << (std::ostream& output, const Vec2s& vec) +{ + output << (int)vec._v[0] << " " + << (int)vec._v[1]; + return output; // to enable cascading +} + +inline std::istream& operator >> (std::istream& input, Vec2s& vec) +{ + input >> vec._v[0] >> std::ws >> vec._v[1]; + return input; +} + +////////////////////////////////////////////////////////////////////////// +// Vec3s steaming operators. +inline std::ostream& operator << (std::ostream& output, const Vec3s& vec) +{ + output << (int)vec._v[0] << " " + << (int)vec._v[1] << " " + << (int)vec._v[2]; + return output; // to enable cascading +} + +inline std::istream& operator >> (std::istream& input, Vec3s& vec) +{ + input >> vec._v[0] >> std::ws >> vec._v[1] >> std::ws >> vec._v[2]; + return input; +} + +////////////////////////////////////////////////////////////////////////// +// Vec4s steaming operators. +inline std::ostream& operator << (std::ostream& output, const Vec4s& vec) +{ + output << (int)vec._v[0] << " " + << (int)vec._v[1] << " " + << (int)vec._v[2] << " " + << (int)vec._v[3]; + return output; // to enable cascading +} + +inline std::istream& operator >> (std::istream& input, Vec4s& vec) +{ + input >> vec._v[0] >> std::ws + >> vec._v[1] >> std::ws + >> vec._v[2] >> std::ws + >> vec._v[3]; + return input; +} + + +////////////////////////////////////////////////////////////////////////// +// Matrixf steaming operators. +inline std::ostream& operator<< (std::ostream& os, const Matrixf& m ) +{ + os << "{"<> (std::istream& input, Vec4ub& vec) +{ + input >> vec._v[0] >> std::ws + >> vec._v[1] >> std::ws + >> vec._v[2] >> std::ws + >> vec._v[3]; + return input; +} + + +////////////////////////////////////////////////////////////////////////// +// Quat steaming operators. +inline std::ostream& operator << (std::ostream& output, const Quat& vec) +{ + output << vec._v[0] << " " + << vec._v[1] << " " + << vec._v[2] << " " + << vec._v[3]; + return output; // to enable cascading +} + +inline std::istream& operator >> (std::istream& input, Quat& vec) +{ + input >> vec._v[0] >> std::ws + >> vec._v[1] >> std::ws + >> vec._v[2] >> std::ws + >> vec._v[3]; + return input; +} + + + +////////////////////////////////////////////////////////////////////////// +// Plane steaming operators. +inline std::ostream& operator << (std::ostream& output, const Plane& pl) +{ + output << pl[0] << " " + << pl[1] << " " + << pl[2] << " " + << pl[3]; + return output; // to enable cascading +} + +inline std::istream& operator >> (std::istream& input, Plane& vec) +{ + input >> vec[0] >> std::ws + >> vec[1] >> std::ws + >> vec[2] >> std::ws + >> vec[3]; + return input; +} + +} // end of namespace osg +#endif diff --git a/libs/include/android/osg/observer_ptr b/libs/include/android/osg/observer_ptr new file mode 100755 index 0000000..01bc71b --- /dev/null +++ b/libs/include/android/osg/observer_ptr @@ -0,0 +1,159 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_OBSERVER_PTR +#define OSG_OBSERVER_PTR + +#include +#include +#include + +#include +#include + +namespace osg { + +/** Smart pointer for observed objects, that automatically set pointers to them to null when they are deleted. + * To use the observer_ptr<> robustly in multi-threaded applications it is recommend to access the pointer via + * the lock() method that passes back a ref_ptr<> that safely takes a reference to the object to prevent deletion + * during usage of the object. In certain conditions it may be safe to use the pointer directly without using lock(), + * which will confer a perfomance advantage, the conditions are: + * 1) The data structure is only accessed/deleted in single threaded/serial way. + * 2) The data strucutre is guarenteed by high level management of data strucutures and threads which avoid + * possible situations where the observer_ptr<>'s object may be deleted by one thread whilst being accessed + * by another. + * If you are in any doubt about whether it is safe to access the object safe then use the + * ref_ptr<> observer_ptr<>.lock() combination. */ +template +class observer_ptr +{ +public: + typedef T element_type; + observer_ptr() : _reference(0), _ptr(0) {} + + /** + * Create a observer_ptr from a ref_ptr. + */ + observer_ptr(const ref_ptr& rp) + { + _reference = rp.valid() ? rp->getOrCreateObserverSet() : 0; + _ptr = (_reference.valid() && _reference->getObserverdObject()!=0) ? rp.get() : 0; + } + + /** + * Create a observer_ptr from a raw pointer. For compatibility; + * the result might not be lockable. + */ + observer_ptr(T* rp) + { + _reference = rp ? rp->getOrCreateObserverSet() : 0; + _ptr = (_reference.valid() && _reference->getObserverdObject()!=0) ? rp : 0; + } + + observer_ptr(const observer_ptr& wp) : + _reference(wp._reference), + _ptr(wp._ptr) + { + } + + ~observer_ptr() + { + } + + observer_ptr& operator = (const observer_ptr& wp) + { + if (&wp==this) return *this; + + _reference = wp._reference; + _ptr = wp._ptr; + return *this; + } + + observer_ptr& operator = (const ref_ptr& rp) + { + _reference = rp.valid() ? rp->getOrCreateObserverSet() : 0; + _ptr = (_reference.valid() && _reference->getObserverdObject()!=0) ? rp.get() : 0; + return *this; + } + + observer_ptr& operator = (T* rp) + { + _reference = rp ? rp->getOrCreateObserverSet() : 0; + _ptr = (_reference.valid() && _reference->getObserverdObject()!=0) ? rp : 0; + return *this; + } + + /** + * Assign the observer_ptr to a ref_ptr. The ref_ptr will be valid if the + * referenced object hasn't been deleted and has a ref count > 0. + */ + bool lock(ref_ptr& rptr) const + { + if (!_reference) + { + rptr = 0; + return false; + } + + Referenced* obj = _reference->addRefLock(); + if (!obj) + { + rptr = 0; + return false; + } + + rptr = _ptr; + obj->unref_nodelete(); + return rptr.valid(); + } + + /** Comparison operators. These continue to work even after the + * observed object has been deleted. + */ + bool operator == (const observer_ptr& wp) const { return _reference == wp._reference; } + bool operator != (const observer_ptr& wp) const { return _reference != wp._reference; } + bool operator < (const observer_ptr& wp) const { return _reference < wp._reference; } + bool operator > (const observer_ptr& wp) const { return _reference > wp._reference; } + + // Non-strict interface, for compatibility + // comparison operator for const T*. + inline bool operator == (const T* ptr) const { return _ptr == ptr; } + inline bool operator != (const T* ptr) const { return _ptr != ptr; } + inline bool operator < (const T* ptr) const { return _ptr < ptr; } + inline bool operator > (const T* ptr) const { return _ptr > ptr; } + + // Convenience methods for operating on object, however, access is not automatically threadsafe. + // To make thread safe, one should either ensure at a high level + // that the object will not be deleted while operating on it, or + // by using the observer_ptr<>::lock() to get a ref_ptr<> that + // ensures the objects stay alive throughout all access to it. + + // Throw an error if _reference is null? + inline T& operator*() const { return *_ptr; } + inline T* operator->() const { return _ptr; } + + // get the raw C pointer + inline T* get() const { return (_reference.valid() && _reference->getObserverdObject()!=0) ? _ptr : 0; } + + inline bool operator!() const { return get() == 0; } + inline bool valid() const { return get() != 0; } + +protected: + + osg::ref_ptr _reference; + T* _ptr; +}; + +} + +#endif diff --git a/libs/include/android/osg/ref_ptr b/libs/include/android/osg/ref_ptr new file mode 100755 index 0000000..956cb61 --- /dev/null +++ b/libs/include/android/osg/ref_ptr @@ -0,0 +1,142 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_REF_PTR +#define OSG_REF_PTR 1 + +#include + +namespace osg { + +template class observer_ptr; + +/** Smart pointer for handling referenced counted objects.*/ +template +class ref_ptr +{ + public: + typedef T element_type; + + ref_ptr() : _ptr(0) {} + ref_ptr(T* ptr) : _ptr(ptr) { if (_ptr) _ptr->ref(); } + ref_ptr(const ref_ptr& rp) : _ptr(rp._ptr) { if (_ptr) _ptr->ref(); } + template ref_ptr(const ref_ptr& rp) : _ptr(rp._ptr) { if (_ptr) _ptr->ref(); } + ref_ptr(observer_ptr& optr) : _ptr(0) { optr.lock(*this); } + ~ref_ptr() { if (_ptr) _ptr->unref(); _ptr = 0; } + + ref_ptr& operator = (const ref_ptr& rp) + { + assign(rp); + return *this; + } + + template ref_ptr& operator = (const ref_ptr& rp) + { + assign(rp); + return *this; + } + + inline ref_ptr& operator = (T* ptr) + { + if (_ptr==ptr) return *this; + T* tmp_ptr = _ptr; + _ptr = ptr; + if (_ptr) _ptr->ref(); + // unref second to prevent any deletion of any object which might + // be referenced by the other object. i.e rp is child of the + // original _ptr. + if (tmp_ptr) tmp_ptr->unref(); + return *this; + } + +#ifdef OSG_USE_REF_PTR_IMPLICIT_OUTPUT_CONVERSION + // implicit output conversion + operator T*() const { return _ptr; } +#else + // comparison operators for ref_ptr. + bool operator == (const ref_ptr& rp) const { return (_ptr==rp._ptr); } + bool operator == (const T* ptr) const { return (_ptr==ptr); } + friend bool operator == (const T* ptr, const ref_ptr& rp) { return (ptr==rp._ptr); } + + bool operator != (const ref_ptr& rp) const { return (_ptr!=rp._ptr); } + bool operator != (const T* ptr) const { return (_ptr!=ptr); } + friend bool operator != (const T* ptr, const ref_ptr& rp) { return (ptr!=rp._ptr); } + + bool operator < (const ref_ptr& rp) const { return (_ptr() const { return _ptr; } + T* get() const { return _ptr; } + + bool operator!() const { return _ptr==0; } // not required + bool valid() const { return _ptr!=0; } + + /** release the pointer from ownership by this ref_ptr<>, decrementing the objects refencedCount() via unref_nodelete() to prevent the Object + * object from being deleted even if the reference count goes to zero. Use when using a local ref_ptr<> to an Object that you want to return + * from a function/method via a C pointer, whilst preventing the normal ref_ptr<> destructor from cleaning up the object. When using release() + * you are implicitly expecting other code to take over managment of the object, otherwise a memory leak will result. */ + T* release() { T* tmp=_ptr; if (_ptr) _ptr->unref_nodelete(); _ptr=0; return tmp; } + + void swap(ref_ptr& rp) { T* tmp=_ptr; _ptr=rp._ptr; rp._ptr=tmp; } + + private: + + template void assign(const ref_ptr& rp) + { + if (_ptr==rp._ptr) return; + T* tmp_ptr = _ptr; + _ptr = rp._ptr; + if (_ptr) _ptr->ref(); + // unref second to prevent any deletion of any object which might + // be referenced by the other object. i.e rp is child of the + // original _ptr. + if (tmp_ptr) tmp_ptr->unref(); + } + + template friend class ref_ptr; + + T* _ptr; +}; + + +template inline +void swap(ref_ptr& rp1, ref_ptr& rp2) { rp1.swap(rp2); } + +template inline +T* get_pointer(const ref_ptr& rp) { return rp.get(); } + +template inline +ref_ptr static_pointer_cast(const ref_ptr& rp) { return static_cast(rp.get()); } + +template inline +ref_ptr dynamic_pointer_cast(const ref_ptr& rp) { return dynamic_cast(rp.get()); } + +template inline +ref_ptr const_pointer_cast(const ref_ptr& rp) { return const_cast(rp.get()); } + +} + +#endif diff --git a/libs/include/android/osgAnimation/Action b/libs/include/android/osgAnimation/Action new file mode 100755 index 0000000..7b2be26 --- /dev/null +++ b/libs/include/android/osgAnimation/Action @@ -0,0 +1,147 @@ +/* -*-c++-*- + * Copyright (C) 2009 Cedric Pinson + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGANIMATION_ACTION_H +#define OSGANIMATION_ACTION_H + +#include +#include +#include +#include +#include + +#define META_Action(library,name) \ + virtual osg::Object* cloneType() const { return new name (); } \ + virtual osg::Object* clone(const osg::CopyOp& copyop) const { return new name (*this,copyop); } \ + virtual bool isSameKindAs(const osg::Object* obj) const { return dynamic_cast(obj)!=NULL; } \ + virtual const char* className() const { return #name; } \ + virtual const char* libraryName() const { return #library; } \ + virtual void accept(osgAnimation::ActionVisitor& nv) { nv.apply(*this); } \ + + +namespace osgAnimation +{ + + class OSGANIMATION_EXPORT Action : public osg::Object + { + public: + + class Callback : public osg::Object + { + public: + Callback(){} + Callback(const Callback& nc,const osg::CopyOp&) : + _nestedCallback(nc._nestedCallback) {} + + META_Object(osgAnimation,Callback); + + virtual void operator()(Action* /*action*/, osgAnimation::ActionVisitor* /*nv*/) {} + + Callback* getNestedCallback() { return _nestedCallback.get(); } + void addNestedCallback(Callback* callback) + { + if (callback) { + if (_nestedCallback.valid()) + _nestedCallback->addNestedCallback(callback); + else + _nestedCallback = callback; + } + } + + void removeCallback(Callback* cb) + { + if (!cb) + return; + + if (_nestedCallback.get() == cb) + _nestedCallback = _nestedCallback->getNestedCallback(); + else if (_nestedCallback.valid()) + _nestedCallback->removeCallback(cb); + } + + protected: + osg::ref_ptr _nestedCallback; + }; + + + typedef std::map > FrameCallback; + + META_Action(osgAnimation, Action); + + Action(); + Action(const Action&,const osg::CopyOp&); + + void setCallback(double when, Callback* callback) + { + setCallback(static_cast(floor(when*_fps)), callback); + } + + void setCallback(unsigned int frame, Callback* callback) + { + if (_framesCallback[frame].valid()) + _framesCallback[frame]->addNestedCallback(callback); + else + _framesCallback[frame] = callback; + } + Callback* getCallback(unsigned int frame) + { + if (_framesCallback.find(frame) == _framesCallback.end()) + return 0; + return _framesCallback[frame].get(); + } + + void removeCallback(Callback*); + + Callback* getFrameCallback(unsigned int frame); + Callback* getFrameCallback(double time); + unsigned int getFramesPerSecond() const { return _fps; } + + void setNumFrames(unsigned int numFrames) { _numberFrame = numFrames;} + void setDuration(double duration) { _numberFrame = static_cast(floor(duration * _fps)); } + unsigned int getNumFrames() const { return _numberFrame;} + double getDuration() const { return _numberFrame * 1.0 / _fps; } + + // 0 means infini else it's the number of loop + virtual void setLoop(unsigned int nb) { _loop = nb; } + virtual unsigned int getLoop() const { return _loop;} + + // get the number of loop, the frame relative to loop. + // return true if in range, and false if out of range. + bool evaluateFrame(unsigned int frame, unsigned int& resultframe, unsigned int& nbloop ); + virtual void traverse(ActionVisitor& /*visitor*/) {} + //virtual void evaluate(unsigned int frame); + + protected: + FrameCallback _framesCallback; + + double _speed; + unsigned int _fps; + unsigned int _numberFrame; + unsigned int _loop; + + enum Status + { + Play, + Stop + }; + + Status _state; + }; + + + + +} + +#endif diff --git a/libs/include/android/osgAnimation/ActionAnimation b/libs/include/android/osgAnimation/ActionAnimation new file mode 100755 index 0000000..0c3fdce --- /dev/null +++ b/libs/include/android/osgAnimation/ActionAnimation @@ -0,0 +1,41 @@ +/* -*-c++-*- + * Copyright (C) 2009 Cedric Pinson + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGANIMATION_ACTION_ANIMATION_H +#define OSGANIMATION_ACTION_ANIMATION_H + +#include +#include + + +namespace osgAnimation { + + + class OSGANIMATION_EXPORT ActionAnimation : public Action + { + public: + META_Action(osgAnimation, ActionAnimation); + ActionAnimation(); + ActionAnimation(const ActionAnimation& a, const osg::CopyOp& c); + ActionAnimation(Animation* animation); + void updateAnimation(unsigned int frame, int priority); + Animation* getAnimation() { return _animation.get(); } + + protected: + osg::ref_ptr _animation; + }; + +} + +#endif diff --git a/libs/include/android/osgAnimation/ActionBlendIn b/libs/include/android/osgAnimation/ActionBlendIn new file mode 100755 index 0000000..b5702b9 --- /dev/null +++ b/libs/include/android/osgAnimation/ActionBlendIn @@ -0,0 +1,44 @@ +/* -*-c++-*- + * Copyright (C) 2009 Cedric Pinson + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. + */ + +#ifndef OSGANIMATION_ACTION_BLENDIN_H +#define OSGANIMATION_ACTION_BLENDIN_H + +#include +#include + + +namespace osgAnimation { + + + /// blend in from 0 to weight in duration + class OSGANIMATION_EXPORT ActionBlendIn : public Action + { + public: + META_Action(osgAnimation, ActionBlendIn); + ActionBlendIn(); + ActionBlendIn(const ActionBlendIn& a, const osg::CopyOp& c); + ActionBlendIn(Animation* animation, double duration, double weight); + double getWeight() const { return _weight;} + Animation* getAnimation() { return _animation.get(); } + void computeWeight(unsigned int frame); + + protected: + double _weight; + osg::ref_ptr _animation; + }; + +} + +#endif diff --git a/libs/include/android/osgAnimation/ActionBlendOut b/libs/include/android/osgAnimation/ActionBlendOut new file mode 100755 index 0000000..5a12ad9 --- /dev/null +++ b/libs/include/android/osgAnimation/ActionBlendOut @@ -0,0 +1,45 @@ +/* -*-c++-*- + * Copyright (C) 2009 Cedric Pinson + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. + */ + +#ifndef OSGANIMATION_ACTION_BLENDOUT_H +#define OSGANIMATION_ACTION_BLENDOUT_H + +#include +#include + + +namespace osgAnimation { + + + /// blend out from weight to 0 in duration + class OSGANIMATION_EXPORT ActionBlendOut : public Action + { + public: + META_Action(osgAnimation, ActionBlendOut); + ActionBlendOut(); + ActionBlendOut(const ActionBlendOut& a, const osg::CopyOp& c); + ActionBlendOut(Animation* animation, double duration); + Animation* getAnimation() { return _animation.get(); } + double getWeight() const { return _weight;} + void computeWeight(unsigned int frame); + + protected: + double _weight; + osg::ref_ptr _animation; + + }; + +} + +#endif diff --git a/libs/include/android/osgAnimation/ActionCallback b/libs/include/android/osgAnimation/ActionCallback new file mode 100755 index 0000000..cb5845d --- /dev/null +++ b/libs/include/android/osgAnimation/ActionCallback @@ -0,0 +1,41 @@ +/* -*-c++-*- + * Copyright (C) 2009 Cedric Pinson + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGANIMATION_ACTION_CALLBACK_H +#define OSGANIMATION_ACTION_CALLBACK_H + +#include +#include + +namespace osgAnimation +{ + + /** Callback used to run new action on the timeline.*/ + class OSGANIMATION_EXPORT RunAction : public Action::Callback + { + public: + RunAction(Action* a, int priority = 0) : _action(a), _priority(priority) {} + virtual void operator()(Action* action, ActionVisitor* visitor); + + Action* getAction() const { return _action.get(); } + int getPriority() const { return _priority; } + protected: + osg::ref_ptr _action; + int _priority; + + }; + +} + +#endif diff --git a/libs/include/android/osgAnimation/ActionStripAnimation b/libs/include/android/osgAnimation/ActionStripAnimation new file mode 100755 index 0000000..82f3101 --- /dev/null +++ b/libs/include/android/osgAnimation/ActionStripAnimation @@ -0,0 +1,57 @@ +/* -*-c++-*- + * Copyright (C) 2009 Cedric Pinson + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGANIMATION_ACTION_STRIPANIMATION_H +#define OSGANIMATION_ACTION_STRIPANIMATION_H + +#include +#include +#include +#include +#include +#include + +namespace osgAnimation +{ + + // encapsulate animation with blend in blend out for classic usage + class OSGANIMATION_EXPORT ActionStripAnimation : public Action + { + public: + META_Action(osgAnimation, ActionStripAnimation); + ActionStripAnimation() {} + ActionStripAnimation(const ActionStripAnimation& a, const osg::CopyOp& c); + ActionStripAnimation(Animation* animation, double blendInDuration = 0.0, double blendOutDuration = 0.0, double blendInWeightTarget = 1.0 ); + ActionAnimation* getAnimation(); + ActionBlendIn* getBlendIn(); + ActionBlendOut* getBlendOut(); + const ActionAnimation* getAnimation() const; + const ActionBlendIn* getBlendIn() const; + const ActionBlendOut* getBlendOut() const; + unsigned int getBlendOutStartFrame() const; + + unsigned int getLoop() const; + void setLoop(unsigned int loop); + void traverse(ActionVisitor& visitor); + + protected: + typedef std::pair > FrameBlendOut; + osg::ref_ptr _blendIn; + FrameBlendOut _blendOut; + osg::ref_ptr _animation; + }; + +} + +#endif diff --git a/libs/include/android/osgAnimation/ActionVisitor b/libs/include/android/osgAnimation/ActionVisitor new file mode 100755 index 0000000..18d11f2 --- /dev/null +++ b/libs/include/android/osgAnimation/ActionVisitor @@ -0,0 +1,117 @@ +/* -*-c++-*- + * Copyright (C) 2009 Cedric Pinson + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGANIMATION_ACTIONVISITOR_H +#define OSGANIMATION_ACTIONVISITOR_H + +#include +#include +#include +#include + +namespace osgAnimation +{ + + class Timeline; + class Action; + class ActionBlendIn; + class ActionBlendOut; + class ActionAnimation; + class ActionStripAnimation; + +#define META_ActionVisitor(library,name) \ + virtual const char* libraryName() const { return #library; }\ + virtual const char* className() const { return #name; } + + + class OSGANIMATION_EXPORT ActionVisitor : public osg::Referenced + { + public: + META_ActionVisitor(osgAnimation, ActionVisitor); + ActionVisitor(); + void traverse(Action& visitor); + + void pushFrameActionOnStack(const FrameAction& fa); + void popFrameAction(); + + void pushTimelineOnStack(Timeline* tm); + void popTimeline(); + + Timeline* getCurrentTimeline(); + void setCurrentLayer(int layer) { _currentLayer = layer;} + int getCurrentLayer() const { return _currentLayer; } + + const std::vector& getStackedFrameAction() const { return _stackFrameAction; } + + virtual void apply(Action& action); + virtual void apply(Timeline& tm); + virtual void apply(ActionBlendIn& action); + virtual void apply(ActionBlendOut& action); + virtual void apply(ActionAnimation& action); + virtual void apply(ActionStripAnimation& action); + + protected: + std::vector _stackFrameAction; + std::vector _stackTimeline; + int _currentLayer; + }; + + + class OSGANIMATION_EXPORT UpdateActionVisitor : public osgAnimation::ActionVisitor + { + protected: + unsigned int _frame; + unsigned int _currentAnimationPriority; + public: + META_ActionVisitor(osgAnimation, UpdateActionVisitor); + UpdateActionVisitor(); + void setFrame(unsigned int frame) { _frame = frame;} + + bool isActive(Action& action) const; + unsigned int getLocalFrame() const; + + void apply(Timeline& action); + void apply(Action& action); + void apply(ActionBlendIn& action); + void apply(ActionBlendOut& action); + void apply(ActionAnimation& action); + void apply(ActionStripAnimation& action); + + }; + + + class OSGANIMATION_EXPORT ClearActionVisitor : public osgAnimation::ActionVisitor + { + public: + enum ClearType { + BEFORE_FRAME, + AFTER_FRAME + }; + + META_ActionVisitor(osgAnimation, ClearActionVisitor); + ClearActionVisitor(ClearType type = BEFORE_FRAME); + void setFrame(unsigned int frame) { _frame = frame;} + + void apply(Timeline& action); + void apply(Action& action); + + protected: + unsigned int _frame; + std::vector > _remove; + ClearType _clearType; + }; + +} + +#endif diff --git a/libs/include/android/osgAnimation/Animation b/libs/include/android/osgAnimation/Animation new file mode 100755 index 0000000..99f1ded --- /dev/null +++ b/libs/include/android/osgAnimation/Animation @@ -0,0 +1,104 @@ +/* -*-c++-*- + * Copyright (C) 2008 Cedric Pinson + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGANIMATION_ANIMATION +#define OSGANIMATION_ANIMATION 1 + +#include +#include +#include +#include +#include +#include + +namespace osgAnimation +{ + + class OSGANIMATION_EXPORT Animation : public osg::Object + { + public: + META_Object(osgAnimation, Animation) + + Animation() : _duration(0), _weight(0), _startTime(0), _playmode(LOOP) {} + Animation(const osgAnimation::Animation&, const osg::CopyOp&); + + enum PlayMode + { + ONCE, + STAY, + LOOP, + PPONG + }; + + // addChannel insert the channel and call the computeDuration function + void addChannel (Channel* pChannel); + + /** Those accessors let you add and remove channels + * if you modify something that can change the duration + * you are supposed to call computeDuration or setDuration + */ + ChannelList& getChannels(); + const ChannelList& getChannels() const; + + /** Change the duration of animation + * then evaluate the animation in the range 0-duration + * it stretch the animation in time. + * see computeDuration too + */ + void setDuration(double duration); + + + /** Compute duration from channel and keyframes + * if the duration is not specified you should + * call this method before using it + */ + void computeDuration(); + + double getDuration() const; + + + void setWeight (float weight); + float getWeight() const; + + bool update (double time, int priority = 0); + void resetTargets(); + + void setPlayMode (PlayMode mode) { _playmode = mode; } + PlayMode getPlayMode() const { return _playmode; } + + void setStartTime(double time) { _startTime = time;} + double getStartTime() const { return _startTime;} + + protected: + + double computeDurationFromChannels() const; + + ~Animation() {} + + double _duration; + double _originalDuration; + float _weight; + double _startTime; + PlayMode _playmode; + ChannelList _channels; + + }; + + typedef std::vector > AnimationList; + typedef std::map > AnimationMap; + + +} + +#endif diff --git a/libs/include/android/osgAnimation/AnimationManagerBase b/libs/include/android/osgAnimation/AnimationManagerBase new file mode 100755 index 0000000..faf763d --- /dev/null +++ b/libs/include/android/osgAnimation/AnimationManagerBase @@ -0,0 +1,70 @@ +/* -*-c++-*- + * Copyright (C) 2008 Cedric Pinson + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGANIMATION_ANIMATION_MANAGER_BASE +#define OSGANIMATION_ANIMATION_MANAGER_BASE 1 + +#include +#include +#include +#include +#include + + + +namespace osgAnimation +{ + class OSGANIMATION_EXPORT AnimationManagerBase : public osg::NodeCallback + { + public: + typedef std::set > TargetSet; + + AnimationManagerBase(); + AnimationManagerBase(const AnimationManagerBase& b, const osg::CopyOp& copyop= osg::CopyOp::SHALLOW_COPY); + virtual ~AnimationManagerBase(); + virtual void buildTargetReference(); + virtual void registerAnimation (Animation*); + virtual void unregisterAnimation (Animation*); + virtual void link(osg::Node* subgraph); + virtual void update(double t) = 0; + virtual bool needToLink() const; + const AnimationList& getAnimationList() const { return _animations;} + + /** Callback method called by the NodeVisitor when visiting a node.*/ + virtual void operator()(osg::Node* node, osg::NodeVisitor* nv); + + /** Reset the value of targets + this Operation must be done each frame */ + void clearTargets(); + + + LinkVisitor* getOrCreateLinkVisitor(); + void setLinkVisitor(LinkVisitor*); + + /// set a flag to define the behaviour + void setAutomaticLink(bool); + bool getAutomaticLink() const; + bool isAutomaticLink() const { return getAutomaticLink(); } + void dirty(); + + protected: + + osg::ref_ptr _linker; + AnimationList _animations; + TargetSet _targets; + bool _needToLink; + bool _automaticLink; + }; +} +#endif diff --git a/libs/include/android/osgAnimation/AnimationUpdateCallback b/libs/include/android/osgAnimation/AnimationUpdateCallback new file mode 100755 index 0000000..2db6561 --- /dev/null +++ b/libs/include/android/osgAnimation/AnimationUpdateCallback @@ -0,0 +1,72 @@ +/* -*-c++-*- + * Copyright (C) 2009 Cedric Pinson + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGANIMATION_ANIMATION_UPDATE_CALLBACK +#define OSGANIMATION_ANIMATION_UPDATE_CALLBACK 1 + +#include +#include +#include +#include + +namespace osgAnimation +{ + + class AnimationUpdateCallbackBase : public virtual osg::Object + { + public: + virtual bool link(Channel* channel) = 0; + virtual int link(Animation* animation) = 0; + }; + + + template + class AnimationUpdateCallback : public AnimationUpdateCallbackBase, public T + { + public: + AnimationUpdateCallback() {} + AnimationUpdateCallback(const std::string& name) { T::setName(name);} + AnimationUpdateCallback(const AnimationUpdateCallback& apc,const osg::CopyOp& copyop): T(apc, copyop) {} + + META_Object(osgAnimation, AnimationUpdateCallback); + + const std::string& getName() const { return T::getName(); } + bool link(Channel* /*channel*/) { return 0; } + int link(Animation* animation) + { + if (T::getName().empty()) + { + osg::notify(osg::WARN) << "An update callback has no name, it means it could link only with \"\" named Target, often an error, discard" << std::endl; + return 0; + } + int nbLinks = 0; + for (ChannelList::iterator it = animation->getChannels().begin(); + it != animation->getChannels().end(); + ++it) + { + std::string targetName = (*it)->getTargetName(); + if (targetName == T::getName()) + { + AnimationUpdateCallbackBase* a = this; + a->link((*it).get()); + nbLinks++; + } + } + return nbLinks; + } + }; + +} + +#endif diff --git a/libs/include/android/osgAnimation/BasicAnimationManager b/libs/include/android/osgAnimation/BasicAnimationManager new file mode 100755 index 0000000..c753f6c --- /dev/null +++ b/libs/include/android/osgAnimation/BasicAnimationManager @@ -0,0 +1,53 @@ +/* -*-c++-*- + * Copyright (C) 2008 Cedric Pinson + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGANIMATION_BASIC_ANIMATION_MANAGER_H +#define OSGANIMATION_BASIC_ANIMATION_MANAGER_H + +#include +#include +#include +#include + +namespace osgAnimation +{ + class OSGANIMATION_EXPORT BasicAnimationManager : public AnimationManagerBase + { + public: + + META_Object(osgAnimation, BasicAnimationManager); + + BasicAnimationManager(); + BasicAnimationManager(const AnimationManagerBase& b, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY); + virtual ~BasicAnimationManager(); + + void update (double time); + + void playAnimation (Animation* pAnimation, int priority = 0, float weight = 1.0); + bool stopAnimation (Animation* pAnimation); + + bool findAnimation (Animation* pAnimation); + bool isPlaying (Animation* pAnimation); + bool isPlaying (const std::string& animationName); + + void stopAll(); + + protected: + typedef std::map AnimationLayers; + AnimationLayers _animationsPlaying; + double _lastUpdate; + }; + +} +#endif diff --git a/libs/include/android/osgAnimation/Bone b/libs/include/android/osgAnimation/Bone new file mode 100755 index 0000000..b2debed --- /dev/null +++ b/libs/include/android/osgAnimation/Bone @@ -0,0 +1,61 @@ +/* -*-c++-*- + * Copyright (C) 2008 Cedric Pinson + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. + * + * Authors: + * Cedric Pinson + * Michael Platings + */ + +#ifndef OSGANIMATION_BONE +#define OSGANIMATION_BONE 1 + +#include +#include + +namespace osgAnimation +{ + + // A bone can't have more than one parent Bone, so sharing a part of Bone's hierarchy + // makes no sense. You can share the entire hierarchy but not only a part of it. + class OSGANIMATION_EXPORT Bone : public osg::MatrixTransform + { + public: + typedef osg::Matrix MatrixType; + + META_Node(osgAnimation, Bone); + Bone(const Bone& b, const osg::CopyOp& copyop= osg::CopyOp::SHALLOW_COPY); + Bone(const std::string& name = ""); + + void setDefaultUpdateCallback(const std::string& name = ""); + + Bone* getBoneParent(); + const Bone* getBoneParent() const; + + const osg::Matrix& getMatrixInBoneSpace() const { return getMatrix();} + const osg::Matrix& getMatrixInSkeletonSpace() const { return _boneInSkeletonSpace; } + const osg::Matrix& getInvBindMatrixInSkeletonSpace() const { return _invBindInSkeletonSpace;} + void setMatrixInSkeletonSpace(const osg::Matrix& matrix) { _boneInSkeletonSpace = matrix; } + void setInvBindMatrixInSkeletonSpace(const osg::Matrix& matrix) { _invBindInSkeletonSpace = matrix; } + + protected: + + // bind data + osg::Matrix _invBindInSkeletonSpace; + + // bone updated + osg::Matrix _boneInSkeletonSpace; + }; + + typedef std::map > BoneMap; +} +#endif diff --git a/libs/include/android/osgAnimation/BoneMapVisitor b/libs/include/android/osgAnimation/BoneMapVisitor new file mode 100755 index 0000000..6095517 --- /dev/null +++ b/libs/include/android/osgAnimation/BoneMapVisitor @@ -0,0 +1,42 @@ +/* -*-c++-*- + * Copyright (C) 2009 Cedric Pinson + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. + * + * Authors: + * Cedric Pinson + */ + +#ifndef OSGANIMATION_BONEMAP_VISITOR +#define OSGANIMATION_BONEMAP_VISITOR 1 + +#include +#include +#include + +namespace osgAnimation +{ + class OSGANIMATION_EXPORT BoneMapVisitor : public osg::NodeVisitor + { + public: + META_NodeVisitor(osgAnimation, BoneMapVisitor) + BoneMapVisitor(); + + void apply(osg::Node&); + void apply(osg::Transform& node); + const BoneMap& getBoneMap() const; + + protected: + BoneMap _map; + }; +} + +#endif diff --git a/libs/include/android/osgAnimation/Channel b/libs/include/android/osgAnimation/Channel new file mode 100755 index 0000000..0b3df05 --- /dev/null +++ b/libs/include/android/osgAnimation/Channel @@ -0,0 +1,185 @@ +/* -*-c++-*- + * Copyright (C) 2008 Cedric Pinson + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. + * + * Authors: + * Cedric Pinson + * Michael Platings + */ + +#ifndef OSGANIMATION_CHANNEL +#define OSGANIMATION_CHANNEL 1 + +#include +#include +#include +#include +#include + +namespace osgAnimation +{ + + class OSGANIMATION_EXPORT Channel : public osg::Referenced + { + public: + + Channel(); + Channel(const Channel& channel); + virtual ~Channel(); + virtual Channel* clone() const = 0; + + virtual void update(double time, float weight, int priority) = 0; + virtual void reset() = 0; + virtual Target* getTarget() = 0; + virtual bool setTarget(Target*) = 0; + + const std::string& getName() const; + void setName(const std::string& name); + + virtual double getStartTime() const = 0; + virtual double getEndTime() const = 0; + + const std::string& getTargetName() const; + void setTargetName(const std::string& name); + + virtual Sampler* getSampler() = 0; + virtual const Sampler* getSampler() const = 0; + + // create a keyframe container from current target value + // with one key only, can be used for debug or to create + // easily a default channel from an existing one + virtual bool createKeyframeContainerFromTargetValue() = 0; + + protected: + + std::string _targetName; + std::string _name; + }; + + + template + class TemplateChannel : public Channel + { + public: + + typedef typename SamplerType::UsingType UsingType; + typedef TemplateTarget TargetType; + typedef TemplateKeyframeContainer KeyframeContainerType; + Channel* clone() const { return new TemplateChannel(*this); } + + TemplateChannel (const TemplateChannel& channel) : + Channel(channel) + { + if (channel.getTargetTyped()) + _target = new TargetType(*channel.getTargetTyped()); + + if (channel.getSamplerTyped()) + _sampler = new SamplerType(*channel.getSamplerTyped()); + } + + TemplateChannel (SamplerType* s = 0,TargetType* target = 0) + { + if (target) + _target = target; + else + _target = new TargetType; + _sampler = s; + } + + virtual bool createKeyframeContainerFromTargetValue() + { + if (!_target.valid()) // no target it does not make sense to do it + { + return false; + } + + // create a key from current target value + typename KeyframeContainerType::KeyType key(0, _target->getValue()); + // recreate the keyframe container + getOrCreateSampler()->setKeyframeContainer(0); + getOrCreateSampler()->getOrCreateKeyframeContainer(); + // add the key + _sampler->getKeyframeContainerTyped()->push_back(key); + return true; + } + + virtual ~TemplateChannel() {} + virtual void update(double time, float weight, int priority) + { + // skip if weight == 0 + if (weight < 1e-4) + return; + typename SamplerType::UsingType value; + _sampler->getValueAt(time, value); + _target->update(weight, value, priority); + } + virtual void reset() { _target->reset(); } + virtual Target* getTarget() { return _target.get();} + virtual bool setTarget(Target* target) + { + _target = dynamic_cast(target); + return _target.get() == target; + } + + SamplerType* getOrCreateSampler() + { + if (!_sampler.valid()) + _sampler = new SamplerType; + return _sampler.get(); + } + + Sampler* getSampler() { return _sampler.get(); } + const Sampler* getSampler() const { return _sampler.get(); } + + SamplerType* getSamplerTyped() { return _sampler.get();} + const SamplerType* getSamplerTyped() const { return _sampler.get();} + void setSampler(SamplerType* sampler) { _sampler = sampler; } + + TargetType* getTargetTyped() { return _target.get(); } + const TargetType* getTargetTyped() const { return _target.get(); } + void setTarget(TargetType* target) { _target = target; } + + virtual double getStartTime() const { return _sampler->getStartTime(); } + virtual double getEndTime() const { return _sampler->getEndTime(); } + + protected: + osg::ref_ptr _target; + osg::ref_ptr _sampler; + }; + + + typedef std::vector > ChannelList; + + typedef TemplateChannel DoubleStepChannel; + typedef TemplateChannel FloatStepChannel; + typedef TemplateChannel Vec2StepChannel; + typedef TemplateChannel Vec3StepChannel; + typedef TemplateChannel Vec4StepChannel; + typedef TemplateChannel QuatStepChannel; + + typedef TemplateChannel DoubleLinearChannel; + typedef TemplateChannel FloatLinearChannel; + typedef TemplateChannel Vec2LinearChannel; + typedef TemplateChannel Vec3LinearChannel; + typedef TemplateChannel Vec4LinearChannel; + typedef TemplateChannel QuatSphericalLinearChannel; + typedef TemplateChannel MatrixLinearChannel; + + typedef TemplateChannel FloatCubicBezierChannel; + typedef TemplateChannel DoubleCubicBezierChannel; + typedef TemplateChannel Vec2CubicBezierChannel; + typedef TemplateChannel Vec3CubicBezierChannel; + typedef TemplateChannel Vec4CubicBezierChannel; + +} + +#endif diff --git a/libs/include/android/osgAnimation/CubicBezier b/libs/include/android/osgAnimation/CubicBezier new file mode 100755 index 0000000..6b71838 --- /dev/null +++ b/libs/include/android/osgAnimation/CubicBezier @@ -0,0 +1,79 @@ +/* -*-c++-*- + * Copyright (C) 2008 Cedric Pinson + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGANIMATION_CUBIC_BEZIER +#define OSGANIMATION_CUBIC_BEZIER 1 + +#include +#include +#include + +namespace osgAnimation +{ + + template + class TemplateCubicBezier + { + public: + TemplateCubicBezier() {} + + TemplateCubicBezier(const T& p, const T& i, const T& o) : _position(p), _controlPointIn(i), _controlPointOut(o) + { + } + + // Constructor with value only + TemplateCubicBezier(const T& p) : _position(p), _controlPointIn(p), _controlPointOut(p) + { + } + + const T& getPosition() const { return _position;} + const T& getControlPointIn() const { return _controlPointIn;} + const T& getControlPointOut() const { return _controlPointOut;} + + T& getPosition() { return _position;} + T& getControlPointIn() { return _controlPointIn;} + T& getControlPointOut() { return _controlPointOut;} + + void setPosition(const T& v) {_position = v;} + void setControlPointIn(const T& v) {_controlPointIn = v;} + void setControlPointOut(const T& v) {_controlPointOut = v;} + + // steaming operators. + friend std::ostream& operator << (std::ostream& output, const TemplateCubicBezier& tcb) + { + output << tcb._position << " " + << tcb._controlPointIn << " " + << tcb._controlPointOut; + return output; // to enable cascading + } + + friend std::istream& operator >> (std::istream& input, TemplateCubicBezier& tcb) + { + input >> tcb._position >> tcb._controlPointIn >> tcb._controlPointOut; + return input; + } + + protected: + T _position, _controlPointIn, _controlPointOut; + }; + + typedef TemplateCubicBezier FloatCubicBezier; + typedef TemplateCubicBezier DoubleCubicBezier; + typedef TemplateCubicBezier Vec2CubicBezier; + typedef TemplateCubicBezier Vec3CubicBezier; + typedef TemplateCubicBezier Vec4CubicBezier; + +} + +#endif diff --git a/libs/include/android/osgAnimation/EaseMotion b/libs/include/android/osgAnimation/EaseMotion new file mode 100755 index 0000000..2270f95 --- /dev/null +++ b/libs/include/android/osgAnimation/EaseMotion @@ -0,0 +1,530 @@ +/* -*-c++-*- + * Copyright (C) 2008 Cedric Pinson + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. + */ + +#ifndef OSGANIMATION_EASE_MOTION +#define OSGANIMATION_EASE_MOTION 1 + +#include +#include +#include +#include +#include + +namespace osgAnimation +{ + struct OutBounceFunction + { + inline static void getValueAt(float t, float& result) + { + if ((t) < (1/2.75)) + { + result = 7.5625 * t * t; + } + else if (t < (2/2.75)) + { + t = t - (1.5/2.75); + result = 7.5625* t * t + .75; + } + else if (t < (2.5/2.75)) + { + t = t - (2.25/2.75); + result = 7.5625 * t * t + .9375; + } + else + { + t = t - (2.625/2.75); + result = 7.5625* t * t + .984375; + } + } + }; + + struct InBounceFunction + { + inline static void getValueAt(float t, float& result) + { + OutBounceFunction::getValueAt(1-t, result); + result = 1 - result; + } + }; + + struct InOutBounceFunction + { + inline static void getValueAt(float t, float& result) + { + if (t < 0.5) + { + InBounceFunction::getValueAt(t * 2, result); + result *= 0.5; + } + else + { + OutBounceFunction::getValueAt(t * 2 - 1 , result); + result = result * 0.5 + 0.5; + } + } + }; + + /// Linear function + struct LinearFunction + { + inline static void getValueAt(float t, float& result) { result = t;} + }; + + /// Quad function + struct OutQuadFunction + { + inline static void getValueAt(float t, float& result) { result = - (t * (t -2.0));} + }; + + struct InQuadFunction + { + inline static void getValueAt(float t, float& result) { result = t*t;} + }; + + struct InOutQuadFunction + { + inline static void getValueAt(float t, float& result) + { + t *= 2.0; + if (t < 1.0) + result = 0.5 * t * t; + else + { + t -= 1.0; + result = - 0.5 * (t * ( t - 2) - 1); + } + } + }; + + /// Cubic function + struct OutCubicFunction + { + inline static void getValueAt(float t, float& result) { t = t-1.0; result = t*t*t + 1;} + }; + + struct InCubicFunction + { + inline static void getValueAt(float t, float& result) { result = t*t*t;} + }; + + struct InOutCubicFunction + { + inline static void getValueAt(float t, float& result) + { + t *= 2.0f; + if (t < 1.0f) + result = 0.5f * t * t * t; + else { + t -= 2.0f; + result = 0.5 * (t * t * t + 2.0f); + } + } + }; + + /// Quart function + struct InQuartFunction + { + inline static void getValueAt(float t, float& result) { result = t*t*t*t*t;} + }; + + struct OutQuartFunction + { + inline static void getValueAt(float t, float& result) { t = t - 1; result = - (t*t*t*t -1); } + }; + + struct InOutQuartFunction + { + inline static void getValueAt(float t, float& result) + { + t = t * 2.0; + if ( t < 1) + result = 0.5*t*t*t*t; + else + { + t -= 2.0; + result = -0.5 * (t*t*t*t -2); + } + } + }; + + /// Elastic function + struct OutElasticFunction + { + inline static void getValueAt(float t, float& result) + { + result = pow(2.0f, -10.0f * t) * sinf((t - 0.3f / 4.0f) * (2.0f * osg::PI) / 0.3f) + 1.0f; + } + }; + + struct InElasticFunction + { + inline static void getValueAt(float t, float& result) + { + OutElasticFunction::getValueAt(1.0f - t, result); + result = 1.0f - result; + } + }; + + struct InOutElasticFunction + { + inline static void getValueAt(float t, float& result) + { + t *= 2.0f; + if (t < 1.0f) + { + t -= 1.0f; + result = -0.5 * (1.0f * pow(2.0f, 10.0f * t) * sinf((t - 0.45f / 4.0f) * (2.0f * osg::PI) / 0.45f)); + } + else + { + t -= 1.0f; + result = pow(2.0f, -10.0f * t) * sinf((t - 0.45f / 4.0f) * (2.0f * osg::PI) / 0.45f) * 0.5f + 1.0f; + } + } + }; + + // Sine function + struct OutSineFunction + { + inline static void getValueAt(float t, float& result) + { + result = sinf(t * (osg::PI / 2.0f)); + } + }; + + struct InSineFunction + { + inline static void getValueAt(float t, float& result) + { + result = -cosf(t * (osg::PI / 2.0f)) + 1.0f; + } + }; + + struct InOutSineFunction + { + inline static void getValueAt(float t, float& result) + { + result = -0.5f * (cosf((osg::PI * t)) - 1.0f); + } + }; + + // Back function + struct OutBackFunction + { + inline static void getValueAt(float t, float& result) + { + t -= 1.0f; + result = t * t * ((1.70158 + 1.0f) * t + 1.70158) + 1.0f; + } + }; + + struct InBackFunction + { + inline static void getValueAt(float t, float& result) + { + result = t * t * ((1.70158 + 1.0f) * t - 1.70158); + } + }; + + struct InOutBackFunction + { + inline static void getValueAt(float t, float& result) + { + float s = 1.70158 * 1.525f; + t *= 2.0f; + if (t < 1.0f) + { + result = 0.5f * (t * t * ((s + 1.0f) * t - s)); + } + else + { + float p = t -= 2.0f; + result = 0.5f * ((p) * t * ((s + 1.0f) * t + s) + 2.0f); + } + } + }; + + // Circ function + struct OutCircFunction + { + inline static void getValueAt(float t, float& result) + { + t -= 1.0f; + result = sqrt(1.0f - t * t); + } + }; + + struct InCircFunction + { + inline static void getValueAt(float t, float& result) + { + result = -(sqrt(1.0f - (t * t)) - 1.0f); + } + }; + + struct InOutCircFunction + { + inline static void getValueAt(float t, float& result) + { + t *= 2.0f; + if (t < 1.0f) + { + result = -0.5f * (sqrt(1.0f - t * t) - 1.0f); + } + else + { + t -= 2.0f; + result = 0.5f * (sqrt(1 - t * t) + 1.0f); + } + } + }; + + // Expo function + struct OutExpoFunction + { + inline static void getValueAt(float t, float& result) + { + if(t == 1.0f) + { + result = 0.0f; + } + else + { + result = -powf(2.0f, -10.0f * t) + 1.0f; + } + } + }; + + struct InExpoFunction + { + inline static void getValueAt(float t, float& result) + { + if(t == 0.0f) + { + result = 0.0f; + } + else + { + result = powf(2.0f, 10.0f * (t - 1.0f)); + } + } + }; + + struct InOutExpoFunction + { + inline static void getValueAt(float t, float& result) + { + if(t == 0.0f || t == 1.0f) + { + result = 0.0f; + } + else + { + t *= 2.0f; + if(t < 1.0f) + { + result = 0.5f * powf(2.0f, 10.0f * (t - 1.0f)); + } + else + { + result = 0.5f * (-powf(2.0f, -10.0f * (t - 1.0f)) + 2.0f); + } + } + } + }; + + class Motion : public osg::Referenced + { + public: + typedef float value_type; + enum TimeBehaviour + { + CLAMP, + LOOP + }; + Motion(float startValue = 0, float duration = 1, float changeValue = 1, TimeBehaviour tb = CLAMP) : _time(0), _startValue(startValue), _changeValue(changeValue), _duration(duration), _behaviour(tb) {} + virtual ~Motion() {} + void reset() { setTime(0);} + float getTime() const { return _time; } + float evaluateTime(float time) const + { + switch (_behaviour) + { + case CLAMP: + if (time > _duration) + time = _duration; + else if (time < 0.0) + time = 0.0; + break; + case LOOP: + if (time <= 0) + time = 0; + else + time = fmodf(time, _duration); + break; + } + return time; + } + + void update(float dt) + { + _time = evaluateTime(_time + dt); + } + + void setTime(float time) { _time = evaluateTime(time);} + void getValue(value_type& result) const { getValueAt(_time, result); } + value_type getValue() const + { + value_type result; + getValueAt(_time, result); + return result; + } + + void getValueAt(float time, value_type& result) const + { + getValueInNormalizedRange(evaluateTime(time)/_duration, result); + result = result * _changeValue + _startValue; + } + value_type getValueAt(float time) const + { + value_type result; + getValueAt(evaluateTime(time), result); + return result; + } + + virtual void getValueInNormalizedRange(float t, value_type& result) const = 0; + + float getDuration() const { return _duration;} + protected: + float _time; + float _startValue; + float _changeValue; + float _duration; + TimeBehaviour _behaviour; + }; + + + + template + struct MathMotionTemplate : public Motion + { + MathMotionTemplate(float startValue = 0, float duration = 1, float changeValue = 1, TimeBehaviour tb = CLAMP) : Motion(startValue, duration, changeValue, tb) {} + virtual void getValueInNormalizedRange(float t, value_type& result) const { T::getValueAt(t, result); } + }; + + template + struct SamplerMotionTemplate : public Motion + { + T _sampler; + SamplerMotionTemplate(float startValue = 0, float duration = 1, float changeValue = 1, TimeBehaviour tb = CLAMP) : Motion(startValue, duration, changeValue, tb) {} + T& getSampler() { return _sampler;} + const T& getSampler() const { return _sampler;} + virtual void getValueInNormalizedRange(float t, value_type& result) const + { + if (!_sampler.getKeyframeContainer()) + { + result = 0; + return; + } + float size = _sampler.getEndTime() - _sampler.getStartTime(); + t = t * size + _sampler.getStartTime(); + _sampler.getValueAt(t, result); + } + }; + + struct CompositeMotion : public Motion + { + typedef std::vector > MotionList; + MotionList _motions; + + MotionList& getMotionList() { return _motions; } + const MotionList& getMotionList() const { return _motions; } + CompositeMotion(float startValue = 0, float duration = 1, float changeValue = 1, TimeBehaviour tb = CLAMP) : Motion(startValue, duration, changeValue, tb) {} + + virtual void getValueInNormalizedRange(float t, value_type& result) const + { + if (_motions.empty()) + { + result = 0; + osg::notify(osg::WARN) << "CompositeMotion::getValueInNormalizedRange no Motion in the CompositeMotion, add motion to have result" << std::endl; + return; + } + for (MotionList::const_iterator it = _motions.begin(); it != _motions.end(); ++it) + { + const Motion* motion = static_cast(it->get()); + float durationInRange = motion->getDuration() / getDuration(); + if (t < durationInRange) + { + float tInRange = t/durationInRange * motion->getDuration(); + motion->getValueAt( tInRange, result); + return; + } else + t = t - durationInRange; + } + osg::notify(osg::WARN) << "CompositeMotion::getValueInNormalizedRange did find the value in range, something wrong" << std::endl; + result = 0; + } + }; + + + // linear + typedef MathMotionTemplate LinearMotion; + + // quad + typedef MathMotionTemplate OutQuadMotion; + typedef MathMotionTemplate InQuadMotion; + typedef MathMotionTemplate InOutQuadMotion; + + // cubic + typedef MathMotionTemplate OutCubicMotion; + typedef MathMotionTemplate InCubicMotion; + typedef MathMotionTemplate InOutCubicMotion; + + // quart + typedef MathMotionTemplate OutQuartMotion; + typedef MathMotionTemplate InQuartMotion; + typedef MathMotionTemplate InOutQuartMotion; + + // bounce + typedef MathMotionTemplate OutBounceMotion; + typedef MathMotionTemplate InBounceMotion; + typedef MathMotionTemplate InOutBounceMotion; + + // elastic + typedef MathMotionTemplate OutElasticMotion; + typedef MathMotionTemplate InElasticMotion; + typedef MathMotionTemplate InOutElasticMotion; + + // sine + typedef MathMotionTemplate OutSineMotion; + typedef MathMotionTemplate InSineMotion; + typedef MathMotionTemplate InOutSineMotion; + + // back + typedef MathMotionTemplate OutBackMotion; + typedef MathMotionTemplate InBackMotion; + typedef MathMotionTemplate InOutBackMotion; + + // circ + typedef MathMotionTemplate OutCircMotion; + typedef MathMotionTemplate InCircMotion; + typedef MathMotionTemplate InOutCircMotion; + + // expo + typedef MathMotionTemplate OutExpoMotion; + typedef MathMotionTemplate InExpoMotion; + typedef MathMotionTemplate InOutExpoMotion; +} + +#endif diff --git a/libs/include/android/osgAnimation/Export b/libs/include/android/osgAnimation/Export new file mode 100755 index 0000000..ba26765 --- /dev/null +++ b/libs/include/android/osgAnimation/Export @@ -0,0 +1,67 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +// The following symbol has a underscore suffix for compatibility. +#ifndef OSGANIMATION_EXPORT_ +#define OSGANIMATION_EXPORT_ 1 + +#include + +#if defined(_MSC_VER) && defined(OSG_DISABLE_MSVC_WARNINGS) + #pragma warning( disable : 4244 ) + #pragma warning( disable : 4251 ) + #pragma warning( disable : 4267 ) + #pragma warning( disable : 4275 ) + #pragma warning( disable : 4290 ) + #pragma warning( disable : 4786 ) + #pragma warning( disable : 4305 ) + #pragma warning( disable : 4996 ) +#endif + +#if defined(_MSC_VER) || defined(__CYGWIN__) || defined(__MINGW32__) || defined( __BCPLUSPLUS__) || defined( __MWERKS__) + # if defined( OSG_LIBRARY_STATIC ) + # define OSGANIMATION_EXPORT + # elif defined( OSGANIMATION_LIBRARY ) + # define OSGANIMATION_EXPORT __declspec(dllexport) + # else + # define OSGANIMATION_EXPORT __declspec(dllimport) + #endif +#else + #define OSGANIMATION_EXPORT +#endif + +// set up define for whether member templates are supported by VisualStudio compilers. +#ifdef _MSC_VER +# if (_MSC_VER >= 1300) +# define __STL_MEMBER_TEMPLATES +# endif +#endif +/* Define NULL pointer value */ + +#ifndef NULL + #ifdef __cplusplus + #define NULL 0 + #else + #define NULL ((void *)0) + #endif +#endif + +/** + +\namespace osgAnimation + +The osgAnimation library provides general purpose utility classes for animation. + +*/ + +#endif diff --git a/libs/include/android/osgAnimation/FrameAction b/libs/include/android/osgAnimation/FrameAction new file mode 100755 index 0000000..f424133 --- /dev/null +++ b/libs/include/android/osgAnimation/FrameAction @@ -0,0 +1,26 @@ +/* -*-c++-*- + * Copyright (C) 2009 Cedric Pinson + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGANIMATION_FRAMEACTION_H +#define OSGANIMATION_FRAMEACTION_H + +#include +#include + +namespace osgAnimation +{ + class Action; + typedef std::pair > FrameAction; +} +#endif diff --git a/libs/include/android/osgAnimation/Interpolator b/libs/include/android/osgAnimation/Interpolator new file mode 100755 index 0000000..1190e3a --- /dev/null +++ b/libs/include/android/osgAnimation/Interpolator @@ -0,0 +1,240 @@ +/* -*-c++-*- + * Copyright (C) 2008 Cedric Pinson + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. + * + * Authors: + * Cedric Pinson + * Michael Platings + */ + +#ifndef OSGANIMATION_INTERPOLATOR +#define OSGANIMATION_INTERPOLATOR 1 + +#include +#include + +namespace osgAnimation +{ + + template + class TemplateInterpolatorBase + { + public: + typedef KEY KeyframeType; + typedef TYPE UsingType; + + public: + mutable int _lastKeyAccess; + + TemplateInterpolatorBase() : _lastKeyAccess(-1) {} + + void reset() { _lastKeyAccess = -1; } + int getKeyIndexFromTime(const TemplateKeyframeContainer& keys, double time) const + { + // todo use a cache + int key_size = keys.size(); + if (!key_size) { + osg::notify(osg::WARN) << "TemplateInterpolatorBase::getKeyIndexFromTime the container is empty, impossible to get key index from time" << std::endl;; + return -1; + } + const TemplateKeyframe* keysVector = &keys.front(); + for (int i = 0; i < key_size-1; i++) + { + double time0 = keysVector[i].getTime(); + double time1 = keysVector[i+1].getTime(); + + if ( time >= time0 && time < time1 ) + { + _lastKeyAccess = i; + return i; + } + } + osg::notify(osg::WARN) << time << " first key " << keysVector[0].getTime() << " last key " << keysVector[key_size-1].getTime() << std::endl; + return -1; + } + }; + + + template + class TemplateStepInterpolator : public TemplateInterpolatorBase + { + public: + + TemplateStepInterpolator() {} + void getValue(const TemplateKeyframeContainer& keyframes, double time, TYPE& result) const + { + + if (time >= keyframes.back().getTime()) + { + result = keyframes.back().getValue(); + return; + } + else if (time <= keyframes.front().getTime()) + { + result = keyframes.front().getValue(); + return; + } + + int i = this->getKeyIndexFromTime(keyframes,time); + result = keyframes[i].getValue(); + } + }; + + + template + class TemplateLinearInterpolator : public TemplateInterpolatorBase + { + public: + + TemplateLinearInterpolator() {} + void getValue(const TemplateKeyframeContainer& keyframes, double time, TYPE& result) const + { + + if (time >= keyframes.back().getTime()) + { + result = keyframes.back().getValue(); + return; + } + else if (time <= keyframes.front().getTime()) + { + result = keyframes.front().getValue(); + return; + } + + int i = this->getKeyIndexFromTime(keyframes,time); + float blend = (time - keyframes[i].getTime()) / ( keyframes[i+1].getTime() - keyframes[i].getTime()); + const TYPE& v1 = keyframes[i].getValue(); + const TYPE& v2 = keyframes[i+1].getValue(); + result = v1*(1-blend) + v2*blend; + } + }; + + + template + class TemplateSphericalLinearInterpolator : public TemplateInterpolatorBase + { + public: + TemplateSphericalLinearInterpolator() {} + void getValue(const TemplateKeyframeContainer& keyframes, double time, TYPE& result) const + { + if (time >= keyframes.back().getTime()) + { + result = keyframes.back().getValue(); + return; + } + else if (time <= keyframes.front().getTime()) + { + result = keyframes.front().getValue(); + return; + } + + int i = this->getKeyIndexFromTime(keyframes,time); + float blend = (time - keyframes[i].getTime()) / ( keyframes[i+1].getTime() - keyframes[i].getTime()); + const TYPE& q1 = keyframes[i].getValue(); + const TYPE& q2 = keyframes[i+1].getValue(); + result.slerp(blend,q1,q2); + } + }; + + + template + class TemplateLinearPackedInterpolator : public TemplateInterpolatorBase + { + public: + + TemplateLinearPackedInterpolator() {} + void getValue(const TemplateKeyframeContainer& keyframes, double time, TYPE& result) const + { + if (time >= keyframes.back().getTime()) + { + keyframes.back().getValue().uncompress(keyframes.mScale, keyframes.mMin, result); + return; + } + else if (time <= keyframes.front().getTime()) + { + keyframes.front().getValue().uncompress(keyframes.mScale, keyframes.mMin, result); + return; + } + + int i = this->getKeyIndexFromTime(keyframes,time); + float blend = (time - keyframes[i].getTime()) / ( keyframes[i+1].getTime() - keyframes[i].getTime()); + TYPE v1,v2; + keyframes[i].getValue().uncompress(keyframes.mScale, keyframes.mMin, v1); + keyframes[i+1].getValue().uncompress(keyframes.mScale, keyframes.mMin, v2); + result = v1*(1-blend) + v2*blend; + } + }; + + + // http://en.wikipedia.org/wiki/B%C3%A9zier_curve + template + class TemplateCubicBezierInterpolator : public TemplateInterpolatorBase + { + public: + + TemplateCubicBezierInterpolator() {} + void getValue(const TemplateKeyframeContainer& keyframes, double time, TYPE& result) const + { + + if (time >= keyframes.back().getTime()) + { + result = keyframes.back().getValue().getPosition(); + return; + } + else if (time <= keyframes.front().getTime()) + { + result = keyframes.front().getValue().getPosition(); + return; + } + + int i = this->getKeyIndexFromTime(keyframes,time); + + float t = (time - keyframes[i].getTime()) / ( keyframes[i+1].getTime() - keyframes[i].getTime()); + float one_minus_t = 1.0-t; + float one_minus_t2 = one_minus_t * one_minus_t; + float one_minus_t3 = one_minus_t2 * one_minus_t; + float t2 = t * t; + + TYPE v0 = keyframes[i].getValue().getPosition() * one_minus_t3; + TYPE v1 = keyframes[i].getValue().getControlPointIn() * (3.0 * t * one_minus_t2); + TYPE v2 = keyframes[i].getValue().getControlPointOut() * (3.0 * t2 * one_minus_t); + TYPE v3 = keyframes[i+1].getValue().getPosition() * (t2 * t); + + result = v0 + v1 + v2 + v3; + } + }; + + typedef TemplateStepInterpolator DoubleStepInterpolator; + typedef TemplateStepInterpolator FloatStepInterpolator; + typedef TemplateStepInterpolator Vec2StepInterpolator; + typedef TemplateStepInterpolator Vec3StepInterpolator; + typedef TemplateStepInterpolator Vec3PackedStepInterpolator; + typedef TemplateStepInterpolator Vec4StepInterpolator; + typedef TemplateStepInterpolator QuatStepInterpolator; + + typedef TemplateLinearInterpolator DoubleLinearInterpolator; + typedef TemplateLinearInterpolator FloatLinearInterpolator; + typedef TemplateLinearInterpolator Vec2LinearInterpolator; + typedef TemplateLinearInterpolator Vec3LinearInterpolator; + typedef TemplateLinearInterpolator Vec3PackedLinearInterpolator; + typedef TemplateLinearInterpolator Vec4LinearInterpolator; + typedef TemplateSphericalLinearInterpolator QuatSphericalLinearInterpolator; + typedef TemplateLinearInterpolator MatrixLinearInterpolator; + + typedef TemplateCubicBezierInterpolator FloatCubicBezierInterpolator; + typedef TemplateCubicBezierInterpolator DoubleCubicBezierInterpolator; + typedef TemplateCubicBezierInterpolator Vec2CubicBezierInterpolator; + typedef TemplateCubicBezierInterpolator Vec3CubicBezierInterpolator; + typedef TemplateCubicBezierInterpolator Vec4CubicBezierInterpolator; + +} +#endif diff --git a/libs/include/android/osgAnimation/Keyframe b/libs/include/android/osgAnimation/Keyframe new file mode 100755 index 0000000..f28a601 --- /dev/null +++ b/libs/include/android/osgAnimation/Keyframe @@ -0,0 +1,141 @@ +/* -*-c++-*- + * Copyright (C) 2008 Cedric Pinson + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGANIMATION_KEYFRAME_H +#define OSGANIMATION_KEYFRAME_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace osgAnimation +{ + + class Keyframe + { + public: + double getTime() const { return _time; } + void setTime(double time) { _time = time; } + + protected: + double _time; + + }; + + template + class TemplateKeyframe : public Keyframe + { + protected: + T _value; + public: + TemplateKeyframe () {} + ~TemplateKeyframe () {} + + TemplateKeyframe (double time, const T& value) + { + _time = time; + _value = value; + } + + void setValue(const T& value) { _value = value;} + const T& getValue() const { return _value;} + }; + + + class KeyframeContainer : public osg::Referenced + { + public: + KeyframeContainer() {} + virtual unsigned int size() const = 0; + protected: + ~KeyframeContainer() {} + std::string _name; + }; + + + template + class TemplateKeyframeContainer : public std::vector >, public KeyframeContainer + { + public: + // const char* getKeyframeType() { return #T ;} + TemplateKeyframeContainer() {} + typedef TemplateKeyframe KeyType; + + virtual unsigned int size() const { return (unsigned int)std::vector >::size(); } + + }; + + template <> + class TemplateKeyframeContainer : public std::vector >, public KeyframeContainer + { + public: + typedef TemplateKeyframe KeyType; + + TemplateKeyframeContainer() {} + const char* getKeyframeType() { return "Vec3Packed" ;} + void init(const osg::Vec3f& min, const osg::Vec3f& scale) { _min = min; _scale = scale; } + + osg::Vec3f _min; + osg::Vec3f _scale; + }; + + + typedef TemplateKeyframe FloatKeyframe; + typedef TemplateKeyframeContainer FloatKeyframeContainer; + + typedef TemplateKeyframe DoubleKeyframe; + typedef TemplateKeyframeContainer DoubleKeyframeContainer; + + typedef TemplateKeyframe Vec2Keyframe; + typedef TemplateKeyframeContainer Vec2KeyframeContainer; + + typedef TemplateKeyframe Vec3Keyframe; + typedef TemplateKeyframeContainer Vec3KeyframeContainer; + + typedef TemplateKeyframe Vec4Keyframe; + typedef TemplateKeyframeContainer Vec4KeyframeContainer; + + typedef TemplateKeyframe QuatKeyframe; + typedef TemplateKeyframeContainer QuatKeyframeContainer; + + typedef TemplateKeyframe MatrixKeyframe; + typedef TemplateKeyframeContainer MatrixKeyframeContainer; + + typedef TemplateKeyframe Vec3PackedKeyframe; + typedef TemplateKeyframeContainer Vec3PackedKeyframeContainer; + + typedef TemplateKeyframe FloatCubicBezierKeyframe; + typedef TemplateKeyframeContainer FloatCubicBezierKeyframeContainer; + + typedef TemplateKeyframe DoubleCubicBezierKeyframe; + typedef TemplateKeyframeContainer DoubleCubicBezierKeyframeContainer; + + typedef TemplateKeyframe Vec2CubicBezierKeyframe; + typedef TemplateKeyframeContainer Vec2CubicBezierKeyframeContainer; + + typedef TemplateKeyframe Vec3CubicBezierKeyframe; + typedef TemplateKeyframeContainer Vec3CubicBezierKeyframeContainer; + + typedef TemplateKeyframe Vec4CubicBezierKeyframe; + typedef TemplateKeyframeContainer Vec4CubicBezierKeyframeContainer; + +} + +#endif diff --git a/libs/include/android/osgAnimation/LinkVisitor b/libs/include/android/osgAnimation/LinkVisitor new file mode 100755 index 0000000..e392aa4 --- /dev/null +++ b/libs/include/android/osgAnimation/LinkVisitor @@ -0,0 +1,56 @@ +/* -*-c++-*- + * Copyright (C) 2008 Cedric Pinson + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGANIMATION_NODE_VISITOR_H +#define OSGANIMATION_NODE_VISITOR_H + +#include +#include +#include + +namespace osgAnimation +{ + class AnimationUpdateCallbackBase; + + /** This class is instancied by the AnimationManagerBase, it will link animation target to updatecallback that have the same name + */ + class OSGANIMATION_EXPORT LinkVisitor : public osg::NodeVisitor + { + public: + LinkVisitor(); + + META_NodeVisitor(osgAnimation, LinkVisitor); + + void apply(osg::Node& node); + void apply(osg::Geode& node); + + AnimationList& getAnimationList(); + void reset(); + unsigned int getNbLinkedTarget() const { return _nbLinkedTarget; } + + protected: + + void handle_stateset(osg::StateSet* stateset); + void link(osgAnimation::AnimationUpdateCallbackBase* cb); + + // animation list to link + AnimationList _animations; + + // number of success link done + unsigned int _nbLinkedTarget; + }; + +} + +#endif diff --git a/libs/include/android/osgAnimation/MorphGeometry b/libs/include/android/osgAnimation/MorphGeometry new file mode 100755 index 0000000..48e3842 --- /dev/null +++ b/libs/include/android/osgAnimation/MorphGeometry @@ -0,0 +1,154 @@ +/* -*-c++-*- + * Copyright (C) 2008 Cedric Pinson + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGANIMATION_MORPHGEOMETRY_H +#define OSGANIMATION_MORPHGEOMETRY_H + +#include +#include +#include + +namespace osgAnimation +{ + + class OSGANIMATION_EXPORT MorphGeometry : public osg::Geometry + { + + public: + + enum Method { + NORMALIZED, + RELATIVE + }; + + class MorphTarget + { + protected: + osg::ref_ptr _geom; + float _weight; + public: + MorphTarget(osg::Geometry* geom, float w = 1.0) : _geom(geom), _weight(w) {} + void setWeight(float weight) { _weight = weight; } + float getWeight() const { return _weight; } + osg::Geometry* getGeometry() { return _geom.get(); } + const osg::Geometry* getGeometry() const { return _geom.get(); } + void setGeometry(osg::Geometry* geom) { _geom = geom; } + }; + + typedef std::vector MorphTargetList; + + struct UpdateVertex : public osg::Drawable::UpdateCallback + { + virtual void update(osg::NodeVisitor*, osg::Drawable* drw) + { + MorphGeometry* geom = dynamic_cast(drw); + if (!geom) + return; + + geom->transformSoftwareMethod(); + } + }; + + MorphGeometry(); + MorphGeometry(const osg::Geometry& b); + MorphGeometry(const MorphGeometry& b, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY); + + virtual osg::Object* cloneType() const { return new MorphGeometry(); } + virtual osg::Object* clone(const osg::CopyOp& copyop) const { return new MorphGeometry(*this,copyop); } + virtual bool isSameKindAs(const osg::Object* obj) const { return dynamic_cast(obj)!=NULL; } + virtual const char* libraryName() const { return "osgAnimation"; } + virtual const char* className() const { return "MorphGeometry"; } + + virtual void transformSoftwareMethod(); + + /** Set the morphing method. */ + void setMethod(Method method) { _method = method; } + /** Get the morphing method. */ + inline Method getMethod() const { return _method; } + + /** Set flag for morphing normals. */ + void setMorphNormals(bool morphNormals) { _morphNormals = morphNormals; } + /** Get the flag for morphing normals. */ + inline bool getMorphNormals() const { return _morphNormals; } + + /** Add a \c MorphTarget to the \c MorphGeometry. + * If \c MorphTarget is not \c NULL and is not contained in the \c MorphGeometry + * then increment its reference count, add it to the MorphTargets list and + * dirty the bounding sphere to force it to be recomputed on the next + * call to \c getBound(). + * @param morphTarget The \c MorphTarget to be added to the \c MorphGeometry. + * @param weight The weight to be added to the \c MorphGeometry. + * @return \c true for success; \c false otherwise. + */ + virtual void addMorphTarget( osg::Geometry *morphTarget, float weight = 1.0 ) { _morphTargets.push_back(MorphTarget(morphTarget, weight)); _dirty = true; } + + void setWeight(unsigned int index, float morphWeight) + { + if (index < _morphTargets.size()) + { + _morphTargets[index].setWeight(morphWeight); + dirty(); + } + } + + /** Set the MorphGeometry dirty.*/ + void dirty() { _dirty = true; } + + /** Get the list of MorphTargets.*/ + const MorphTargetList& getMorphTargetList() const { return _morphTargets; } + + /** Get the list of MorphTargets. Warning if you modify this array you will have to call dirty() */ + MorphTargetList& getMorphTargetList() { return _morphTargets; } + + /** Return the \c MorphTarget at position \c i.*/ + inline const MorphTarget& getMorphTarget( unsigned int i ) const { return _morphTargets[i]; } + + /** Return the \c MorphTarget at position \c i.*/ + inline MorphTarget& getMorphTarget( unsigned int i ) { return _morphTargets[i]; } + + protected: + /// Do we need to recalculate the morphed geometry? + bool _dirty; + + Method _method; + MorphTargetList _morphTargets; + + std::vector _positionSource; + std::vector _normalSource; + + /// Do we also morph between normals? + bool _morphNormals; + }; + + class OSGANIMATION_EXPORT UpdateMorph : public AnimationUpdateCallback + { + protected: + std::map > _weightTargets; + + public: + + META_Object(osgAnimation, UpdateMorph); + + UpdateMorph(const std::string& name = ""); + UpdateMorph(const UpdateMorph& apc,const osg::CopyOp& copyop); + + /** Callback method called by the NodeVisitor when visiting a node.*/ + virtual void operator()(osg::Node* node, osg::NodeVisitor* nv); + bool needLink() const; + bool link(osgAnimation::Channel* channel); + }; + +} + +#endif diff --git a/libs/include/android/osgAnimation/RigGeometry b/libs/include/android/osgAnimation/RigGeometry new file mode 100755 index 0000000..3015a3a --- /dev/null +++ b/libs/include/android/osgAnimation/RigGeometry @@ -0,0 +1,136 @@ +/* -*-c++-*- + * Copyright (C) 2008 Cedric Pinson + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGANIMATION_RIGGEOMETRY_H +#define OSGANIMATION_RIGGEOMETRY_H + +#include +#include +#include +#include +#include + +namespace osgAnimation +{ + + class OSGANIMATION_EXPORT RigGeometry : public osg::Geometry + { + public: + + RigGeometry(); +// RigGeometry(const osg::Geometry& b); + RigGeometry(const RigGeometry& b, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY); + + META_Object(osgAnimation, RigGeometry); + + void setInfluenceMap(VertexInfluenceMap* vertexInfluenceMap) { _vertexInfluenceMap = vertexInfluenceMap; } + const VertexInfluenceMap* getInfluenceMap() const { return _vertexInfluenceMap.get();} + VertexInfluenceMap* getInfluenceMap() { return _vertexInfluenceMap.get();} + + const Skeleton* getSkeleton() const; + Skeleton* getSkeleton(); + // will be used by the update callback to init correctly the rig mesh + void setSkeleton(Skeleton*); + + void setNeedToComputeMatrix(bool state) { _needToComputeMatrix = state;} + bool getNeedToComputeMatrix() const { return _needToComputeMatrix;} + + + // this build the internal database about vertex influence and bones + void buildVertexInfluenceSet(); + const VertexInfluenceSet& getVertexInfluenceSet() const; + + void computeMatrixFromRootSkeleton(); + + + // set implementation of rig method + void setRigTransformImplementation(RigTransform*); + RigTransform* getRigTransformImplementation(); + + virtual void drawImplementation(osg::RenderInfo& renderInfo) const; + void update(); + + const osg::Matrix& getMatrixFromSkeletonToGeometry() const; + const osg::Matrix& getInvMatrixFromSkeletonToGeometry() const; + + osg::Geometry* getSourceGeometry(); + const osg::Geometry* getSourceGeometry() const; + void setSourceGeometry(osg::Geometry* geometry); + + void copyFrom(osg::Geometry& from); + + protected: + + osg::ref_ptr _geometry; + osg::ref_ptr _rigTransformImplementation; + + VertexInfluenceSet _vertexInfluenceSet; + osg::ref_ptr _vertexInfluenceMap; + + osg::Matrix _matrixFromSkeletonToGeometry; + osg::Matrix _invMatrixFromSkeletonToGeometry; + osg::observer_ptr _root; + bool _needToComputeMatrix; + + struct FindNearestParentSkeleton : public osg::NodeVisitor + { + osg::ref_ptr _root; + FindNearestParentSkeleton() : osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_PARENTS) {} + void apply(osg::Transform& node) + { + if (_root.valid()) + return; + _root = dynamic_cast(&node); + traverse(node); + } + }; + + + struct UpdateVertex : public osg::Drawable::UpdateCallback + { + virtual void update(osg::NodeVisitor*, osg::Drawable* drw) + { + RigGeometry* geom = dynamic_cast(drw); + if (!geom) + return; + if (!geom->getSkeleton() && !geom->getParents().empty()) + { + FindNearestParentSkeleton finder; + if (geom->getParents().size() > 1) + osg::notify(osg::WARN) << "A RigGeometry should not have multi parent ( " << geom->getName() << " )" << std::endl; + geom->getParents()[0]->accept(finder); + + if (!finder._root.valid()) + { + osg::notify(osg::WARN) << "A RigGeometry did not find a parent skeleton for RigGeomtry ( " << geom->getName() << " )" << std::endl; + return; + } + geom->buildVertexInfluenceSet(); + geom->setSkeleton(finder._root.get()); + } + + if (!geom->getSkeleton()) + return; + + if (geom->getNeedToComputeMatrix()) + geom->computeMatrixFromRootSkeleton(); + + geom->update(); + } + }; + }; + +} + +#endif diff --git a/libs/include/android/osgAnimation/RigTransform b/libs/include/android/osgAnimation/RigTransform new file mode 100755 index 0000000..525d1c2 --- /dev/null +++ b/libs/include/android/osgAnimation/RigTransform @@ -0,0 +1,36 @@ +/* -*-c++-*- + * Copyright (C) 2009 Cedric Pinson + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGANIMATION_RIGTRANSFORM +#define OSGANIMATION_RIGTRANSFORM 1 + +#include + +namespace osgAnimation +{ + + class RigGeometry; + + class RigTransform : public osg::Referenced + { + public: + RigTransform() {} + virtual ~RigTransform() {} + virtual void operator()(RigGeometry&) {} + + }; + +} + +#endif diff --git a/libs/include/android/osgAnimation/RigTransformHardware b/libs/include/android/osgAnimation/RigTransformHardware new file mode 100755 index 0000000..54ba615 --- /dev/null +++ b/libs/include/android/osgAnimation/RigTransformHardware @@ -0,0 +1,85 @@ +/* -*-c++-*- + * Copyright (C) 2009 Cedric Pinson + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. + */ + +#ifndef OSGANIMATION_RIG_TRANSFORM_HARDWARE +#define OSGANIMATION_RIG_TRANSFORM_HARDWARE 1 + +#include +#include +#include +#include +#include +#include + +namespace osgAnimation +{ + class RigGeometry; + + /// This class manage format for hardware skinning + class OSGANIMATION_EXPORT RigTransformHardware : public RigTransform + { + public: + typedef osg::Matrix MatrixType; + typedef osgAnimation::Bone BoneType; + typedef std::vector > BoneWeightAttribList; + typedef std::vector > BonePalette; + + typedef std::vector MatrixPalette; + struct IndexWeightEntry + { + int _boneIndex; + float _boneWeight; + IndexWeightEntry() { _boneIndex = 0; _boneWeight = 0;} + IndexWeightEntry(int index, float weight) { _boneIndex = index; _boneWeight = weight;} + int getIndex() const { return _boneIndex; } + float getWeight() const { return _boneWeight; } + }; + typedef std::vector > VertexIndexWeightList; + + RigTransformHardware(); + + osg::Vec4Array* getVertexAttrib(int index); + int getNumVertexAttrib(); + + osg::Uniform* getMatrixPaletteUniform(); + void computeMatrixPaletteUniform(const osg::Matrix& transformFromSkeletonToGeometry, const osg::Matrix& invTransformFromSkeletonToGeometry); + + int getNumBonesPerVertex() const; + int getNumVertexes() const; + + bool createPalette(int nbVertexes, BoneMap boneMap, const VertexInfluenceSet::VertexIndexToBoneWeightMap& vertexIndexToBoneWeightMap); + + virtual void operator()(RigGeometry&); + void setShader(osg::Shader*); + + protected: + + bool init(RigGeometry&); + + BoneWeightAttribList createVertexAttribList(); + osg::Uniform* createVertexUniform(); + + int _bonesPerVertex; + int _nbVertexes; + VertexIndexWeightList _vertexIndexMatrixWeightList; + BonePalette _bonePalette; + BoneWeightAttribList _boneWeightAttribArrays; + osg::ref_ptr _uniformMatrixPalette; + osg::ref_ptr _shader; + + bool _needInit; + }; +} + +#endif diff --git a/libs/include/android/osgAnimation/RigTransformSoftware b/libs/include/android/osgAnimation/RigTransformSoftware new file mode 100755 index 0000000..550940c --- /dev/null +++ b/libs/include/android/osgAnimation/RigTransformSoftware @@ -0,0 +1,172 @@ +/* -*-c++-*- + * Copyright (C) 2009 Cedric Pinson + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. + */ + +#ifndef OSGANIMATION_RIGTRANSFORM_SOFTWARE +#define OSGANIMATION_RIGTRANSFORM_SOFTWARE 1 + +#include +#include +#include +#include +#include + +namespace osgAnimation +{ + + class RigGeometry; + + /// This class manage format for hardware skinning + class OSGANIMATION_EXPORT RigTransformSoftware : public RigTransform + { + public: + + RigTransformSoftware(); + virtual void operator()(RigGeometry&); + + + class BoneWeight + { + public: + BoneWeight(Bone* bone, float weight) : _bone(bone), _weight(weight) {} + const Bone* getBone() const { return _bone.get(); } + float getWeight() const { return _weight; } + void setWeight(float w) { _weight = w; } + protected: + osg::observer_ptr _bone; + float _weight; + }; + + typedef std::vector BoneWeightList; + typedef std::vector VertexList; + + class UniqBoneSetVertexSet + { + public: + BoneWeightList& getBones() { return _bones; } + VertexList& getVertexes() { return _vertexes; } + + void resetMatrix() + { + _result.set(0, 0, 0, 0, + 0, 0, 0, 0, + 0, 0, 0, 0, + 0, 0, 0, 1); + } + void accummulateMatrix(const osg::Matrix& invBindMatrix, const osg::Matrix& matrix, osg::Matrix::value_type weight) + { + osg::Matrix m = invBindMatrix * matrix; + osg::Matrix::value_type* ptr = m.ptr(); + osg::Matrix::value_type* ptrresult = _result.ptr(); + ptrresult[0] += ptr[0] * weight; + ptrresult[1] += ptr[1] * weight; + ptrresult[2] += ptr[2] * weight; + + ptrresult[4] += ptr[4] * weight; + ptrresult[5] += ptr[5] * weight; + ptrresult[6] += ptr[6] * weight; + + ptrresult[8] += ptr[8] * weight; + ptrresult[9] += ptr[9] * weight; + ptrresult[10] += ptr[10] * weight; + + ptrresult[12] += ptr[12] * weight; + ptrresult[13] += ptr[13] * weight; + ptrresult[14] += ptr[14] * weight; + } + void computeMatrixForVertexSet() + { + if (_bones.empty()) + { + osg::notify(osg::WARN) << this << " RigTransformSoftware::UniqBoneSetVertexSet no bones found" << std::endl; + _result = osg::Matrix::identity(); + return; + } + resetMatrix(); + + int size = _bones.size(); + for (int i = 0; i < size; i++) + { + const Bone* bone = _bones[i].getBone(); + if (!bone) + { + osg::notify(osg::WARN) << this << " RigTransformSoftware::computeMatrixForVertexSet Warning a bone is null, skip it" << std::endl; + continue; + } + const osg::Matrix& invBindMatrix = bone->getInvBindMatrixInSkeletonSpace(); + const osg::Matrix& matrix = bone->getMatrixInSkeletonSpace(); + osg::Matrix::value_type w = _bones[i].getWeight(); + accummulateMatrix(invBindMatrix, matrix, w); + } + } + const osg::Matrix& getMatrix() const { return _result;} + protected: + BoneWeightList _bones; + VertexList _vertexes; + osg::Matrix _result; + }; + + + + template void compute(const osg::Matrix& transform, const osg::Matrix& invTransform, const V* src, V* dst) + { + // the result of matrix mult should be cached to be used for vertexes transform and normal transform and maybe other computation + int size = _boneSetVertexSet.size(); + for (int i = 0; i < size; i++) + { + UniqBoneSetVertexSet& uniq = _boneSetVertexSet[i]; + uniq.computeMatrixForVertexSet(); + osg::Matrix matrix = transform * uniq.getMatrix() * invTransform; + + const VertexList& vertexes = uniq.getVertexes(); + int vertexSize = vertexes.size(); + for (int j = 0; j < vertexSize; j++) + { + int idx = vertexes[j]; + dst[idx] = src[idx] * matrix; + } + } + } + + + template void computeNormal(const osg::Matrix& transform, const osg::Matrix& invTransform, const V* src, V* dst) + { + int size = _boneSetVertexSet.size(); + for (int i = 0; i < size; i++) + { + UniqBoneSetVertexSet& uniq = _boneSetVertexSet[i]; + uniq.computeMatrixForVertexSet(); + osg::Matrix matrix = transform * uniq.getMatrix() * invTransform; + + const VertexList& vertexes = uniq.getVertexes(); + int vertexSize = vertexes.size(); + for (int j = 0; j < vertexSize; j++) + { + int idx = vertexes[j]; + dst[idx] = osg::Matrix::transform3x3(src[idx],matrix); + } + } + } + + protected: + + bool init(RigGeometry&); + void initVertexSetFromBones(const BoneMap& map, const VertexInfluenceSet::UniqVertexSetToBoneSetList& influence); + std::vector _boneSetVertexSet; + + bool _needInit; + + }; +} + +#endif diff --git a/libs/include/android/osgAnimation/Sampler b/libs/include/android/osgAnimation/Sampler new file mode 100755 index 0000000..26730c8 --- /dev/null +++ b/libs/include/android/osgAnimation/Sampler @@ -0,0 +1,138 @@ +/* -*-c++-*- + * Copyright (C) 2008 Cedric Pinson + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. + * + * Authors: + * Cedric Pinson + * Michael Platings + */ + +#ifndef OSGANIMATION_SAMPLER +#define OSGANIMATION_SAMPLER 1 + +#include +#include +#include +#include +#include +#include + +namespace osgAnimation +{ + + class Sampler : public osg::Referenced + { + public: + virtual KeyframeContainer* getKeyframeContainer() = 0; + virtual const KeyframeContainer* getKeyframeContainer() const = 0; + protected: + }; + + // Sampler generic + template + class TemplateSampler : public Sampler + { + public: + typedef typename F::KeyframeType KeyframeType; + typedef TemplateKeyframeContainer KeyframeContainerType; + typedef typename F::UsingType UsingType; + typedef F FunctorType; + + TemplateSampler() {} + ~TemplateSampler() {} + + void getValueAt(double time, UsingType& result) const { _functor.getValue(*_keyframes, time, result);} + void setKeyframeContainer(KeyframeContainerType* kf) { _keyframes = kf;} + + virtual KeyframeContainer* getKeyframeContainer() { return _keyframes.get(); } + virtual const KeyframeContainer* getKeyframeContainer() const { return _keyframes.get();} + + KeyframeContainerType* getKeyframeContainerTyped() { return _keyframes.get();} + const KeyframeContainerType* getKeyframeContainerTyped() const { return _keyframes.get();} + KeyframeContainerType* getOrCreateKeyframeContainer() + { + if (_keyframes != 0) + return _keyframes.get(); + _keyframes = new KeyframeContainerType; + return _keyframes.get(); + } + + double getStartTime() const + { + if (!_keyframes || _keyframes->empty()) + return 0.0; + return _keyframes->front().getTime(); + } + + double getEndTime() const + { + if (!_keyframes || _keyframes->empty()) + return 0.0; + return _keyframes->back().getTime(); + } + + protected: + + FunctorType _functor; + osg::ref_ptr _keyframes; + }; + + + template + class TemplateCompositeSampler : public osg::Referenced + { + VALUESAMPLERTYPE& _value; + TIMESAMPLERTYPE& _time; + + public: + typedef typename VALUESAMPLERTYPE::FunctorType::UsingType UsingType; + typedef typename VALUESAMPLERTYPE::FunctorType::KeyframeType KeyframeType; + + TemplateCompositeSampler(VALUESAMPLERTYPE& value, TIMESAMPLERTYPE& time) : _value(value), _time(time) + { + } + + void getValueAt(double time, typename VALUESAMPLERTYPE::FunctorType::UsingType& result) + { + double newtime; + _time.getValueAt(time, newtime); + _value.getValueAt(newtime, result); + } + float getStartTime() const {return _time.getStartTime(); } + float getEndTime() const {return _time.getEndTime();} + }; + + + typedef TemplateSampler DoubleStepSampler; + typedef TemplateSampler FloatStepSampler; + typedef TemplateSampler Vec2StepSampler; + typedef TemplateSampler Vec3StepSampler; + typedef TemplateSampler Vec4StepSampler; + typedef TemplateSampler QuatStepSampler; + + typedef TemplateSampler DoubleLinearSampler; + typedef TemplateSampler FloatLinearSampler; + typedef TemplateSampler Vec2LinearSampler; + typedef TemplateSampler Vec3LinearSampler; + typedef TemplateSampler Vec4LinearSampler; + typedef TemplateSampler QuatSphericalLinearSampler; + typedef TemplateSampler MatrixLinearSampler; + + typedef TemplateSampler FloatCubicBezierSampler; + typedef TemplateSampler DoubleCubicBezierSampler; + typedef TemplateSampler Vec2CubicBezierSampler; + typedef TemplateSampler Vec3CubicBezierSampler; + typedef TemplateSampler Vec4CubicBezierSampler; + +} + +#endif diff --git a/libs/include/android/osgAnimation/Skeleton b/libs/include/android/osgAnimation/Skeleton new file mode 100755 index 0000000..c2444da --- /dev/null +++ b/libs/include/android/osgAnimation/Skeleton @@ -0,0 +1,49 @@ +/* -*-c++-*- + * Copyright (C) 2008 Cedric Pinson + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGANIMATION_SKELETON +#define OSGANIMATION_SKELETON 1 + +#include +#include + +namespace osgAnimation +{ + + class OSGANIMATION_EXPORT Skeleton : public osg::MatrixTransform + { + public: + META_Node(osgAnimation, Skeleton); + + class OSGANIMATION_EXPORT UpdateSkeleton : public osg::NodeCallback + { + public: + META_Object(osgAnimation, UpdateSkeleton); + UpdateSkeleton(); + UpdateSkeleton(const UpdateSkeleton&, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY); + virtual void operator()(osg::Node* node, osg::NodeVisitor* nv); + bool needToValidate() const; + protected: + bool _needValidate; + }; + + Skeleton(); + Skeleton(const Skeleton&, const osg::CopyOp&); + void setDefaultUpdateCallback(); + + }; + +} + +#endif diff --git a/libs/include/android/osgAnimation/StackedMatrixElement b/libs/include/android/osgAnimation/StackedMatrixElement new file mode 100755 index 0000000..a3e5552 --- /dev/null +++ b/libs/include/android/osgAnimation/StackedMatrixElement @@ -0,0 +1,54 @@ +/* -*-c++-*- + * Copyright (C) 2009 Cedric Pinson + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. + */ + + +#ifndef OSGANIMATION_STACKED_MATRIX_ELEMENT +#define OSGANIMATION_STACKED_MATRIX_ELEMENT 1 + +#include +#include +#include +#include + +namespace osgAnimation +{ + + class OSGANIMATION_EXPORT StackedMatrixElement : public StackedTransformElement + { + public: + META_Object(osgAnimation, StackedMatrixElement); + + StackedMatrixElement(); + StackedMatrixElement(const StackedMatrixElement&, const osg::CopyOp&); + StackedMatrixElement(const std::string& name, const osg::Matrix& matrix); + StackedMatrixElement(const osg::Matrix& matrix); + + void applyToMatrix(osg::Matrix& matrix) const { matrix = _matrix * matrix; } + osg::Matrix getAsMatrix() const { return _matrix; } + const osg::Matrix& getMatrix() const { return _matrix;} + void setMatrix(const osg::Matrix& matrix) { _matrix = matrix;} + bool isIdentity() const { return _matrix.isIdentity(); } + void update(float t = 0.0); + virtual Target* getOrCreateTarget(); + virtual Target* getTarget() {return _target.get();} + virtual const Target* getTarget() const {return _target.get();} + + protected: + osg::Matrix _matrix; + osg::ref_ptr _target; + }; + +} + +#endif diff --git a/libs/include/android/osgAnimation/StackedQuaternionElement b/libs/include/android/osgAnimation/StackedQuaternionElement new file mode 100755 index 0000000..3f019e1 --- /dev/null +++ b/libs/include/android/osgAnimation/StackedQuaternionElement @@ -0,0 +1,54 @@ +/* -*-c++-*- + * Copyright (C) 2009 Cedric Pinson + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. + */ + + +#ifndef OSGANIMATION_STACKED_QUATERNION_ELEMENT +#define OSGANIMATION_STACKED_QUATERNION_ELEMENT 1 + +#include +#include +#include + +namespace osgAnimation +{ + + class OSGANIMATION_EXPORT StackedQuaternionElement : public StackedTransformElement + { + public: + META_Object(osgAnimation, StackedQuaternionElement); + + StackedQuaternionElement(); + StackedQuaternionElement(const StackedQuaternionElement&, const osg::CopyOp&); + StackedQuaternionElement(const std::string&, const osg::Quat& q = osg::Quat(0,0,0,1)); + StackedQuaternionElement(const osg::Quat&); + + void applyToMatrix(osg::Matrix& matrix) const; + osg::Matrix getAsMatrix() const; + bool isIdentity() const; + void update(float t = 0.0); + + const osg::Quat& getQuaternion() const; + void setQuaternion(const osg::Quat&); + virtual Target* getOrCreateTarget(); + virtual Target* getTarget(); + virtual const Target* getTarget() const; + + protected: + osg::Quat _quaternion; + osg::ref_ptr _target; + }; + +} + +#endif diff --git a/libs/include/android/osgAnimation/StackedRotateAxisElement b/libs/include/android/osgAnimation/StackedRotateAxisElement new file mode 100755 index 0000000..615a010 --- /dev/null +++ b/libs/include/android/osgAnimation/StackedRotateAxisElement @@ -0,0 +1,59 @@ +/* -*-c++-*- + * Copyright (C) 2009 Cedric Pinson + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. + */ + +#ifndef OSGANIMATION_STACKED_ROTATE_AXIS_ELEMENT +#define OSGANIMATION_STACKED_ROTATE_AXIS_ELEMENT 1 + +#include +#include +#include +#include + +namespace osgAnimation +{ + + class OSGANIMATION_EXPORT StackedRotateAxisElement : public StackedTransformElement + { + public: + META_Object(osgAnimation, StackedRotateAxisElement); + + StackedRotateAxisElement(); + StackedRotateAxisElement(const StackedRotateAxisElement&, const osg::CopyOp&); + StackedRotateAxisElement(const std::string& name, const osg::Vec3& axis, double angle); + StackedRotateAxisElement(const osg::Vec3& axis, double angle); + + void applyToMatrix(osg::Matrix& matrix) const; + osg::Matrix getAsMatrix() const; + bool isIdentity() const { return (_angle == 0); } + void update(float t = 0.0); + + const osg::Vec3& getAxis() const; + double getAngle() const; + void setAxis(const osg::Vec3&); + void setAngle(double); + + virtual Target* getOrCreateTarget(); + virtual Target* getTarget() {return _target.get();} + virtual const Target* getTarget() const {return _target.get();} + + protected: + osg::Vec3 _axis; + double _angle; + osg::ref_ptr _target; + }; + +} + +#endif + diff --git a/libs/include/android/osgAnimation/StackedScaleElement b/libs/include/android/osgAnimation/StackedScaleElement new file mode 100755 index 0000000..080fd19 --- /dev/null +++ b/libs/include/android/osgAnimation/StackedScaleElement @@ -0,0 +1,56 @@ +/* -*-c++-*- + * Copyright (C) 2009 Cedric Pinson + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. + */ + +#ifndef OSGANIMATION_STACKED_SCALE_ELEMENT +#define OSGANIMATION_STACKED_SCALE_ELEMENT 1 + +#include +#include +#include +#include + +namespace osgAnimation +{ + + class OSGANIMATION_EXPORT StackedScaleElement : public StackedTransformElement + { + public: + META_Object(osgAnimation, StackedScaleElement) + + StackedScaleElement(); + StackedScaleElement(const StackedScaleElement&, const osg::CopyOp&); + StackedScaleElement(const std::string& name, const osg::Vec3& scale = osg::Vec3(1,1,1)); + StackedScaleElement(const osg::Vec3& scale); + + void applyToMatrix(osg::Matrix& matrix) const; + osg::Matrix getAsMatrix() const; + bool isIdentity() const; + void update(float t = 0.0); + const osg::Vec3& getScale() const; + void setScale(const osg::Vec3& scale); + + virtual Target* getOrCreateTarget(); + virtual Target* getTarget(); + virtual const Target* getTarget() const; + + protected: + osg::Vec3 _scale; + osg::ref_ptr _target; + }; + + +} + +#endif + diff --git a/libs/include/android/osgAnimation/StackedTransform b/libs/include/android/osgAnimation/StackedTransform new file mode 100755 index 0000000..c91a519 --- /dev/null +++ b/libs/include/android/osgAnimation/StackedTransform @@ -0,0 +1,42 @@ +/* -*-c++-*- + * Copyright (C) 2009 Cedric Pinson + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. + */ + +#ifndef OSGANIMATION_STACKED_TRANSFORM +#define OSGANIMATION_STACKED_TRANSFORM 1 + +#include +#include +#include + +namespace osgAnimation +{ + + class OSGANIMATION_EXPORT StackedTransform : public osg::MixinVector > + { + public: + StackedTransform(); + StackedTransform(const StackedTransform&, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY); + + void update(float t = 0.0); + const osg::Matrix& getMatrix() const; + + protected: + osg::Matrix _matrix; + }; + + + +} + +#endif diff --git a/libs/include/android/osgAnimation/StackedTransformElement b/libs/include/android/osgAnimation/StackedTransformElement new file mode 100755 index 0000000..2bf89c6 --- /dev/null +++ b/libs/include/android/osgAnimation/StackedTransformElement @@ -0,0 +1,42 @@ +/* -*-c++-*- + * Copyright (C) 2009 Cedric Pinson + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. + */ + + +#ifndef OSGANIMATION_STACKED_TRANSFORM_ELEMENT +#define OSGANIMATION_STACKED_TRANSFORM_ELEMENT 1 + +#include +#include +#include + +namespace osgAnimation +{ + class Target; + class OSGANIMATION_EXPORT StackedTransformElement : public osg::Object + { + public: + StackedTransformElement() {} + StackedTransformElement(const StackedTransformElement& rhs, const osg::CopyOp& c) : osg::Object(rhs, c) {} + virtual void applyToMatrix(osg::Matrix& matrix) const = 0; + virtual osg::Matrix getAsMatrix() const = 0; + virtual bool isIdentity() const = 0; + virtual void update(float t) = 0; + virtual Target* getOrCreateTarget() {return 0;} + virtual Target* getTarget() {return 0;} + virtual const Target* getTarget() const {return 0;} + }; + +} + +#endif diff --git a/libs/include/android/osgAnimation/StackedTranslateElement b/libs/include/android/osgAnimation/StackedTranslateElement new file mode 100755 index 0000000..0c9c47c --- /dev/null +++ b/libs/include/android/osgAnimation/StackedTranslateElement @@ -0,0 +1,54 @@ +/* -*-c++-*- + * Copyright (C) 2009 Cedric Pinson + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. + */ + + +#ifndef OSGANIMATION_STACKED_TRANSLATE_ELEMENT +#define OSGANIMATION_STACKED_TRANSLATE_ELEMENT 1 + +#include +#include +#include + +namespace osgAnimation +{ + + class OSGANIMATION_EXPORT StackedTranslateElement : public StackedTransformElement + { + public: + META_Object(osgAnimation, StackedTranslateElement); + + StackedTranslateElement(); + StackedTranslateElement(const StackedTranslateElement&, const osg::CopyOp&); + StackedTranslateElement(const std::string&, const osg::Vec3& translate = osg::Vec3(0,0,0)); + StackedTranslateElement(const osg::Vec3& translate); + + void applyToMatrix(osg::Matrix& matrix) const; + osg::Matrix getAsMatrix() const; + bool isIdentity() const; + void update(float t = 0.0); + + const osg::Vec3& getTranslate() const; + void setTranslate(const osg::Vec3& ); + virtual Target* getOrCreateTarget(); + virtual Target* getTarget(); + virtual const Target* getTarget() const; + + protected: + osg::Vec3 _translate; + osg::ref_ptr _target; + }; + +} + +#endif diff --git a/libs/include/android/osgAnimation/StatsHandler b/libs/include/android/osgAnimation/StatsHandler new file mode 100755 index 0000000..cbaa917 --- /dev/null +++ b/libs/include/android/osgAnimation/StatsHandler @@ -0,0 +1,113 @@ +/* -*-c++-*- + * Copyright (C) 2009 Cedric Pinson + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGANIMATION_STATSHANDLER_H +#define OSGANIMATION_STATSHANDLER_H + +#include +#include +#include +#include +#include + +namespace osgAnimation +{ +#if 0 + struct StatAction + { + + std::string _name; + osg::ref_ptr _group; + osg::ref_ptr _label; + osg::ref_ptr _graph; + osg::ref_ptr _textLabel; + + void init(osg::Stats* stats, const std::string& name, const osg::Vec3& pos, float width, float heigh, const osg::Vec4& color); + void setPosition(const osg::Vec3& pos); + void setAlpha(float v); + }; + +#endif + +/** Event handler for adding on screen stats reporting to Viewers.*/ + class OSGANIMATION_EXPORT StatsHandler : public osgGA::GUIEventHandler + { + public: + + StatsHandler(); + + enum StatsType + { + NO_STATS = 0, + FRAME_RATE = 1, + LAST = 2 + }; + + void setKeyEventTogglesOnScreenStats(int key) { _keyEventTogglesOnScreenStats = key; } + int getKeyEventTogglesOnScreenStats() const { return _keyEventTogglesOnScreenStats; } + + void setKeyEventPrintsOutStats(int key) { _keyEventPrintsOutStats = key; } + int getKeyEventPrintsOutStats() const { return _keyEventPrintsOutStats; } + + double getBlockMultiplier() const { return _blockMultiplier; } + + void reset(); + + osg::Camera* getCamera() { return _camera.get(); } + const osg::Camera* getCamera() const { return _camera.get(); } + + virtual bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa); + + /** Get the keyboard and mouse usage of this manipulator.*/ + virtual void getUsage(osg::ApplicationUsage& usage) const; + + protected: + + void setUpHUDCamera(osgViewer::ViewerBase* viewer); + + osg::Geometry* createBackgroundRectangle(const osg::Vec3& pos, const float width, const float height, osg::Vec4& color); + + osg::Geometry* createGeometry(const osg::Vec3& pos, float height, const osg::Vec4& colour, unsigned int numBlocks); + + osg::Geometry* createFrameMarkers(const osg::Vec3& pos, float height, const osg::Vec4& colour, unsigned int numBlocks); + + osg::Geometry* createTick(const osg::Vec3& pos, float height, const osg::Vec4& colour, unsigned int numTicks); + + osg::Node* createCameraTimeStats(const std::string& font, osg::Vec3& pos, float startBlocks, bool acquireGPUStats, float characterSize, osg::Stats* viewerStats, osg::Camera* camera); + + void setUpScene(osgViewer::Viewer* viewer); + + int _keyEventTogglesOnScreenStats; + int _keyEventPrintsOutStats; + + int _statsType; + + bool _initialized; + osg::ref_ptr _camera; + + osg::ref_ptr _switch; + osg::ref_ptr _group; + + unsigned int _frameRateChildNum; + unsigned int _numBlocks; + double _blockMultiplier; + + float _statsWidth; + float _statsHeight; + +// std::map _actions; + }; + +} +#endif diff --git a/libs/include/android/osgAnimation/StatsVisitor b/libs/include/android/osgAnimation/StatsVisitor new file mode 100755 index 0000000..8f3ccc5 --- /dev/null +++ b/libs/include/android/osgAnimation/StatsVisitor @@ -0,0 +1,53 @@ +/* -*-c++-*- + * Copyright (C) 2009 Cedric Pinson + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGANIMATION_STATSVISITOR_H +#define OSGANIMATION_STATSVISITOR_H + +#include +#include +#include +#include + +namespace osgAnimation +{ + + class OSGANIMATION_EXPORT StatsActionVisitor : public osgAnimation::UpdateActionVisitor + { + protected: + osg::ref_ptr _stats; + std::vector _channels; + + public: + META_ActionVisitor(osgAnimation, StatsActionVisitor); + + StatsActionVisitor(); + StatsActionVisitor(osg::Stats* stats, unsigned int frame); + void reset(); + const std::vector& getChannels() const { return _channels; } + osg::Stats* getStats() { return _stats.get(); } + void setStats(osg::Stats* stats) { _stats = stats; } + void setFrame(unsigned int frame) { _frame = frame; } + void apply(Timeline& action); + void apply(Action& action); + void apply(ActionBlendIn& action); + void apply(ActionBlendOut& action); + void apply(ActionAnimation& action); + void apply(ActionStripAnimation& action); + + }; + +} + +#endif diff --git a/libs/include/android/osgAnimation/Target b/libs/include/android/osgAnimation/Target new file mode 100755 index 0000000..abe91a0 --- /dev/null +++ b/libs/include/android/osgAnimation/Target @@ -0,0 +1,134 @@ +/* -*-c++-*- + * Copyright (C) 2008 Cedric Pinson + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + + +#ifndef OSGANIMATION_TARGET +#define OSGANIMATION_TARGET 1 + +#include +#include +#include +#include +#include +#include +#include + +namespace osgAnimation +{ + + class Channel; + + class OSGANIMATION_EXPORT Target : public osg::Referenced + { + public: + + Target(); + virtual ~Target() {} + void reset() { _weight = 0; _priorityWeight = 0; } + int getCount() const { return referenceCount(); } + float getWeight() const { return _weight; } + protected: + float _weight; + float _priorityWeight; + int _lastPriority; + }; + + + template + class TemplateTarget : public Target + { + public: + + TemplateTarget() : _target() {} + TemplateTarget(const T& v) { setValue(v); } + TemplateTarget(const TemplateTarget& v) { setValue(v.getValue()); } + + inline void lerp(float t, const T& a, const T& b); + + /** + * The priority is used to detect a change of priority + * It's important to update animation target in priority + * order. eg: + * all animation with priority 1 + * all animation with priority 0 + * all animation with priority -1 + * ... + */ + void update(float weight, const T& val, int priority) + { + if (_weight || _priorityWeight) + { + if (_lastPriority != priority) + { + // change in priority + // add to weight with the same previous priority cumulated weight + _weight += _priorityWeight * (1.0 - _weight); + _priorityWeight = 0; + _lastPriority = priority; + } + + _priorityWeight += weight; + float t = (1.0 - _weight) * weight / _priorityWeight; + lerp(t, _target, val); + } + else + { + _priorityWeight = weight; + _lastPriority = priority; + _target = val; + } + } + const T& getValue() const { return _target; } + + void setValue(const T& value) { _target = value; } + + protected: + + T _target; + }; + + template + inline void TemplateTarget::lerp(float t, const T& a, const T& b) + { + _target = a * (1.0f - t) + b * t; + } + + template <> + inline void TemplateTarget::lerp(float t, const osg::Quat& a, const osg::Quat& b) + { + if (a.asVec4() * b.asVec4() < 0.0) + { + _target = a * (1.0f - t) + b * -t; + } + else + { + _target = a * (1.0f - t) + b * t; + } + + osg::Quat::value_type len2 = _target.length2(); + if ( len2 != 1.0 && len2 != 0.0) + _target *= 1.0/sqrt(len2); + } + + typedef TemplateTarget MatrixTarget; + typedef TemplateTarget QuatTarget; + typedef TemplateTarget Vec3Target; + typedef TemplateTarget Vec4Target; + typedef TemplateTarget Vec2Target; + typedef TemplateTarget FloatTarget; + typedef TemplateTarget DoubleTarget; + +} + +#endif diff --git a/libs/include/android/osgAnimation/Timeline b/libs/include/android/osgAnimation/Timeline new file mode 100755 index 0000000..8ce73dc --- /dev/null +++ b/libs/include/android/osgAnimation/Timeline @@ -0,0 +1,122 @@ +/* -*-c++-*- + * Copyright (C) 2008 Cedric Pinson + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGANIMATION_TIMELINE +#define OSGANIMATION_TIMELINE 1 + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace osgAnimation +{ + class OSGANIMATION_EXPORT Timeline : public Action + { + public: + + Timeline(); + Timeline(const Timeline& nc,const osg::CopyOp& op = osg::CopyOp::SHALLOW_COPY); + + META_Action(osgAnimation, Timeline); + + enum TimelineStatus + { + Play, + Stop + }; + + TimelineStatus getStatus() const { return _state; } + + typedef std::vector ActionList; + typedef std::map ActionLayers; + + const ActionList& getActionLayer(int i) { return _actions[i];} + unsigned int getCurrentFrame() const { return _currentFrame;} + double getCurrentTime() const { return _currentFrame * 1.0 / _fps;} + + void play() { _state = Play; } + void gotoFrame(unsigned int frame) { _currentFrame = frame; } + void stop() { _state = Stop; } + bool getEvaluating() const { return _evaluating;} + + bool isActive(Action* activeAction); + + void removeAction(Action* action); + virtual void addActionAt(unsigned int frame, Action* action, int priority = 0); + virtual void addActionAt(double t, Action* action, int priority = 0); + void addActionNow(Action* action, int priority = 0); + + void clearActions(); + + virtual void update(double simulationTime); + void setLastFrameEvaluated(unsigned int frame) { _previousFrameEvaluated = frame; } + + void setEvaluating(bool state) { _evaluating = state;} + void traverse(ActionVisitor& visitor); + + void setStats(osg::Stats* stats); + osg::Stats* getStats(); + void collectStats(bool state); + osgAnimation::StatsActionVisitor* getStatsVisitor(); + + const ActionLayers& getActionLayers() const { return _actions; } + + void processPendingOperation(); + void setAnimationManager(AnimationManagerBase*); + protected: + osg::observer_ptr _animationManager; + ActionLayers _actions; + double _lastUpdate; + double _speed; + unsigned int _currentFrame; + unsigned int _previousFrameEvaluated; + bool _initFirstFrame; + TimelineStatus _state; + + bool _collectStats; + osg::ref_ptr _stats; + osg::ref_ptr _statsVisitor; + + // to manage pending operation + bool _evaluating; + + struct Command + { + Command():_priority(0) {} + Command(int priority, const FrameAction& action) : _priority(priority), _action(action) {} + int _priority; + FrameAction _action; + }; + + typedef std::vector CommandList; + CommandList _addActionOperations; + ActionList _removeActionOperations; + + void internalRemoveAction(Action* action); + void internalAddAction(int priority, const FrameAction& ftl); + + }; + + + +} + +#endif diff --git a/libs/include/android/osgAnimation/TimelineAnimationManager b/libs/include/android/osgAnimation/TimelineAnimationManager new file mode 100755 index 0000000..bf7d7b8 --- /dev/null +++ b/libs/include/android/osgAnimation/TimelineAnimationManager @@ -0,0 +1,44 @@ +/* -*-c++-*- + * Copyright (C) 2008 Cedric Pinson + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. + */ + +#ifndef OSGANIMATION_TIMELINE_ANIMATION_MANAGER +#define OSGANIMATION_TIMELINE_ANIMATION_MANAGER 1 + +#include +#include +#include + + +namespace osgAnimation +{ + + class OSGANIMATION_EXPORT TimelineAnimationManager : public AnimationManagerBase + { + protected: + osg::ref_ptr _timeline; + + public: + META_Object(osgAnimation, TimelineAnimationManager); + TimelineAnimationManager(); + TimelineAnimationManager(const AnimationManagerBase& manager); + TimelineAnimationManager(const TimelineAnimationManager& nc,const osg::CopyOp&); + + Timeline* getTimeline() { return _timeline.get(); } + const Timeline* getTimeline() const { return _timeline.get(); } + void update(double time); + }; + +} + +#endif diff --git a/libs/include/android/osgAnimation/UpdateBone b/libs/include/android/osgAnimation/UpdateBone new file mode 100755 index 0000000..b364cea --- /dev/null +++ b/libs/include/android/osgAnimation/UpdateBone @@ -0,0 +1,36 @@ +/* -*-c++-*- + * Copyright (C) 2009 Cedric Pinson + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. + */ + +#ifndef OSGANIMATION_UPDATE_BONE +#define OSGANIMATION_UPDATE_BONE 1 + +#include +#include + +namespace osgAnimation +{ + + class OSGANIMATION_EXPORT UpdateBone : public UpdateMatrixTransform + { + public: + META_Object(osgAnimation, UpdateBone); + + UpdateBone(const std::string& name = ""); + UpdateBone(const UpdateBone&,const osg::CopyOp&); + void operator()(osg::Node* node, osg::NodeVisitor* nv); + }; + +} + +#endif diff --git a/libs/include/android/osgAnimation/UpdateMaterial b/libs/include/android/osgAnimation/UpdateMaterial new file mode 100755 index 0000000..a00d150 --- /dev/null +++ b/libs/include/android/osgAnimation/UpdateMaterial @@ -0,0 +1,46 @@ +/* -*-c++-*- + * Copyright (C) 2009 Cedric Pinson + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. + */ + +#ifndef OSGANIMATION_UPDATE_MATERIAL +#define OSGANIMATION_UPDATE_MATERIAL 1 + +#include +#include +#include +#include + +namespace osgAnimation +{ + + class OSGANIMATION_EXPORT UpdateMaterial : public AnimationUpdateCallback + { + protected: + osg::ref_ptr _diffuse; + + public: + + META_Object(osgAnimation, UpdateMaterial); + + UpdateMaterial(const std::string& name = ""); + UpdateMaterial(const UpdateMaterial& apc,const osg::CopyOp& copyop); + + /** Callback method called by the NodeVisitor when visiting a node.*/ + virtual void operator () (osg::StateAttribute*, osg::NodeVisitor*); + void update(osg::Material& material); + bool link(Channel* channel); + Vec4Target* getDiffuse(); + }; +} + +#endif diff --git a/libs/include/android/osgAnimation/UpdateMatrixTransform b/libs/include/android/osgAnimation/UpdateMatrixTransform new file mode 100755 index 0000000..b39c806 --- /dev/null +++ b/libs/include/android/osgAnimation/UpdateMatrixTransform @@ -0,0 +1,48 @@ +/* -*-c++-*- + * Copyright (C) 2009 Cedric Pinson + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. + */ + + +#ifndef OSGANIMATION_UPDATE_MATRIX_TRANSFORM +#define OSGANIMATION_UPDATE_MATRIX_TRANSFORM 1 + +#include +#include +#include +#include + +namespace osgAnimation +{ + + class OSGANIMATION_EXPORT UpdateMatrixTransform : public AnimationUpdateCallback + { + public: + META_Object(osgAnimation, UpdateMatrixTransform); + + UpdateMatrixTransform(const std::string& name = ""); + UpdateMatrixTransform(const UpdateMatrixTransform& apc,const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY); + + // Callback method called by the NodeVisitor when visiting a node. + virtual void operator()(osg::Node* node, osg::NodeVisitor* nv); + virtual bool link(osgAnimation::Channel* channel); + + StackedTransform& getStackedTransforms() { return _transforms;} + const StackedTransform& getStackedTransforms() const { return _transforms;} + + protected: + StackedTransform _transforms; + }; + +} + +#endif diff --git a/libs/include/android/osgAnimation/Vec3Packed b/libs/include/android/osgAnimation/Vec3Packed new file mode 100755 index 0000000..f2587ae --- /dev/null +++ b/libs/include/android/osgAnimation/Vec3Packed @@ -0,0 +1,119 @@ +/* -*-c++-*- +*/ +//****************************************************************************// +// loader.cpp // +// Copyright (C) 2001, 2002 Bruno 'Beosil' Heidelberger // +//****************************************************************************// +// This library is free software; you can redistribute it and/or modify it // +// under the terms of the GNU Lesser General Public License as published by // +// the Free Software Foundation; either version 2.1 of the License, or (at // +// your option) any later version. // +//****************************************************************************// + +/*****************************************************************************/ +/* Loads a core compressed keyframe instance. + * + * This function loads a core compressed keyframe instance from a data source. + * + * @param dataSrc The data source to load the core compressed keyframe instance from. + * + * @return One of the following values: + * \li a pointer to the core keyframe + * \li \b 0 if an error happened + * Authors + * Igor Kravchenko + * Cedric Pinson + *****************************************************************************/ + + +#ifndef OSGANIMATION_PACKED_H +#define OSGANIMATION_PACKED_H + +#include +#include +#include +#include + +namespace osgAnimation +{ + + + struct Vec3Packed + { + typedef unsigned int uint32_t; + uint32_t m32bits; + Vec3Packed(uint32_t val): m32bits(val) {} + Vec3Packed(): m32bits(0) {} + + void uncompress(const osg::Vec3& scale, const osg::Vec3& min, osg::Vec3& result) const + { + uint32_t pt[3]; + pt[0] = m32bits & 0x7ff; + pt[1] = (m32bits >> 11) & 0x7ff; + pt[2] = m32bits >> 22; + result[0] = scale[0] * pt[0] + min[0]; + result[1] = scale[1] * pt[1] + min[1]; + result[2] = scale[2] * pt[2] + min[2]; + } + + void compress(const osg::Vec3f& src, const osg::Vec3f& min, const osg::Vec3f& scaleInv) + { + uint32_t srci[3]; + srci[0] = osg::minimum(static_cast(((src[0] - min[0] )*scaleInv[0])), uint32_t(2047)); + srci[1] = osg::minimum(static_cast(((src[1] - min[1] )*scaleInv[1])), uint32_t(2047)); + srci[2] = osg::minimum(static_cast(((src[2] - min[2] )*scaleInv[2])), uint32_t(1023)); + m32bits = srci[0] + (srci[1] << 11) + (srci[2] << 22); + } + }; + + struct Vec3ArrayPacked + { + std::vector mVecCompressed; + osg::Vec3 mMin; + osg::Vec3 mScale; + osg::Vec3 mScaleInv; + + void analyze(const std::vector& src) + { + //analyze the keys + mMin.set(FLT_MAX, FLT_MAX, FLT_MAX); + osg::Vec3 maxp(-FLT_MAX, -FLT_MAX, -FLT_MAX); + int nb = (int)src.size(); + for(int i = 0; i < nb; i++) + { + const osg::Vec3 &pos = src[i]; + for(int j = 0; j < 3; j++) + { + maxp[j] = osg::maximum(pos[j],maxp[j]); + mMin[j] = osg::minimum(pos[j],mMin[j]); + } + } + + osg::Vec3 diff = maxp - mMin; + mScaleInv.set(0,0,0); + if (diff[0] != 0) + mScaleInv[0] = 2047.0/diff[0]; + + if (diff[1] != 0) + mScaleInv[1] = 2047.0/diff[1]; + + if (diff[2] != 0) + mScaleInv[2] = 1023.0/diff[2]; + + mScale[0] = diff[0] / 2047; + mScale[1] = diff[1] / 2047; + mScale[2] = diff[2] / 1023; + } + + void compress(const std::vector& src) + { + mVecCompressed.resize(src.size()); + // save all core keyframes + for(int i = 0; i < (int)src.size(); i++) + mVecCompressed[i].compress(src[i], mMin, mScaleInv); + } + }; + +} + +#endif diff --git a/libs/include/android/osgAnimation/VertexInfluence b/libs/include/android/osgAnimation/VertexInfluence new file mode 100755 index 0000000..c385ea1 --- /dev/null +++ b/libs/include/android/osgAnimation/VertexInfluence @@ -0,0 +1,103 @@ +/* -*-c++-*- + * Copyright (C) 2008 Cedric Pinson + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGANIMATION_VERTEX_INFLUENCE +#define OSGANIMATION_VERTEX_INFLUENCE 1 + +#include +#include +#include +#include +#include + +namespace osgAnimation +{ + + // first is vertex index, and second the weight, the + typedef std::pair VertexIndexWeight; + typedef std::vector VertexList; + class OSGANIMATION_EXPORT VertexInfluence : public VertexList + { + public: + const std::string& getName() const { return _name;} + void setName(const std::string& name) { _name = name;} + + protected: + // the name is the bone to link to + std::string _name; + }; + + class VertexInfluenceMap : public std::map , public osg::Object + { + public: + META_Object(osgAnimation, VertexInfluenceMap); + + VertexInfluenceMap() {} + VertexInfluenceMap(const osgAnimation::VertexInfluenceMap&, const osg::CopyOp&) {} + }; + + + // this class manage VertexInfluence database by mesh + // reference bones per vertex ... + class OSGANIMATION_EXPORT VertexInfluenceSet + { + public: + typedef std::vector BoneToVertexList; + + class BoneWeight + { + public: + BoneWeight(const std::string& name, float weight) : _boneName(name), _weight(weight) {} + const std::string& getBoneName() const { return _boneName; } + float getWeight() const { return _weight; } + void setWeight(float weight) { _weight = weight; } + bool operator==(const BoneWeight& b) const { return (_boneName == b.getBoneName() && _weight == b.getWeight()); } + protected: + std::string _boneName; + float _weight; + }; + + typedef std::vector BoneWeightList; + typedef std::map VertexIndexToBoneWeightMap; + + class UniqVertexSetToBoneSet + { + public: + void setBones(BoneWeightList& bones) { _bones = bones;} + const BoneWeightList& getBones() const { return _bones;} + std::vector& getVertexes() { return _vertexes;} + const std::vector& getVertexes() const { return _vertexes;} + protected: + std::vector _vertexes; + BoneWeightList _bones; // here we could limit matrix operation by caching (weight * matrix) + }; + + typedef std::vector UniqVertexSetToBoneSetList; + + const UniqVertexSetToBoneSetList& getUniqVertexSetToBoneSetList() const { return _uniqVertexSetToBoneSet;} + void addVertexInfluence(const VertexInfluence& v); + void buildVertex2BoneList(); + void buildUniqVertexSetToBoneSetList(); + void clear(); + + const VertexIndexToBoneWeightMap& getVertexToBoneList() const; + protected: + BoneToVertexList _bone2Vertexes; + VertexIndexToBoneWeightMap _vertex2Bones; + UniqVertexSetToBoneSetList _uniqVertexSetToBoneSet; + }; + +} + +#endif diff --git a/libs/include/android/osgDB/Archive b/libs/include/android/osgDB/Archive new file mode 100755 index 0000000..9f69d28 --- /dev/null +++ b/libs/include/android/osgDB/Archive @@ -0,0 +1,86 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGDB_ARCHIVE +#define OSGDB_ARCHIVE 1 + +#include +#include +#include + +#include +#include + +namespace osgDB { + + +/** Base class for implementing database Archives. See src/osgPlugins/osga for an example of a concrete implementation. */ +class OSGDB_EXPORT Archive : public ReaderWriter +{ + public: + Archive(); + virtual ~Archive(); + + virtual const char* libraryName() const { return "osgDB"; } + + virtual const char* className() const { return "Archive"; } + + virtual bool acceptsExtension(const std::string& /*extension*/) const { return true; } + + /** close the archive.*/ + virtual void close() = 0; + + /** Get the file name which represents the archived file.*/ + virtual std::string getArchiveFileName() const = 0; + + /** Get the file name which represents the master file recorded in the Archive.*/ + virtual std::string getMasterFileName() const = 0; + + /** return true if file exists in archive.*/ + virtual bool fileExists(const std::string& filename) const = 0; + + /** return type of file. */ + virtual FileType getFileType(const std::string& filename) const = 0; + + typedef osgDB::DirectoryContents FileNameList; + + /** Get the full list of file names available in the archive.*/ + virtual bool getFileNames(FileNameList& fileNames) const = 0; + + /** return the contents of a directory. + * returns an empty array on any error.*/ + virtual DirectoryContents getDirectoryContents(const std::string& dirName) const; + + + virtual ReadResult readObject(const std::string& /*fileName*/,const Options* =NULL) const = 0; + virtual ReadResult readImage(const std::string& /*fileName*/,const Options* =NULL) const = 0; + virtual ReadResult readHeightField(const std::string& /*fileName*/,const Options* =NULL) const = 0; + virtual ReadResult readNode(const std::string& /*fileName*/,const Options* =NULL) const = 0; + virtual ReadResult readShader(const std::string& /*fileName*/,const Options* =NULL) const = 0; + + virtual WriteResult writeObject(const osg::Object& /*obj*/,const std::string& /*fileName*/,const Options* =NULL) const = 0; + virtual WriteResult writeImage(const osg::Image& /*image*/,const std::string& /*fileName*/,const Options* =NULL) const = 0; + virtual WriteResult writeHeightField(const osg::HeightField& /*heightField*/,const std::string& /*fileName*/,const Options* =NULL) const = 0; + virtual WriteResult writeNode(const osg::Node& /*node*/,const std::string& /*fileName*/,const Options* =NULL) const = 0; + virtual WriteResult writeShader(const osg::Shader& /*shader*/,const std::string& /*fileName*/,const Options* =NULL) const = 0; + +}; + +/** Open an archive for reading or writing.*/ +OSGDB_EXPORT Archive* openArchive(const std::string& filename, ReaderWriter::ArchiveStatus status, unsigned int indexBlockSizeHint=4096); + +/** Open an archive for reading or writing.*/ +OSGDB_EXPORT Archive* openArchive(const std::string& filename, ReaderWriter::ArchiveStatus status, unsigned int indexBlockSizeHint,Options* options); +} + +#endif // OSGDB_ARCHIVE diff --git a/libs/include/android/osgDB/AuthenticationMap b/libs/include/android/osgDB/AuthenticationMap new file mode 100755 index 0000000..5c36c07 --- /dev/null +++ b/libs/include/android/osgDB/AuthenticationMap @@ -0,0 +1,79 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGDB_AUTHENTICATIONMAP +#define OSGDB_AUTHENTICATIONMAP 1 + +#include +#include + +#include + +#include +#include + +namespace osgDB { + +class Archive; + +class AuthenticationDetails : public osg::Referenced +{ +public: + + /** Http authentication techniques, see libcurl docs for details on names and associated functionality.*/ + enum HttpAuthentication + { + BASIC = 1<<0, + DIGEST = 1<<1, + NTLM = 1<<2, + GSSNegotiate = 1<<2, + ANY = ~0, + ANYSAFE = ~BASIC + }; + + AuthenticationDetails(const std::string& u, const std::string& p, HttpAuthentication auth=BASIC): + username(u), + password(p), + httpAuthentication(auth) {} + + std::string username; + std::string password; + HttpAuthentication httpAuthentication; + +protected: + virtual ~AuthenticationDetails() {} +}; + +class OSGDB_EXPORT AuthenticationMap : public osg::Referenced +{ + public: + + AuthenticationMap() {} + + + virtual void addAuthenticationDetails(const std::string& path, AuthenticationDetails* details); + + virtual const AuthenticationDetails* getAuthenticationDetails(const std::string& path) const; + + protected: + + virtual ~AuthenticationMap() {} + + typedef std::map > AuthenticationDetailsMap; + AuthenticationDetailsMap _authenticationMap; + +}; + +} + +#endif // OSGDB_AUTHENTICATIONMAP diff --git a/libs/include/android/osgDB/Callbacks b/libs/include/android/osgDB/Callbacks new file mode 100755 index 0000000..7e0e6f2 --- /dev/null +++ b/libs/include/android/osgDB/Callbacks @@ -0,0 +1,110 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGDB_CALLBACKS +#define OSGDB_CALLBACKS 1 + +#include +#include +#include + +#include +#include +#include + +namespace osgDB { + +/** list of directories to search through which searching for files. */ +typedef std::deque FilePathList; + +enum CaseSensitivity +{ + CASE_SENSITIVE, + CASE_INSENSITIVE +}; + +// forward decare +class Options; + +class OSGDB_EXPORT FindFileCallback : public virtual osg::Referenced +{ + public: + + virtual std::string findDataFile(const std::string& filename, const Options* options, CaseSensitivity caseSensitivity); + + virtual std::string findLibraryFile(const std::string& filename, const Options* options, CaseSensitivity caseSensitivity); + + protected: + virtual ~FindFileCallback() {} +}; + + +class OSGDB_EXPORT ReadFileCallback : public virtual osg::Referenced +{ + public: + + virtual ReaderWriter::ReadResult openArchive(const std::string& filename,ReaderWriter::ArchiveStatus status, unsigned int indexBlockSizeHint, const Options* useObjectCache); + + virtual ReaderWriter::ReadResult readObject(const std::string& filename, const Options* options); + + virtual ReaderWriter::ReadResult readImage(const std::string& filename, const Options* options); + + virtual ReaderWriter::ReadResult readHeightField(const std::string& filename, const Options* options); + + virtual ReaderWriter::ReadResult readNode(const std::string& filename, const Options* options); + + virtual ReaderWriter::ReadResult readShader(const std::string& filename, const Options* options); + + protected: + virtual ~ReadFileCallback() {} +}; + +class OSGDB_EXPORT WriteFileCallback : public virtual osg::Referenced +{ + public: + + virtual ReaderWriter::WriteResult writeObject(const osg::Object& obj, const std::string& fileName,const Options* options); + + virtual ReaderWriter::WriteResult writeImage(const osg::Image& obj, const std::string& fileName,const Options* options); + + virtual ReaderWriter::WriteResult writeHeightField(const osg::HeightField& obj, const std::string& fileName,const Options* options); + + virtual ReaderWriter::WriteResult writeNode(const osg::Node& obj, const std::string& fileName,const Options* options); + + virtual ReaderWriter::WriteResult writeShader(const osg::Shader& obj, const std::string& fileName,const Options* options); + + protected: + virtual ~WriteFileCallback() {} +}; + +class OSGDB_EXPORT FileLocationCallback : public virtual osg::Referenced +{ + public: + + enum Location + { + LOCAL_FILE, + REMOTE_FILE + }; + + virtual Location fileLocation(const std::string& filename, const Options* options) = 0; + + virtual bool useFileCache() const = 0; + + protected: + virtual ~FileLocationCallback() {} +}; + +} + +#endif // OSGDB_OPTIONS diff --git a/libs/include/android/osgDB/ConvertUTF b/libs/include/android/osgDB/ConvertUTF new file mode 100755 index 0000000..90f87bb --- /dev/null +++ b/libs/include/android/osgDB/ConvertUTF @@ -0,0 +1,52 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 2008 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGDB_CONVERTUTF +#define OSGDB_CONVERTUTF 1 + +#include +#include + +#include + +#if defined(__CYGWIN__) || defined(ANDROID) +namespace std +{ +typedef basic_string wstring; +} +#endif + +namespace osgDB +{ + +extern OSGDB_EXPORT std::string convertUTF16toUTF8(const wchar_t* source, unsigned sourceLength); +extern OSGDB_EXPORT std::wstring convertUTF8toUTF16(const char* source, unsigned sourceLength); + +extern OSGDB_EXPORT std::string convertUTF16toUTF8(const std::wstring& s); +extern OSGDB_EXPORT std::string convertUTF16toUTF8(const wchar_t* s); + +extern OSGDB_EXPORT std::wstring convertUTF8toUTF16(const std::string& s); +extern OSGDB_EXPORT std::wstring convertUTF8toUTF16(const char* s); + +extern OSGDB_EXPORT std::string convertStringFromCurrentCodePageToUTF8(const char* source, unsigned sourceLength); +extern OSGDB_EXPORT std::string convertStringFromUTF8toCurrentCodePage(const char* source, unsigned sourceLength); + +extern OSGDB_EXPORT std::string convertStringFromCurrentCodePageToUTF8(const std::string& s); +extern OSGDB_EXPORT std::string convertStringFromCurrentCodePageToUTF8(const char* s); + +extern OSGDB_EXPORT std::string convertStringFromUTF8toCurrentCodePage(const std::string& s); +extern OSGDB_EXPORT std::string convertStringFromUTF8toCurrentCodePage(const char* s); + +} + +#endif diff --git a/libs/include/android/osgDB/DataTypes b/libs/include/android/osgDB/DataTypes new file mode 100755 index 0000000..9425305 --- /dev/null +++ b/libs/include/android/osgDB/DataTypes @@ -0,0 +1,133 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2010 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +// Written by Wang Rui, (C) 2010 + +#ifndef OSGDB_DATATYPES +#define OSGDB_DATATYPES + +#include +#include + +namespace osgDB +{ + +// OSG Header (MD5, 16Bit) +#define OSG_HEADER_LOW 0x6C910EA1 +#define OSG_HEADER_HIGH 0x1AFB4545 + +// Reader/writer plugin version +const unsigned int PLUGIN_VERSION = 2; + +const int BOOL_SIZE = 1; +const int CHAR_SIZE = 1; +const int SHORT_SIZE = 2; +const int INT_SIZE = 4; +const int LONG_SIZE = 4; +const int FLOAT_SIZE = 4; +const int DOUBLE_SIZE = 8; +const int GLENUM_SIZE = 4; + +const int ID_BYTE_ARRAY = 0; +const int ID_UBYTE_ARRAY = 1; +const int ID_SHORT_ARRAY = 2; +const int ID_USHORT_ARRAY = 3; +const int ID_INT_ARRAY = 4; +const int ID_UINT_ARRAY = 5; +const int ID_FLOAT_ARRAY = 6; +const int ID_DOUBLE_ARRAY = 7; +const int ID_VEC2B_ARRAY = 8; +const int ID_VEC3B_ARRAY = 9; +const int ID_VEC4B_ARRAY = 10; +const int ID_VEC4UB_ARRAY = 11; +const int ID_VEC2S_ARRAY = 12; +const int ID_VEC3S_ARRAY = 13; +const int ID_VEC4S_ARRAY = 14; +const int ID_VEC2_ARRAY = 15; +const int ID_VEC3_ARRAY = 16; +const int ID_VEC4_ARRAY = 17; +const int ID_VEC2D_ARRAY = 18; +const int ID_VEC3D_ARRAY = 19; +const int ID_VEC4D_ARRAY = 20; +const int ID_VEC2UB_ARRAY = 21; +const int ID_VEC3UB_ARRAY = 22; +const int ID_VEC2US_ARRAY = 23; +const int ID_VEC3US_ARRAY = 24; +const int ID_VEC4US_ARRAY = 25; + +const int ID_DRAWARRAYS = 50; +const int ID_DRAWARRAY_LENGTH = 51; +const int ID_DRAWELEMENTS_UBYTE = 52; +const int ID_DRAWELEMENTS_USHORT = 53; +const int ID_DRAWELEMENTS_UINT = 54; + +// Used by BEGIN_BRACKET and END_BRACKET +const int INDENT_VALUE = 2; + +// Used by the writeImage/readImage parameter +const int IMAGE_INLINE_DATA = 0; +const int IMAGE_INLINE_FILE = 1; +const int IMAGE_EXTERNAL = 2; +const int IMAGE_WRITE_OUT = 3; + +struct ObjectGLenum +{ + ObjectGLenum( GLenum value=0 ) : _value(value) {} + ObjectGLenum( const ObjectGLenum& copy ) : _value(copy._value) {} + void set( GLenum e ) { _value = e; } + GLenum get() const { return _value; } + GLenum _value; +}; +#define GLENUM(value) osgDB::ObjectGLenum(value) +#define DEF_GLENUM(var) osgDB::ObjectGLenum var; + +class ObjectProperty +{ +public: + ObjectProperty() : _value(0), _mapProperty(false) {} + + ObjectProperty( const char* name, int value=0, bool useMap=false ) + : _name(name), _value(value), _mapProperty(useMap) {} + + ObjectProperty( const ObjectProperty& copy ) + : _name(copy._name), _value(copy._value), _mapProperty(copy._mapProperty) {} + + ObjectProperty& operator()( const char* name ) + { _name = name; return *this; } + + void set( int v ) { _value = v; } + int get() const { return _value; } + + std::string _name; + int _value; + bool _mapProperty; +}; +#define MAPPEE(pairName, value) osgDB::ObjectProperty(#pairName, value, true) +#define DEF_MAPPEE(pairName, var) osgDB::ObjectProperty var(#pairName, 0, true); + +class ObjectMark +{ +public: + ObjectMark() : _indentDelta(0) {} + + ObjectMark( const ObjectMark& copy ) + : _name(copy._name), _indentDelta(copy._indentDelta) {} + + void set( const char* name, int delta=0 ) + { _name = name, _indentDelta = delta; } + + std::string _name; + int _indentDelta; +}; + +} +#endif diff --git a/libs/include/android/osgDB/DatabasePager b/libs/include/android/osgDB/DatabasePager new file mode 100755 index 0000000..5c84448 --- /dev/null +++ b/libs/include/android/osgDB/DatabasePager @@ -0,0 +1,476 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGDB_DATABASEPAGER +#define OSGDB_DATABASEPAGER 1 + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include + +#include +#include +#include + + +#include +#include +#include +#include + +namespace osgDB { + + + +/** Database paging class which manages the loading of files in a background thread, + * and synchronizing of loaded models with the main scene graph.*/ +class OSGDB_EXPORT DatabasePager : public osg::NodeVisitor::DatabaseRequestHandler +{ + public : + + typedef OpenThreads::Thread::ThreadPriority ThreadPriority; + + DatabasePager(); + + DatabasePager(const DatabasePager& rhs); + + virtual const char* className() const { return "DatabasePager"; } + + /** Create a shallow copy on the DatabasePager.*/ + virtual DatabasePager* clone() const { return new DatabasePager(*this); } + + /** get the prototype singleton used by DatabasePager::create().*/ + static osg::ref_ptr& prototype(); + + /** create a DatabasePager by cloning DatabasePager::prototype().*/ + static DatabasePager* create(); + + + + /** Add a request to load a node file to end the the database request list.*/ + virtual void requestNodeFile(const std::string& fileName, osg::NodePath& nodePath, + float priority, const osg::FrameStamp* framestamp, + osg::ref_ptr& databaseRequest, + const osg::Referenced* options); + + /** Set the priority of the database pager thread(s).*/ + int setSchedulePriority(OpenThreads::Thread::ThreadPriority priority); + + /** Cancel the database pager thread(s).*/ + virtual int cancel(); + + virtual bool isRunning() const; + + /** Clear all internally cached structures.*/ + virtual void clear(); + + class OSGDB_EXPORT DatabaseThread : public osg::Referenced, public OpenThreads::Thread + { + public: + + enum Mode + { + HANDLE_ALL_REQUESTS, + HANDLE_NON_HTTP, + HANDLE_ONLY_HTTP + }; + + DatabaseThread(DatabasePager* pager, Mode mode, const std::string& name); + + DatabaseThread(const DatabaseThread& dt, DatabasePager* pager); + + void setName(const std::string& name) { _name = name; } + const std::string& getName() const { return _name; } + + void setDone(bool done) { _done.exchange(done?1:0); } + bool getDone() const { return _done!=0; } + + void setActive(bool active) { _active = active; } + bool getActive() const { return _active; } + + virtual int cancel(); + + virtual void run(); + + protected: + + virtual ~DatabaseThread(); + + OpenThreads::Atomic _done; + volatile bool _active; + DatabasePager* _pager; + Mode _mode; + std::string _name; + + }; + + void setUpThreads(unsigned int totalNumThreads=2, unsigned int numHttpThreads=1); + + virtual unsigned int addDatabaseThread(DatabaseThread::Mode mode, const std::string& name); + + DatabaseThread* getDatabaseThread(unsigned int i) { return _databaseThreads[i].get(); } + + const DatabaseThread* getDatabaseThread(unsigned int i) const { return _databaseThreads[i].get(); } + + unsigned int getNumDatabaseThreads() const { return static_cast(_databaseThreads.size()); } + + /** Set whether the database pager thread should be paused or not.*/ + void setDatabasePagerThreadPause(bool pause); + + /** Get whether the database pager thread should is paused or not.*/ + bool getDatabasePagerThreadPause() const { return _databasePagerThreadPaused; } + + /** Set whether new database request calls are accepted or ignored.*/ + void setAcceptNewDatabaseRequests(bool acceptNewRequests) { _acceptNewRequests = acceptNewRequests; } + + /** Get whether new database request calls are accepted or ignored.*/ + bool getAcceptNewDatabaseRequests() const { return _acceptNewRequests; } + + /** Get the number of frames that are currently active.*/ + int getNumFramesActive() const { return _numFramesActive; } + + /** Signal the database thread that the update, cull and draw has begun for a new frame. + * Note, this is called by the application so that the database pager can go to sleep while the CPU is busy on the main rendering threads. */ + virtual void signalBeginFrame(const osg::FrameStamp* framestamp); + + /** Signal the database thread that the update, cull and draw dispatch has completed. + * Note, this is called by the application so that the database pager can go to wake back up now the main rendering threads are iddle waiting for the next frame.*/ + virtual void signalEndFrame(); + + + /** Find all PagedLOD nodes in a subgraph and register them with + * the DatabasePager so it can keep track of expired nodes. + * note, should be only be called from the update thread. */ + virtual void registerPagedLODs(osg::Node* subgraph, unsigned int frameNumber = 0); + + /** Set the incremental compile operation. + * Used to manage the OpenGL object compilation and merging of subgraphs in a way that avoids overloading + * the rendering of frame with too many new objects in one frame. */ + void setIncrementalCompileOperation(osgUtil::IncrementalCompileOperation* ico); + + /** Get the incremental compile operation. */ + osgUtil::IncrementalCompileOperation* getIncrementalCompileOperation() { return _incrementalCompileOperation.get(); } + + + /** Set whether the database pager should pre compile OpenGL objects before allowing + * them to be merged into the scene graph. + * Pre compilation helps reduce the chances of frame drops, but also slows the + * speed at which tiles are merged as they have to be compiled first.*/ + void setDoPreCompile(bool flag) { _doPreCompile = flag; } + + /** Get whether the database pager should pre compile OpenGL objects before allowing + * them to be merged into the scene graph.*/ + bool getDoPreCompile() const { return _doPreCompile; } + + + + /** Set the target maximum number of PagedLOD to maintain in memory. + * Note, if more than the target number are required for rendering of a frame then these active PagedLOD are excempt from being expiried. + * But once the number of active drops back below the target the inactive PagedLOD will be trimmed back to the target number.*/ + void setTargetMaximumNumberOfPageLOD(unsigned int target) { _targetMaximumNumberOfPageLOD = target; } + + /** Get the target maximum number of PagedLOD to maintain in memory.*/ + unsigned int getTargetMaximumNumberOfPageLOD() const { return _targetMaximumNumberOfPageLOD; } + + + /** Set whether the removed subgraphs should be deleted in the database thread or not.*/ + void setDeleteRemovedSubgraphsInDatabaseThread(bool flag) { _deleteRemovedSubgraphsInDatabaseThread = flag; } + + /** Get whether the removed subgraphs should be deleted in the database thread or not.*/ + bool getDeleteRemovedSubgraphsInDatabaseThread() const { return _deleteRemovedSubgraphsInDatabaseThread; } + + enum DrawablePolicy + { + DO_NOT_MODIFY_DRAWABLE_SETTINGS, + USE_DISPLAY_LISTS, + USE_VERTEX_BUFFER_OBJECTS, + USE_VERTEX_ARRAYS + }; + + /** Set how loaded drawables should be handled w.r.t their display list/vertex buffer object/vertex array settings.*/ + void setDrawablePolicy(DrawablePolicy policy) { _drawablePolicy = policy; } + + /** Get how loaded drawables should be handled w.r.t their display list/vertex buffer object/vertex array settings.*/ + DrawablePolicy getDrawablePolicy() const { return _drawablePolicy; } + + + /** Set whether newly loaded textures should have a PixelBufferObject assigned to them to aid download to the GPU.*/ + void setApplyPBOToImages(bool assignPBOToImages) { _assignPBOToImages = assignPBOToImages; } + + /** Get whether newly loaded textures should have a PixelBufferObject assigned to them..*/ + bool getApplyPBOToImages() const { return _assignPBOToImages; } + + + /** Set whether newly loaded textures should have their UnrefImageDataAfterApply set to a specified value.*/ + void setUnrefImageDataAfterApplyPolicy(bool changeAutoUnRef, bool valueAutoUnRef) { _changeAutoUnRef = changeAutoUnRef; _valueAutoUnRef = valueAutoUnRef; } + + /** Get whether newly loaded textures should have their UnrefImageDataAfterApply set to a specified value.*/ + void getUnrefImageDataAfterApplyPolicy(bool& changeAutoUnRef, bool& valueAutoUnRef) const { changeAutoUnRef = _changeAutoUnRef; valueAutoUnRef = _valueAutoUnRef; } + + + /** Set whether newly loaded textures should have their MaxAnisotopy set to a specified value.*/ + void setMaxAnisotropyPolicy(bool changeAnisotropy, float valueAnisotropy) { _changeAnisotropy = changeAnisotropy; _valueAnisotropy = valueAnisotropy; } + + /** Set whether newly loaded textures should have their MaxAnisotopy set to a specified value.*/ + void getMaxAnisotropyPolicy(bool& changeAnisotropy, float& valueAnisotropy) const { changeAnisotropy = _changeAnisotropy; valueAnisotropy = _valueAnisotropy; } + + + /** Return true if there are pending updates to the scene graph that require a call to updateSceneGraph(double). */ + bool requiresUpdateSceneGraph() const; + + /** Merge the changes to the scene graph by calling calling removeExpiredSubgraphs then addLoadedDataToSceneGraph. + * Note, must only be called from single thread update phase. */ + virtual void updateSceneGraph(const osg::FrameStamp& frameStamp); + + /** Report how many items are in the _fileRequestList queue */ + unsigned int getFileRequestListSize() const { return static_cast(_fileRequestQueue->size() + _httpRequestQueue->size()); } + + /** Report how many items are in the _dataToCompileList queue */ + unsigned int getDataToCompileListSize() const { return static_cast(_dataToCompileList->size()); } + + /** Report how many items are in the _dataToMergeList queue */ + unsigned int getDataToMergeListSize() const { return static_cast(_dataToMergeList->size()); } + + /** Report whether any requests are in the pager.*/ + bool getRequestsInProgress() const; + + /** Get the minimum time between the first request for a tile to be loaded and the time of its merge into the main scene graph.*/ + double getMinimumTimeToMergeTile() const { return _minimumTimeToMergeTile; } + + /** Get the maximum time between the first request for a tile to be loaded and the time of its merge into the main scene graph.*/ + double getMaximumTimeToMergeTile() const { return _maximumTimeToMergeTile; } + + /** Get the average time between the first request for a tile to be loaded and the time of its merge into the main scene graph.*/ + double getAverageTimeToMergeTiles() const { return (_numTilesMerges > 0) ? _totalTimeToMergeTiles/static_cast(_numTilesMerges) : 0; } + + /** Reset the Stats variables.*/ + void resetStats(); + + typedef std::set< osg::ref_ptr > StateSetList; + typedef std::vector< osg::ref_ptr > DrawableList; + + class ExpirePagedLODsVisitor; + + typedef std::list< osg::ref_ptr > ObjectList; + + struct PagedLODList : public osg::Referenced + { + virtual PagedLODList* clone() = 0; + virtual void clear() = 0; + virtual unsigned int size() = 0; + virtual void removeExpiredChildren(int numberChildrenToRemove, double expiryTime, unsigned int expiryFrame, ObjectList& childrenRemoved, bool visitActive) = 0; + virtual void removeNodes(osg::NodeList& nodesToRemove) = 0; + virtual void insertPagedLOD(const osg::observer_ptr& plod) = 0; + virtual bool containsPagedLOD(const osg::observer_ptr& plod) const = 0; + }; + + + protected: + + virtual ~DatabasePager(); + + friend class DatabaseThread; + friend struct DatabaseRequest; + + struct RequestQueue; + + struct OSGDB_EXPORT DatabaseRequest : public osg::Referenced + { + DatabaseRequest(): + osg::Referenced(true), + _valid(false), + _frameNumberFirstRequest(0), + _timestampFirstRequest(0.0), + _priorityFirstRequest(0.f), + _frameNumberLastRequest(0), + _timestampLastRequest(0.0), + _priorityLastRequest(0.0f), + _numOfRequests(0), + _groupExpired(false) + {} + + void invalidate(); + + bool valid() const { return _valid; } + + bool _valid; + std::string _fileName; + unsigned int _frameNumberFirstRequest; + double _timestampFirstRequest; + float _priorityFirstRequest; + unsigned int _frameNumberLastRequest; + double _timestampLastRequest; + float _priorityLastRequest; + unsigned int _numOfRequests; + + osg::observer_ptr _terrain; + osg::observer_ptr _group; + + osg::ref_ptr _loadedModel; + osg::ref_ptr _loadOptions; + + osg::observer_ptr _compileSet; + bool _groupExpired; // flag used only in update thread + + bool isRequestCurrent (int frameNumber) const + { + return _valid && (frameNumber - _frameNumberLastRequest <= 1); + } + }; + + + struct OSGDB_EXPORT RequestQueue : public osg::Referenced + { + public: + + RequestQueue(DatabasePager* pager); + + void add(DatabaseRequest* databaseRequest); + void remove(DatabaseRequest* databaseRequest); + + void addNoLock(DatabaseRequest* databaseRequest); + + void takeFirst(osg::ref_ptr& databaseRequest); + + /// prune all the old requests and then return true if requestList left empty + bool pruneOldRequestsAndCheckIfEmpty(); + + virtual void updateBlock() {} + + void invalidate(DatabaseRequest* dr); + + bool empty(); + + unsigned int size(); + + void clear(); + + + typedef std::list< osg::ref_ptr > RequestList; + void swap(RequestList& requestList); + + DatabasePager* _pager; + RequestList _requestList; + OpenThreads::Mutex _requestMutex; + unsigned int _frameNumberLastPruned; + + protected: + virtual ~RequestQueue(); + }; + + + typedef std::vector< osg::ref_ptr > DatabaseThreadList; + + struct OSGDB_EXPORT ReadQueue : public RequestQueue + { + ReadQueue(DatabasePager* pager, const std::string& name); + + void block() { _block->block(); } + + void release() { _block->release(); } + + virtual void updateBlock(); + + + osg::ref_ptr _block; + + std::string _name; + + OpenThreads::Mutex _childrenToDeleteListMutex; + ObjectList _childrenToDeleteList; + }; + + // forward declare inner helper classes + class FindCompileableGLObjectsVisitor; + friend class FindCompileableGLObjectsVisitor; + + struct DatabasePagerCompileCompletedCallback; + friend struct DatabasePagerCompileCompletedCallback; + + class FindPagedLODsVisitor; + friend class FindPagedLODsVisitor; + + struct SortFileRequestFunctor; + friend struct SortFileRequestFunctor; + + + OpenThreads::Mutex _run_mutex; + OpenThreads::Mutex _dr_mutex; + bool _startThreadCalled; + + void compileCompleted(DatabaseRequest* databaseRequest); + + /** Iterate through the active PagedLOD nodes children removing + * children which havn't been visited since specified expiryTime. + * note, should be only be called from the update thread. */ + virtual void removeExpiredSubgraphs(const osg::FrameStamp &frameStamp); + + /** Add the loaded data to the scene graph.*/ + void addLoadedDataToSceneGraph(const osg::FrameStamp &frameStamp); + + + bool _done; + bool _acceptNewRequests; + bool _databasePagerThreadPaused; + + DatabaseThreadList _databaseThreads; + + int _numFramesActive; + mutable OpenThreads::Mutex _numFramesActiveMutex; + OpenThreads::Atomic _frameNumber; + + osg::ref_ptr _fileRequestQueue; + osg::ref_ptr _httpRequestQueue; + osg::ref_ptr _dataToCompileList; + osg::ref_ptr _dataToMergeList; + + DrawablePolicy _drawablePolicy; + + bool _assignPBOToImages; + bool _changeAutoUnRef; + bool _valueAutoUnRef; + bool _changeAnisotropy; + float _valueAnisotropy; + + bool _deleteRemovedSubgraphsInDatabaseThread; + + + osg::ref_ptr _activePagedLODList; + + unsigned int _targetMaximumNumberOfPageLOD; + + bool _doPreCompile; + osg::ref_ptr _incrementalCompileOperation; + + + double _minimumTimeToMergeTile; + double _maximumTimeToMergeTile; + double _totalTimeToMergeTiles; + unsigned int _numTilesMerges; +}; + +} + +#endif diff --git a/libs/include/android/osgDB/DatabaseRevisions b/libs/include/android/osgDB/DatabaseRevisions new file mode 100755 index 0000000..d0df009 --- /dev/null +++ b/libs/include/android/osgDB/DatabaseRevisions @@ -0,0 +1,133 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGDB_DATABASEREVISIONS +#define OSGDB_DATABASEREVISIONS 1 + +#include + +#include + +#include + +namespace osgDB { + +class OSGDB_EXPORT FileList : public osg::Object +{ + public: + + FileList(); + FileList(const FileList& fileList, const osg::CopyOp & copyop=osg::CopyOp::SHALLOW_COPY); + + META_Object(osgDB, FileList) + + typedef std::set FileNames; + FileNames& getFileNames() { return _files; } + const FileNames& getFileNames() const { return _files; } + + bool empty() const { return _files.empty(); } + + bool containsFile(const std::string& filename) const { return _files.count(filename)!=0; } + + void addFile(const std::string& filename) { _files.insert(filename); } + + bool removeFile(const std::string& filename); + + void append(FileList* fileList); + + protected: + + virtual ~FileList(); + + FileNames _files; +}; + + +class OSGDB_EXPORT DatabaseRevision : public osg::Object +{ + public: + + DatabaseRevision(); + DatabaseRevision(const DatabaseRevision& revision, const osg::CopyOp & copyop=osg::CopyOp::SHALLOW_COPY); + + META_Object(osgDB, DatabaseRevision) + + void setDatabasePath(const std::string& path) { _databasePath = path; } + const std::string& getDatabasePath() const { return _databasePath; } + + typedef std::set FileNames; + + void setFilesAdded(FileList* fileList) { _filesAdded = fileList; } + FileList* getFilesAdded() { return _filesAdded.get(); } + const FileList* getFilesAdded() const { return _filesAdded.get(); } + + void setFilesRemoved(FileList* fileList) { _filesRemoved = fileList; } + FileList* getFilesRemoved() { return _filesRemoved.get(); } + const FileList* getFilesRemoved() const { return _filesRemoved.get(); } + + void setFilesModified(FileList* fileList) { _filesModified = fileList; } + FileList* getFilesModified() { return _filesModified.get(); } + const FileList* getFilesModified() const { return _filesModified.get(); } + + bool isFileBlackListed(const std::string& filename) const; + + bool removeFile(const std::string& filename); + + protected: + + virtual ~DatabaseRevision(); + + std::string _databasePath; + + osg::ref_ptr _filesAdded; + osg::ref_ptr _filesRemoved; + osg::ref_ptr _filesModified; +}; + +class OSGDB_EXPORT DatabaseRevisions : public osg::Object +{ + public: + + DatabaseRevisions(); + DatabaseRevisions(const DatabaseRevisions& revisions, const osg::CopyOp & copyop=osg::CopyOp::SHALLOW_COPY); + + META_Object(osgDB, DatabaseRevisions) + + typedef std::vector< osg::ref_ptr > DatabaseRevisionList; + + void setDatabasePath(const std::string& path) { _databasePath = path; } + const std::string& getDatabasePath() const { return _databasePath; } + + void addRevision(DatabaseRevision* revision); + void removeRevision(DatabaseRevision* revision); + + DatabaseRevision* getDatabaseRevision(unsigned int i) { return i<_revisionList.size() ? _revisionList[i].get() : 0; } + + DatabaseRevisionList& getDatabaseRevisionList() { return _revisionList; } + const DatabaseRevisionList& getDatabaseRevisionList() const { return _revisionList; } + + bool isFileBlackListed(const std::string& filename) const; + + bool removeFile(const std::string& filename); + + protected: + + virtual ~DatabaseRevisions(); + + std::string _databasePath; + DatabaseRevisionList _revisionList; +}; + +} + +#endif diff --git a/libs/include/android/osgDB/DotOsgWrapper b/libs/include/android/osgDB/DotOsgWrapper new file mode 100755 index 0000000..c7563ca --- /dev/null +++ b/libs/include/android/osgDB/DotOsgWrapper @@ -0,0 +1,171 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGDB_DOTOSGWRAPPER +#define OSGDB_DOTOSGWRAPPER 1 + +#include +#include + +#include +#include + +#include +#include + +namespace osgDB { + + +/** deprecated. */ +class OSGDB_EXPORT DotOsgWrapper : public osg::Referenced +{ + public: + + typedef std::vector Associates; + typedef bool (*ReadFunc)(osg::Object&,osgDB::Input&); + typedef bool (*WriteFunc)(const osg::Object&,osgDB::Output&); + + enum ReadWriteMode + { + READ_AND_WRITE, + READ_ONLY + }; + + DotOsgWrapper(osg::Object* proto, + const std::string& name, + const std::string& associates, + ReadFunc readFunc, + WriteFunc writeFunc, + ReadWriteMode readWriteMode=READ_AND_WRITE); + + + inline const osg::Object* getPrototype() const { return _prototype.get(); } + inline const std::string& getName() const { return _name; } + inline const Associates& getAssociates() const { return _associates; } + inline ReadFunc getReadFunc() const { return _readFunc; } + inline WriteFunc getWriteFunc() const { return _writeFunc; } + inline ReadWriteMode getReadWriteMode() const { return _readWriteMode; } + + protected: + + /// protected to prevent inappropriate creation of wrappers. + DotOsgWrapper() {} + + /// protected to prevent inappropriate creation of wrappers. + DotOsgWrapper(DotOsgWrapper&):osg::Referenced() {} + + /// protected to prevent wrapper being created on stack. + virtual ~DotOsgWrapper() {} + + osg::ref_ptr _prototype; + + std::string _name; + Associates _associates; + + ReadFunc _readFunc; + WriteFunc _writeFunc; + + ReadWriteMode _readWriteMode; +}; + + +/** deprecated. */ +class OSGDB_EXPORT DeprecatedDotOsgWrapperManager : public osg::Referenced +{ + public: + + DeprecatedDotOsgWrapperManager() {} + + void addDotOsgWrapper(DotOsgWrapper* wrapper); + void removeDotOsgWrapper(DotOsgWrapper* wrapper); + + osg::Object* readObjectOfType(const osg::Object& compObj,Input& fr); + osg::Object* readObjectOfType(const basic_type_wrapper &btw, Input& fr); + + osg::Object* readObject(Input& fr); + osg::Image* readImage(Input& fr); + osg::Drawable* readDrawable(Input& fr); + osg::Uniform* readUniform(Input& fr); + osg::StateAttribute* readStateAttribute(Input& fr); + osg::Node* readNode(Input& fr); + osg::Shader* readShader(Input& fr); + + bool writeObject(const osg::Object& obj,Output& fw); + + typedef std::list FileNames; + bool getLibraryFileNamesToTry(const std::string& name, FileNames& fileNames); + + private: + + virtual ~DeprecatedDotOsgWrapperManager() {} + + typedef std::map< std::string, osg::ref_ptr > DotOsgWrapperMap; + + osg::Object* readObject(DotOsgWrapperMap& dowMap,Input& fr); + void eraseWrapper(DotOsgWrapperMap& wrappermap,DotOsgWrapper* wrapper); + + DotOsgWrapperMap _objectWrapperMap; + DotOsgWrapperMap _imageWrapperMap; + DotOsgWrapperMap _drawableWrapperMap; + DotOsgWrapperMap _stateAttrWrapperMap; + DotOsgWrapperMap _uniformWrapperMap; + DotOsgWrapperMap _nodeWrapperMap; + DotOsgWrapperMap _shaderWrapperMap; + + DotOsgWrapperMap _classNameWrapperMap; + +}; + + +/** deprecated. */ +class OSGDB_EXPORT RegisterDotOsgWrapperProxy +{ + public: + + RegisterDotOsgWrapperProxy(osg::Object* proto, + const std::string& name, + const std::string& associates, + DotOsgWrapper::ReadFunc readFunc, + DotOsgWrapper::WriteFunc writeFunc, + DotOsgWrapper::ReadWriteMode readWriteMode=DotOsgWrapper::READ_AND_WRITE); + + ~RegisterDotOsgWrapperProxy(); + + protected: + osg::ref_ptr _wrapper; +}; + +/** deprecated. */ +template +class TemplateRegisterDotOsgWrapperProxy : public RegisterDotOsgWrapperProxy, public T +{ + public: + + TemplateRegisterDotOsgWrapperProxy(osg::Object* proto, + const std::string& name, + const std::string& associates, + DotOsgWrapper::ReadFunc readFunc, + DotOsgWrapper::WriteFunc writeFunc, + DotOsgWrapper::ReadWriteMode readWriteMode=DotOsgWrapper::READ_AND_WRITE): + RegisterDotOsgWrapperProxy(proto, name, associates, readFunc, writeFunc, readWriteMode) {} + +}; + + +#define REGISTER_DOTOSGWRAPPER(classname) \ + extern "C" void dotosgwrapper_##classname(void) {} \ + static osgDB::RegisterDotOsgWrapperProxy dotosgwrapper_proxy_##classname + +} + +#endif diff --git a/libs/include/android/osgDB/DynamicLibrary b/libs/include/android/osgDB/DynamicLibrary new file mode 100755 index 0000000..b700f36 --- /dev/null +++ b/libs/include/android/osgDB/DynamicLibrary @@ -0,0 +1,79 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGDB_DYNAMICLIBRARY +#define OSGDB_DYNAMICLIBRARY 1 + +#include +#include + +#include + + +namespace osgDB { + +/** DynamicLibrary - encapsulates the loading and unloading of dynamic libraries, + typically used for loading ReaderWriter plug-ins. +*/ +class OSGDB_EXPORT DynamicLibrary : public osg::Referenced +{ + public: + + typedef void* HANDLE; + typedef void* PROC_ADDRESS; + + /** returns a pointer to a DynamicLibrary object on successfully + * opening of library returns NULL on failure. + */ + static DynamicLibrary* loadLibrary(const std::string& libraryName); + + /** return name of library stripped of path.*/ + const std::string& getName() const { return _name; } + + /** return name of library including full path to it.*/ + const std::string& getFullName() const { return _fullName; } + + /** return handle to .dso/.dll dynamic library itself.*/ + HANDLE getHandle() const { return _handle; } + + /** return address of function located in library.*/ + PROC_ADDRESS getProcAddress(const std::string& procName); + + protected: + + /** get handle to library file */ + static HANDLE getLibraryHandle( const std::string& libraryName); + + /** disallow default constructor.*/ + DynamicLibrary():osg::Referenced() {} + /** disallow copy constructor.*/ + DynamicLibrary(const DynamicLibrary&):osg::Referenced() {} + /** disallow copy operator.*/ + DynamicLibrary& operator = (const DynamicLibrary&) { return *this; } + + /** Disallow public construction so that users have to go + * through loadLibrary() above which returns NULL on + * failure, a valid DynamicLibrary object on success. + */ + DynamicLibrary(const std::string& name,HANDLE handle); + ~DynamicLibrary(); + + HANDLE _handle; + std::string _name; + std::string _fullName; + +}; + +} + +#endif // __DYNAMIC_LIBRARY_H diff --git a/libs/include/android/osgDB/Export b/libs/include/android/osgDB/Export new file mode 100755 index 0000000..398a7fc --- /dev/null +++ b/libs/include/android/osgDB/Export @@ -0,0 +1,51 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGDB_EXPORT_ +#define OSGDB_EXPORT_ 1 + +#include + +#if defined(_MSC_VER) && defined(OSG_DISABLE_MSVC_WARNINGS) + #pragma warning( disable : 4244 ) + #pragma warning( disable : 4251 ) + #pragma warning( disable : 4267 ) + #pragma warning( disable : 4275 ) + #pragma warning( disable : 4290 ) + #pragma warning( disable : 4786 ) + #pragma warning( disable : 4305 ) + #pragma warning( disable : 4996 ) +#endif + +#if defined(_MSC_VER) || defined(__CYGWIN__) || defined(__MINGW32__) || defined( __BCPLUSPLUS__) || defined( __MWERKS__) + # if defined( OSG_LIBRARY_STATIC ) + # define OSGDB_EXPORT + # elif defined( OSGDB_LIBRARY ) + # define OSGDB_EXPORT __declspec(dllexport) + # else + # define OSGDB_EXPORT __declspec(dllimport) + # endif +#else + # define OSGDB_EXPORT +#endif + +/** + +\namespace osgDB + +The osgDB library provides support for reading and writing scene graphs, providing a plugin framework and file utility classes. +The plugin framework in centered around the osgDB::Registry, and allows plugins which provide specific file format support to be dynamically loaded on demand. +*/ + +#endif + diff --git a/libs/include/android/osgDB/ExternalFileWriter b/libs/include/android/osgDB/ExternalFileWriter new file mode 100755 index 0000000..86e37b1 --- /dev/null +++ b/libs/include/android/osgDB/ExternalFileWriter @@ -0,0 +1,106 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGDB_PLUGIN_IMAGE_WRITER +#define OSGDB_PLUGIN_IMAGE_WRITER 1 + +#include +#include +#include + +namespace osg +{ + class Object; +} + +namespace osgDB +{ + + class Options; + + /// Helper allowing 'intelligent' writing of external files (images, shaders, etc.), regarding to a main file (a scene), especially in plugins. + /// Goals are: + /// - Enable writing out objects only once (even if referenced multiple times) + /// - Handle duplicates (avoid writing two different objects at the same place, renaming files as needed) + /// - Handle directory creation when paths don't just exist + /// - Generate writing paths which may keep original directory structure (depending on user wishes). Ex: + /// Reading: model.osg and images/img1.jpg + /// Writing with 'keepRelativePaths': /somePath/newmodel.osg and /somePath/images/img1.jpg + /// Writing without 'keepRelativePaths': /somePath/newmodel.osg and /somePath/img1.jpg + ///\author Sukender + ///\todo Handling of naming constraints (such as "8.3" names in 3DS) + class OSGDB_EXPORT ExternalFileWriter + { + public: + /// Builds the helper class with all options. + ///\param srcDirectory Directory of the initial main file (if any), used as a base when relativising objects names. Not used if keepRelativePaths==false. + ///\param destDirectory Directory where to write the main file. + ///\param keepRelativePaths If true, then relative paths of source objects are kept if possible (ex: If an image is initially "imageDir/image.jpg" relatively to the source dir, then we'd like to get "destDir/imageDir/image.jpg"). If false, then only the simple file name is used to write the object file. + ///\param allowUpDirs When relativising objects paths, sets the maximum number of directories the objects can be written "up" the destination directory. Not used if keepRelativePaths==false. Examples: If an image is initially "../image.jpg" relatively to the source dir *AND* if we allow one dir level up, then we'd like to get "destDirParent/destDir/../image.jpg" (= "destDirParent/image.jpg"). If we *DO NOT* allow one dir level up, then we'd like to get "destDir/image.jpg". + ExternalFileWriter(const std::string & srcDirectory, const std::string & destDirectory, bool keepRelativePaths, unsigned int allowUpDirs=0); + + /// Short constructor used when not relativising objects paths, or when having no initial model file (which is pretty the same here). + ExternalFileWriter(const std::string & destDirectory); + + /// Writes the current object if not already done. + ///\param obj Object to write, using corresponding osgDB::write method. + ///\param options Writing options to pass to corresponding osgDB::write method. + ///\param [out] out_absolutePath Pointer to a string to be filled with absolute writing path, or NULL. + ///\param [out] out_relativePath Pointer to a string to be filled with write path relative to the destination directory if possible (absolute path if not), or NULL. + ///\return true on success, false otherwise. + bool write(const osg::Object & obj, const osgDB::Options * options, std::string * out_absolutePath=NULL, std::string * out_relativePath=NULL); + + struct ObjectData + { + ObjectData() : written(false) {} + ObjectData(const std::string & absolutePath, const std::string & relativePath, bool written) : absolutePath(absolutePath), relativePath(relativePath), written(written) {} + std::string absolutePath; + std::string relativePath; + bool written; ///< Says if write succeded or not. + }; + + /// Set of written objects, with their absolute writing path. + /// Objects being passed to the write() method but which have failed to be effectively written are also included. + typedef std::map ObjectsSet; + + /// Returns the written objects. + const ObjectsSet & getObjects() const { return _objects; } + + protected: + // Dev note: + // A multi-indexed structure would be more efficient for ObjectsSet (such as boost::multi_index, indexed on object pointer (unique), and hashed indexed on absolute path (unique)). + // In order to get a correct search time, SearchMap "replaces" the multi-index structure for hashed indexes on absolute paths. + typedef std::multimap SearchMap; + typedef unsigned int ObjectIndex; ///< Integer type used for indices of unnamed objects + ObjectsSet _objects; + SearchMap _searchMap; ///< Map used to search by absolute file path. + ObjectIndex _lastGeneratedObjectIndex; + const std::string _srcDirectory; + const std::string _destDirectory; + bool _keepRelativePaths; + const unsigned int _allowUpDirs; + + /// Generates a unique name for an object to be written on disk. + /// Side effect: updates _lastGeneratedObjectIndex to the index associated withe the returned name. + void generateObjectName(std::string & out_relativePath, std::string & out_absolutePath, int type); + + bool absoluteObjectPathExists(const std::string & path); + + private: + // Prevent copy + ExternalFileWriter & operator=(const ExternalFileWriter &); + ExternalFileWriter(const ExternalFileWriter &); + }; +} + +#endif // OSGDB_PLUGIN_IMAGE_WRITER diff --git a/libs/include/android/osgDB/FileCache b/libs/include/android/osgDB/FileCache new file mode 100755 index 0000000..cb14004 --- /dev/null +++ b/libs/include/android/osgDB/FileCache @@ -0,0 +1,77 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGDB_FILECACHE +#define OSGDB_FILECACHE 1 + +#include + +#include +#include + +#include + +namespace osgDB { + +class OSGDB_EXPORT FileCache : public osg::Referenced +{ + public: + + FileCache(const std::string& path); + + const std::string& getFileCachePath() const { return _fileCachePath; } + + virtual bool isFileAppropriateForFileCache(const std::string& originalFileName) const; + + virtual std::string createCacheFileName(const std::string& originalFileName) const; + + virtual bool existsInCache(const std::string& originalFileName) const; + + virtual ReaderWriter::ReadResult readImage(const std::string& originalFileName, const osgDB::Options* options) const; + virtual ReaderWriter::WriteResult writeImage(const osg::Image& image, const std::string& originalFileName, const osgDB::Options* options) const; + + virtual ReaderWriter::ReadResult readObject(const std::string& originalFileName, const osgDB::Options* options) const; + virtual ReaderWriter::WriteResult writeObject(const osg::Object& object, const std::string& originalFileName, const osgDB::Options* options) const; + + virtual ReaderWriter::ReadResult readHeightField(const std::string& originalFileName, const osgDB::Options* options) const; + virtual ReaderWriter::WriteResult writeHeightField(const osg::HeightField& hf, const std::string& originalFileName, const osgDB::Options* options) const; + + virtual ReaderWriter::ReadResult readNode(const std::string& originalFileName, const osgDB::Options* options, bool buildKdTreeIfRequired=true) const; + virtual ReaderWriter::WriteResult writeNode(const osg::Node& node, const std::string& originalFileName, const osgDB::Options* options) const; + + virtual ReaderWriter::ReadResult readShader(const std::string& originalFileName, const osgDB::Options* options) const; + virtual ReaderWriter::WriteResult writeShader(const osg::Shader& shader, const std::string& originalFileName, const osgDB::Options* options) const; + + bool loadDatabaseRevisionsForFile(const std::string& originanlFileName); + + typedef std::list< osg::ref_ptr > DatabaseRevisionsList; + DatabaseRevisionsList& getDatabaseRevisionsList() { return _databaseRevisionsList; } + + bool isCachedFileBlackListed(const std::string& originalFileName) const; + + protected: + + virtual ~FileCache(); + + std::string _fileCachePath; + + DatabaseRevisionsList _databaseRevisionsList; + + FileList* readFileList(const std::string& originalFileName) const; + bool removeFileFromBlackListed(const std::string& originalFileName) const; + +}; + +} + +#endif diff --git a/libs/include/android/osgDB/FileNameUtils b/libs/include/android/osgDB/FileNameUtils new file mode 100755 index 0000000..ed1e552 --- /dev/null +++ b/libs/include/android/osgDB/FileNameUtils @@ -0,0 +1,136 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGDB_FILENAMEUTILS +#define OSGDB_FILENAMEUTILS 1 + +#include + +#include +#include + +namespace osgDB { + +/** Gets the parent path from full name (Ex: /a/b/c.Ext => /a/b). */ +extern OSGDB_EXPORT std::string getFilePath(const std::string& filename); +/** Gets the extension without dot (Ex: /a/b/c.Ext => Ext). */ +extern OSGDB_EXPORT std::string getFileExtension(const std::string& filename); +/** Gets the extension including dot (Ex: /a/b/c.Ext => .Ext). */ +extern OSGDB_EXPORT std::string getFileExtensionIncludingDot(const std::string& filename); +/** Gets the lowercase extension without dot (Ex: /a/b/c.Ext => ext). */ +extern OSGDB_EXPORT std::string getLowerCaseFileExtension(const std::string& filename); +/** Gets file name with extension (Ex: /a/b/c.Ext => c.Ext). */ +extern OSGDB_EXPORT std::string getSimpleFileName(const std::string& fileName); +/** Gets file path without last extension (Ex: /a/b/c.Ext => /a/b/c ; file.ext1.ext2 => file.ext1). */ +extern OSGDB_EXPORT std::string getNameLessExtension(const std::string& fileName); +/** Gets file path without \b all extensions (Ex: /a/b/c.Ext => /a/b/c ; file.ext1.ext2 => file). */ +extern OSGDB_EXPORT std::string getNameLessAllExtensions(const std::string& fileName); +/** Gets file name without last extension (Ex: /a/b/c.Ext => c ; file.ext1.ext2 => file.ext1). */ +extern OSGDB_EXPORT std::string getStrippedName(const std::string& fileName); +/** If 'to' is in a subdirectory of 'from' then this function returns the subpath, otherwise it just returns the file name. + * The function does \b not automagically resolve paths as the system does, so be careful to give canonical paths. + * However, the function interprets slashes ('/') ans backslashes ('\') as they were equal. + */ +extern OSGDB_EXPORT std::string getPathRelative(const std::string& from, const std::string& to); +/** Gets root part of a path ("/" or "C:"), or an empty string if none found. */ +extern OSGDB_EXPORT std::string getPathRoot(const std::string& path); +/** Tests if path is absolute, as !getPathRoot(path).empty(). */ +extern OSGDB_EXPORT bool isAbsolutePath(const std::string& path); + + +/** Converts forward slashes (/) to back slashes (\). */ +extern OSGDB_EXPORT std::string convertFileNameToWindowsStyle(const std::string& fileName); +/** Converts back slashes (\) to forward slashes (/). */ +extern OSGDB_EXPORT std::string convertFileNameToUnixStyle(const std::string& fileName); +extern OSGDB_EXPORT std::string convertToLowerCase(const std::string& fileName); + +const char UNIX_PATH_SEPARATOR = '/'; +const char WINDOWS_PATH_SEPARATOR = '\\'; + +/** Get the path separator for the current platform. */ +extern OSGDB_EXPORT char getNativePathSeparator(); +/** Check if the path contains only the current platform's path separators. */ +extern OSGDB_EXPORT bool isFileNameNativeStyle(const std::string& fileName); +/** Convert the path to contain only the current platform's path separators. */ +extern OSGDB_EXPORT std::string convertFileNameToNativeStyle(const std::string& fileName); + +extern OSGDB_EXPORT bool equalCaseInsensitive(const std::string& lhs,const std::string& rhs); +extern OSGDB_EXPORT bool equalCaseInsensitive(const std::string& lhs,const char* rhs); + +extern OSGDB_EXPORT bool containsServerAddress(const std::string& filename); +extern OSGDB_EXPORT std::string getServerProtocol(const std::string& filename); +extern OSGDB_EXPORT std::string getServerAddress(const std::string& filename); +extern OSGDB_EXPORT std::string getServerFileName(const std::string& filename); + +/** Concatenates two paths */ +extern OSGDB_EXPORT std::string concatPaths(const std::string& left, const std::string& right); + +/** Removes .. and . dirs in a path */ +extern OSGDB_EXPORT std::string getRealPath(const std::string& path); + +/** Splits a path into elements between separators (including Windows' root, if any). */ +extern OSGDB_EXPORT void getPathElements(const std::string& path, std::vector & out_elements); + +/** Functor for helping sort filename in alphabetical and numerical order when using in conjunction with std::sort.*/ +struct FileNameComparator +{ + inline bool operator() (const std::string& lhs, const std::string& rhs) const + { + std::string::size_type size_lhs = lhs.size(); + std::string::size_type size_rhs = rhs.size(); + std::string::size_type pos_lhs = 0; + std::string::size_type pos_rhs = 0; + while(pos_lhs='0' && lhs[pos_lhs]<='9'; + bool numeric_rhs = rhs[pos_rhs]>='0' && rhs[pos_rhs]<='9'; + if (numeric_lhs && numeric_rhs) + { + std::string::size_type start_lhs = pos_lhs; + ++pos_lhs; + while(pos_lhs='0' && lhs[pos_lhs]<='9')) ++pos_lhs; + + std::string::size_type start_rhs = pos_rhs; + ++pos_rhs; + while(pos_rhs='0' && rhs[pos_rhs]<='9')) ++pos_rhs; + + if (pos_lhsrhs[start_rhs]) return false; + ++start_lhs; + ++start_rhs; + } + } + else + { + if (c_lhs + +#include +#include +#include +#include + +namespace osgDB { + +/** Overload of the standard fopen function. If OSG_USE_UTF8_FILENAME is defined, + * filename will be expanded from UTF8 to UTF16 and _wfopen will be called. */ +extern OSGDB_EXPORT FILE* fopen(const char* filename, const char* mode); + +/** Make a new directory. Returns true if directory exists or was created. */ +extern OSGDB_EXPORT bool makeDirectory( const std::string &directoryPath ); + +/** Make a new directory for a given file. */ +extern OSGDB_EXPORT bool makeDirectoryForFile( const std::string &filePath ); + +/** Get current working directory. */ +extern OSGDB_EXPORT std::string getCurrentWorkingDirectory( void ); + +/** Set current working directory. */ +extern OSGDB_EXPORT bool setCurrentWorkingDirectory( const std::string &newCurrentWorkingDirectory ); + + +/** return true if a file exists. */ +extern OSGDB_EXPORT bool fileExists(const std::string& filename); + +enum FileType +{ + FILE_NOT_FOUND, + REGULAR_FILE, + DIRECTORY +}; + +/** return type of file. */ +extern OSGDB_EXPORT FileType fileType(const std::string& filename); + +/** find specified file in specified file path.*/ +extern OSGDB_EXPORT std::string findFileInPath(const std::string& filename, const FilePathList& filePath,CaseSensitivity caseSensitivity=CASE_SENSITIVE); + +/** return the directory/filename of a file if its is contained within specified directory. + * return "" if directory does not contain file. If caseInsensitive is set to true then + * a case insensitive comparison is used to compare fileName to directory contents. + * This is useful when unix programs attempt read case insensitive windows filenames. + */ +extern OSGDB_EXPORT std::string findFileInDirectory(const std::string& fileName,const std::string& dirName,CaseSensitivity caseSensitivity=CASE_SENSITIVE); + +/** simple list of names to represent a directory's contents. */ +typedef std::vector DirectoryContents; + +/** Return the contents of a directory. + * Return value will contain filenames only, not absolute paths. + * Returns an empty array on any error.*/ +extern OSGDB_EXPORT DirectoryContents getDirectoryContents(const std::string& dirName); + +/** Return the contents of a directory, sorting the names into alphabetic and numberical order. + * Return value will contain filenames only, not absolute paths. + * Returns an empty array on any error.*/ +extern OSGDB_EXPORT DirectoryContents getSortedDirectoryContents(const std::string& dirName); + +/** Return the list of filenames that match the given filename with wildcards. + * Will only expand '*', and will not expand wildcards in directory, only in + * filename part of the given filename. + * Return value will contain path+filename so that if ever the above + * limitation (expanding wildcards in directory) is fixed, client code will + * still work unchanged. */ +extern OSGDB_EXPORT DirectoryContents expandWildcardsInFilename(const std::string& filename); + +namespace FileOpResult { + enum Value + { + OK, /**< Operation done. */ + SOURCE_EQUALS_DESTINATION, /**< Operation is useless (source == destination). */ + BAD_ARGUMENT, + SOURCE_MISSING, /**< Source file doesn't exist. */ + SOURCE_NOT_OPENED, /**< Error opening source file. */ + DESTINATION_NOT_OPENED, /**< Error opening destination file. */ + READ_ERROR, + WRITE_ERROR + }; +} + +/** Copy a file to another location, overwriting if necessary. + * You must provide full path for both source and destination. + * \return true on success, or if source and destination are the same. + * \todo Replace the implementation with filesystem functions from TR2 when available. +*/ +extern OSGDB_EXPORT FileOpResult::Value copyFile(const std::string & source, const std::string & destination); + + + +inline void setDataFilePathList(const FilePathList& filepath) { osgDB::Registry::instance()->setDataFilePathList(filepath); } + +inline void setDataFilePathList(const std::string& paths) { osgDB::Registry::instance()->setDataFilePathList(paths); } + +inline FilePathList& getDataFilePathList() { return osgDB::Registry::instance()->getDataFilePathList(); } + +/** Search for specified file in file system, checking the DataFilePathList for possible paths, + * returning the full path of the first valid file found, return an empty string if no string is found. + */ +extern OSGDB_EXPORT std::string findDataFile(const std::string& filename,CaseSensitivity caseSensitivity=CASE_SENSITIVE); + +/** Search for specified file in file system, checking first the database path set in the Options structure, then the DataFilePathList for possible paths, + * returning the full path of the first valid file found, return an empty string if no string is found. + */ +extern OSGDB_EXPORT std::string findDataFile(const std::string& filename,const Options* options, CaseSensitivity caseSensitivity=CASE_SENSITIVE); + +inline void setLibraryFilePathList(const FilePathList& filepaths) { osgDB::Registry::instance()->setLibraryFilePathList(filepaths); } + +inline void setLibraryFilePathList(const std::string& paths) { osgDB::Registry::instance()->setLibraryFilePathList(paths); } + +inline FilePathList& getLibraryFilePathList() { return osgDB::Registry::instance()->getLibraryFilePathList(); } + +extern OSGDB_EXPORT std::string findLibraryFile(const std::string& filename,CaseSensitivity caseSensitivity=CASE_SENSITIVE); + +/** convert a string containing a list of paths delimited either with ';' (Windows) or ':' (All other platforms) into FilePath representation.*/ +extern OSGDB_EXPORT void convertStringPathIntoFilePathList(const std::string& paths,FilePathList& filepath); + +/** Return true if FilePathList contains a filepath that is significies checking of the current working directory.*/ +extern OSGDB_EXPORT bool containsCurrentWorkingDirectoryReference(const FilePathList& paths); + +extern OSGDB_EXPORT void appendPlatformSpecificLibraryFilePaths(FilePathList& filepath); +extern OSGDB_EXPORT void appendPlatformSpecificResourceFilePaths(FilePathList& filepath); + +} // namespace osgDB + +#endif diff --git a/libs/include/android/osgDB/ImageOptions b/libs/include/android/osgDB/ImageOptions new file mode 100755 index 0000000..b545320 --- /dev/null +++ b/libs/include/android/osgDB/ImageOptions @@ -0,0 +1,149 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGDB_IMAGEOPTIONS +#define OSGDB_IMAGEOPTIONS 1 + +#include + +namespace osgDB { + +class OSGDB_EXPORT ImageOptions : public osgDB::Options +{ + public: + + ImageOptions(); + + ImageOptions(const std::string& str); + + ImageOptions(const ImageOptions& options,const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY): + osgDB::Options(options,copyop), + _sourceImageSamplingMode(options._sourceImageSamplingMode), + _sourceImageWindowMode(options._sourceImageWindowMode), + _sourceRatioWindow(options._sourceRatioWindow), + _sourcePixelWindow(options._sourcePixelWindow), + _destinationImage(options._destinationImage), + _destinationImageWindowMode(options._destinationImageWindowMode), + _destinationRatioWindow(options._destinationRatioWindow), + _destinationPixelWindow(options._destinationPixelWindow), + _destinationDataType(options._destinationDataType), + _destinationPixelFormat(options._destinationPixelFormat) {} + + + META_Object(osgDB,ImageOptions); + + /** RatioWindow stores the window (as ratios of 0.0 to 1.0) from the overall imagery from which to extract the osg::Image*/ + struct RatioWindow + { + RatioWindow(): + windowX(0.0), + windowY(0.0), + windowWidth(1.0), + windowHeight(1.0) {} + + void set(double x, double y, double w, double h) + { + windowX = x; + windowY = y; + windowWidth = w; + windowHeight = h; + } + + double windowX; + double windowY; + double windowWidth; + double windowHeight; + }; + + /** PixelWindow stores the window (in exact pixels) from the overall imagery from which to extract the osg::Image*/ + struct PixelWindow + { + PixelWindow(): + windowX(0), + windowY(0), + windowWidth(0), + windowHeight(0) {} + + void set(unsigned int x, unsigned int y, unsigned int w, unsigned int h) + { + windowX = x; + windowY = y; + windowWidth = w; + windowHeight = h; + } + + unsigned int windowX; + unsigned int windowY; + unsigned int windowWidth; + unsigned int windowHeight; + }; + + enum ImageWindowMode + { + ALL_IMAGE, + RATIO_WINDOW, + PIXEL_WINDOW + }; + + enum ImageSamplingMode + { + NEAREST, + LINEAR, + CUBIC + }; + + /** Used as UserData attached to generated osg::Image's*/ + struct TexCoordRange : public osg::Referenced + { + TexCoordRange(): + _x(0.0), + _y(0.0), + _w(1.0), + _h(1.0) {} + + void set(double x,double y, double w, double h) + { + _x = x; + _y = y; + _w = w; + _h = h; + } + + double _x,_y,_w,_h; + }; + + + // source + ImageSamplingMode _sourceImageSamplingMode; + ImageWindowMode _sourceImageWindowMode; + RatioWindow _sourceRatioWindow; + PixelWindow _sourcePixelWindow; + + // destination + osg::ref_ptr _destinationImage; + + ImageWindowMode _destinationImageWindowMode; + RatioWindow _destinationRatioWindow; + PixelWindow _destinationPixelWindow; + + GLenum _destinationDataType; + GLenum _destinationPixelFormat; + + void init(); + +}; + + +} + +#endif // OSGDB_IMAGEOPTIONS diff --git a/libs/include/android/osgDB/ImagePager b/libs/include/android/osgDB/ImagePager new file mode 100755 index 0000000..662f448 --- /dev/null +++ b/libs/include/android/osgDB/ImagePager @@ -0,0 +1,190 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGDB_IMAGEPAGER +#define OSGDB_IMAGEPAGER 1 + +#include +#include +#include +#include +#include + +#include +#include + +#include +#include + +namespace osgDB +{ + +class OSGDB_EXPORT ImagePager : public osg::NodeVisitor::ImageRequestHandler +{ + public: + + ImagePager(); + + class OSGDB_EXPORT ImageThread : public osg::Referenced, public OpenThreads::Thread + { + public: + + enum Mode + { + HANDLE_ALL_REQUESTS, + HANDLE_NON_HTTP, + HANDLE_ONLY_HTTP + }; + + ImageThread(ImagePager* pager, Mode mode, const std::string& name); + + ImageThread(const ImageThread& dt, ImagePager* pager); + + void setDone(bool done) { _done = done; } + bool getDone() const { return _done; } + + virtual int cancel(); + + virtual void run(); + + protected: + + virtual ~ImageThread(); + + bool _done; + Mode _mode; + ImagePager* _pager; + std::string _name; + }; + + + ImageThread* getImageThread(unsigned int i) { return _imageThreads[i].get(); } + + const ImageThread* getImageThread(unsigned int i) const { return _imageThreads[i].get(); } + + unsigned int getNumImageThreads() const { return static_cast(_imageThreads.size()); } + + + void setPreLoadTime(double preLoadTime) { _preLoadTime=preLoadTime; } + virtual double getPreLoadTime() const { return _preLoadTime; } + + virtual osg::Image* readImageFile(const std::string& fileName, const osg::Referenced* options=0); + + virtual void requestImageFile(const std::string& fileName, osg::Object* attachmentPoint, int attachmentIndex, double timeToMergeBy, const osg::FrameStamp* framestamp, osg::ref_ptr& imageRequest, const osg::Referenced* options); + + /** Return true if there are pending updates to the scene graph that require a call to updateSceneGraph(double). */ + virtual bool requiresUpdateSceneGraph() const; + + /** Merge the changes to the scene graph. */ + virtual void updateSceneGraph(const osg::FrameStamp &frameStamp); + + /** Signal the image thread that the update, cull and draw has begun for a new frame. + * Note, this is called by the application so that the image pager can go to sleep while the CPU is busy on the main rendering threads. */ + virtual void signalBeginFrame(const osg::FrameStamp* framestamp); + + /** Signal the image thread that the update, cull and draw dispatch has completed. + * Note, this is called by the application so that the image pager can go to wake back up now the main rendering threads are iddle waiting for the next frame.*/ + virtual void signalEndFrame(); + + int cancel(); + + protected: + + virtual ~ImagePager(); + // forward declare + struct RequestQueue; + + struct SortFileRequestFunctor; + friend struct SortFileRequestFunctor; + + struct ImageRequest : public osg::Referenced + { + ImageRequest(): + osg::Referenced(true), + _timeToMergeBy(0.0), + _attachmentIndex(-1) {} + + unsigned int _frameNumber; + double _timeToMergeBy; + std::string _fileName; + osg::ref_ptr _loadOptions; + osg::observer_ptr _attachmentPoint; + int _attachmentIndex; + osg::ref_ptr _loadedImage; + RequestQueue* _requestQueue; + osg::ref_ptr _readOptions; + + }; + + struct RequestQueue : public osg::Referenced + { + typedef std::vector< osg::ref_ptr > RequestList; + + void sort(); + + unsigned int size() const; + + RequestList _requestList; + mutable OpenThreads::Mutex _requestMutex; + }; + + + struct ReadQueue : public RequestQueue + { + ReadQueue(ImagePager* pager, const std::string& name); + + void block() { _block->block(); } + + void release() { _block->release(); } + + void updateBlock() + { + _block->set((!_requestList.empty() || !_pager->_databasePagerThreadPaused)); + } + + void clear(); + + void add(ImageRequest* imageRequest); + + void takeFirst(osg::ref_ptr& databaseRequest); + + osg::ref_ptr _block; + + ImagePager* _pager; + std::string _name; + }; + + OpenThreads::Mutex _run_mutex; + bool _startThreadCalled; + + bool _done; + bool _databasePagerThreadPaused; + + OpenThreads::Atomic _frameNumber; + + OpenThreads::Mutex _ir_mutex; + osg::ref_ptr _readQueue; + + typedef std::vector< osg::ref_ptr > ImageThreads; + ImageThreads _imageThreads; + + osg::ref_ptr _completedQueue; + + double _preLoadTime; +}; + + +} + +#endif + diff --git a/libs/include/android/osgDB/ImageProcessor b/libs/include/android/osgDB/ImageProcessor new file mode 100755 index 0000000..2ce823d --- /dev/null +++ b/libs/include/android/osgDB/ImageProcessor @@ -0,0 +1,54 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGDB_IMAGEPROCESSOR +#define OSGDB_IMAGEPROCESSOR 1 + +#include + +namespace osgDB { + +class ImageProcessor : public osg::Object +{ + public: + + ImageProcessor(): + osg::Object(true) {} + + ImageProcessor(const ImageProcessor& rw,const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY): + osg::Object(rw,copyop) {} + + virtual ~ImageProcessor() {} + + META_Object(osgDB,ImageProcessor); + + enum CompressionMethod + { + USE_CPU, /// Use CPU for compression even when GPU compression is available + USE_GPU /// Use GPU for compression when available (i.e CUDA), otherwise fallback to CPU + }; + + enum CompressionQuality + { + FASTEST, + NORMAL, + PRODUCTION, + HIGHEST + }; + + virtual void compress(osg::Image& /*image*/, osg::Texture::InternalFormatMode /*compressedFormat*/, bool /*generateMipMap*/, bool /*resizeToPowerOfTwo*/, CompressionMethod /*method*/, CompressionQuality /*quality*/) {} + virtual void generateMipMap(osg::Image& /*image*/, bool /*resizeToPowerOfTwo*/, CompressionMethod /*method*/) {} +}; + +} +#endif diff --git a/libs/include/android/osgDB/Input b/libs/include/android/osgDB/Input new file mode 100755 index 0000000..9605d31 --- /dev/null +++ b/libs/include/android/osgDB/Input @@ -0,0 +1,331 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGDB_INPUT +#define OSGDB_INPUT 1 + +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include + +namespace osgDB { + +/** basic structure for custom runtime inheritance checking */ +struct basic_type_wrapper { + virtual ~basic_type_wrapper() {} + virtual bool matches(const osg::Object *proto) const = 0; +}; + +/** a class template that checks inheritance between a given + Object's class and a class defined at compile time through + the template parameter T. + This is used in conjunction with readObjectOfType() to + specify an abstract class as reference type. +**/ +template +struct type_wrapper: basic_type_wrapper { + bool matches(const osg::Object *proto) const + { + return dynamic_cast(proto) != 0; + } +}; + +/** deprecated. */ +class OSGDB_EXPORT Field +{ + public: + + enum { + MIN_CACHE_SIZE = 256 + }; + + Field(); + Field(const Field& field); + virtual ~Field(); + + virtual Field& operator = (const Field& ic); + + void reset(); + void addChar(char c); + int getNoCharacters() const { return _fieldCacheSize; } + + void setWithinQuotes(bool withinQuotes=true); + bool getWithinQuotes(); + + void setNoNestedBrackets(int no); + int getNoNestedBrackets(); + + enum FieldType + { + OPEN_BRACKET, + CLOSE_BRACKET, + STRING, + WORD, + REAL, + INTEGER, + BLANK, + UNINITIALISED + }; + + FieldType getFieldType() const; + + bool isValid() const; + + bool isOpenBracket() const; + bool isCloseBracket() const; + + bool isWord() const; + bool matchWord(const char* str) const; + bool matchWord(const char* str,int noCharacters) const; + + bool isString() const; + bool matchString(const char* str) const; + bool matchString(const char* str,int noCharacters) const; + bool isQuotedString() const; + + const char* getStr() const; + char* takeStr(); + + bool isInt() const; + bool matchInt(int i) const; + bool getInt(int& i) const; + + bool isUInt() const; + bool matchUInt(unsigned int i) const; + bool getUInt(unsigned int& i) const; + + bool isFloat() const; + bool matchFloat(float f) const; + bool getFloat(float& f) const; + bool getFloat(double& f) const; + + static FieldType calculateFieldType(const char* str,bool withinQuotes=false); + + protected: + + void _init(); + void _free(); + void _copy(const Field& ic); + + int _fieldCacheCapacity; + int _fieldCacheSize; + char* _fieldCache; + + mutable FieldType _fieldType; + + bool _withinQuotes; + + int _noNestedBrackets; + +}; + +/** deprecated. */ +class OSGDB_EXPORT FieldReader +{ + public: + + FieldReader(); + FieldReader(const FieldReader& ic); + virtual ~FieldReader(); + + virtual FieldReader& operator = (const FieldReader& ic); + + void attach(std::istream* input); + void detach(); + + virtual bool eof() const; + + bool readField(Field& fieldPtr); + void ignoreField(); + + /** no of unmatched `{' encountered so far in file*/ + int getNoNestedBrackets() const; + + private: + + bool _readField(Field* fieldPtr); + + void _init(); + void _free(); + void _copy(const FieldReader& ic); + + std::istream* _fin; + bool _eof; + + bool findStartOfNextField(); + + int _noNestedBrackets; + + bool _delimiterEatLookUp[256]; + bool _delimiterKeepLookUp[256]; + +}; + +/** deprecated. */ +class OSGDB_EXPORT FieldReaderIterator +{ + public: + + enum { + MINIMUM_FIELD_READER_QUEUE_SIZE = 10 + }; + + FieldReaderIterator(); + FieldReaderIterator(const FieldReaderIterator& ic); + virtual ~FieldReaderIterator(); + + FieldReaderIterator& operator = (const FieldReaderIterator& ic); + + void attach(std::istream* input); + void detach(); + + virtual bool eof() const; + + FieldReader& getFieldReader() { return _reader; } + + void insert(int pos,Field* field); + void insert(int pos,const char* str); + + Field& operator [] (int pos); + Field& field (int pos); + + FieldReaderIterator& operator ++ (); + FieldReaderIterator& operator += (int no); + + /** increments the iterator of the next simple field or + * whole block if the current field[0] is an open bracket */ + void advanceOverCurrentFieldOrBlock(); + void advanceToEndOfCurrentBlock(); + void advanceToEndOfBlock(int noNestBrackets); + + bool matchSequence(const char* str); + + bool readSequence(const char* keyword,std::string& value); + bool readSequence(const char* keyword,unsigned int& value); + bool readSequence(const char* keyword,int& value); + bool readSequence(const char* keyword,float& value); + bool readSequence(const char* keyword,osg::Vec2f& value); + bool readSequence(const char* keyword,osg::Vec3f& value); + bool readSequence(const char* keyword,osg::Vec4f& value); + bool readSequence(const char* keyword,osg::Vec2d& value); + bool readSequence(const char* keyword,osg::Vec3d& value); + bool readSequence(const char* keyword,osg::Vec4d& value); + + bool readSequence(std::string& value); + bool readSequence(unsigned int& value); + bool readSequence(int& value); + bool readSequence(float& value); + bool readSequence(osg::Vec2f& value); + bool readSequence(osg::Vec3f& value); + bool readSequence(osg::Vec4f& value); + bool readSequence(osg::Vec2d& value); + bool readSequence(osg::Vec3d& value); + bool readSequence(osg::Vec4d& value); + + private: + + void _init(); + void _free(); + void _copy(const FieldReaderIterator& ic); + + FieldReader _reader; + + Field _blank; + + Field* _previousField; + + Field** _fieldQueue; + int _fieldQueueSize; + int _fieldQueueCapacity; + +}; + +/** deprecated. */ +class OSGDB_EXPORT Input : public FieldReaderIterator +{ + public: + + Input(); + virtual ~Input(); + + void setOptions(const Options* options) { _options = options; } + const Options* getOptions() const { return _options.get(); } + + virtual osg::Object* readObjectOfType(const osg::Object& compObj); + virtual osg::Object* readObjectOfType(const basic_type_wrapper &btw); + + + template + inline T* readObjectOfType() + { + return dynamic_cast(readObjectOfType(osgDB::type_wrapper())); + } + + virtual osg::Object* readObject(); + virtual osg::Image* readImage(); + virtual osg::Drawable* readDrawable(); + virtual osg::StateAttribute* readStateAttribute(); + virtual osg::Uniform* readUniform(); + virtual osg::Node* readNode(); + virtual osg::Shader* readShader(); + + virtual osg::Object* readObject(const std::string& fileName); + virtual osg::Image* readImage(const std::string& fileName); + virtual osg::Node* readNode(const std::string& fileName); + virtual osg::Shader* readShader(const std::string& fileName); + + virtual osg::Object* getObjectForUniqueID(const std::string& uniqueID); + virtual void registerUniqueIDForObject(const std::string& uniqueID,osg::Object* obj); + + typedef osg::ArgumentParser::Parameter Parameter; + + bool read(Parameter value1); + bool read(Parameter value1, Parameter value2); + bool read(Parameter value1, Parameter value2, Parameter value3); + bool read(Parameter value1, Parameter value2, Parameter value3, Parameter value4); + bool read(Parameter value1, Parameter value2, Parameter value3, Parameter value4, Parameter value5); + bool read(Parameter value1, Parameter value2, Parameter value3, Parameter value4, Parameter value5, Parameter value6); + bool read(Parameter value1, Parameter value2, Parameter value3, Parameter value4, Parameter value5, Parameter value6, Parameter value7); + bool read(Parameter value1, Parameter value2, Parameter value3, Parameter value4, Parameter value5, Parameter value6, Parameter value7, Parameter value8); + + bool read(const char* str); + bool read(const char* str, Parameter value1); + bool read(const char* str, Parameter value1, Parameter value2); + bool read(const char* str, Parameter value1, Parameter value2, Parameter value3); + bool read(const char* str, Parameter value1, Parameter value2, Parameter value3, Parameter value4); + bool read(const char* str, Parameter value1, Parameter value2, Parameter value3, Parameter value4, Parameter value5); + bool read(const char* str, Parameter value1, Parameter value2, Parameter value3, Parameter value4, Parameter value5, Parameter value6); + bool read(const char* str, Parameter value1, Parameter value2, Parameter value3, Parameter value4, Parameter value5, Parameter value6, Parameter value7); + bool read(const char* str, Parameter value1, Parameter value2, Parameter value3, Parameter value4, Parameter value5, Parameter value6, Parameter value7, Parameter value8); + + private: + + typedef std::map< std::string, osg::ref_ptr > UniqueIDToObjectMapping; + UniqueIDToObjectMapping _uniqueIDToObjectMap; + + osg::ref_ptr _options; + +}; + +} + +#endif // __SG_INPUT_H diff --git a/libs/include/android/osgDB/InputStream b/libs/include/android/osgDB/InputStream new file mode 100755 index 0000000..7eb714b --- /dev/null +++ b/libs/include/android/osgDB/InputStream @@ -0,0 +1,222 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2010 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +// Written by Wang Rui, (C) 2010 + +#ifndef OSGDB_INPUTSTREAM +#define OSGDB_INPUTSTREAM + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace osgDB +{ + +class InputException : public osg::Referenced +{ +public: + InputException( const std::vector& fields, const std::string& err ) : _error(err) + { + for ( unsigned int i=0; i > ArrayMap; + typedef std::map< unsigned int, osg::ref_ptr > IdentifierMap; + + enum ReadType + { + READ_UNKNOWN = 0, + READ_SCENE, + READ_IMAGE, + READ_OBJECT + }; + + InputStream( const osgDB::Options* options ); + virtual ~InputStream(); + + void setFileVersion( const std::string& d, int v ) { _domainVersionMap[d] = v; } + int getFileVersion( const std::string& d=std::string() ) const; + + bool isBinary() const { return _in->isBinary(); } + const osgDB::Options* getOptions() const { return _options.get(); } + + // Serialization related functions + InputStream& operator>>( bool& b ) { _in->readBool(b); checkStream(); return *this; } + InputStream& operator>>( char& c ) { _in->readChar(c); checkStream(); return *this; } + InputStream& operator>>( signed char& c ) { _in->readSChar(c); checkStream(); return *this; } + InputStream& operator>>( unsigned char& c ) { _in->readUChar(c); checkStream(); return *this; } + InputStream& operator>>( short& s ) { _in->readShort(s); checkStream(); return *this; } + InputStream& operator>>( unsigned short& s ) { _in->readUShort(s); checkStream(); return *this; } + InputStream& operator>>( int& i ) { _in->readInt(i); checkStream(); return *this; } + InputStream& operator>>( unsigned int& i ) { _in->readUInt(i); checkStream(); return *this; } + InputStream& operator>>( long& l ) { _in->readLong(l); checkStream(); return *this; } + InputStream& operator>>( unsigned long& l ) { _in->readULong(l); checkStream(); return *this; } + InputStream& operator>>( float& f ) { _in->readFloat(f); checkStream(); return *this; } + InputStream& operator>>( double& d ) { _in->readDouble(d); checkStream(); return *this; } + InputStream& operator>>( std::string& s ) { _in->readString(s); checkStream(); return *this; } + InputStream& operator>>( std::istream& (*fn)(std::istream&) ) { _in->readStream(fn); checkStream(); return *this; } + InputStream& operator>>( std::ios_base& (*fn)(std::ios_base&) ) { _in->readBase(fn); checkStream(); return *this; } + + InputStream& operator>>( ObjectGLenum& value ) { _in->readGLenum(value); checkStream(); return *this; } + InputStream& operator>>( ObjectProperty& prop ) { _in->readProperty(prop); checkStream(); return *this; } + InputStream& operator>>( ObjectMark& mark ) { _in->readMark(mark); checkStream(); return *this; } + + InputStream& operator>>( osg::Vec2b& v ); + InputStream& operator>>( osg::Vec3b& v ); + InputStream& operator>>( osg::Vec4b& v ); + InputStream& operator>>( osg::Vec2ub& v ); + InputStream& operator>>( osg::Vec3ub& v ); + InputStream& operator>>( osg::Vec4ub& v ); + InputStream& operator>>( osg::Vec2s& v ); + InputStream& operator>>( osg::Vec3s& v ); + InputStream& operator>>( osg::Vec4s& v ); + InputStream& operator>>( osg::Vec2us& v ); + InputStream& operator>>( osg::Vec3us& v ); + InputStream& operator>>( osg::Vec4us& v ); + InputStream& operator>>( osg::Vec2i& v ); + InputStream& operator>>( osg::Vec3i& v ); + InputStream& operator>>( osg::Vec4i& v ); + InputStream& operator>>( osg::Vec2ui& v ); + InputStream& operator>>( osg::Vec3ui& v ); + InputStream& operator>>( osg::Vec4ui& v ); + InputStream& operator>>( osg::Vec2f& v ); + InputStream& operator>>( osg::Vec3f& v ); + InputStream& operator>>( osg::Vec4f& v ); + InputStream& operator>>( osg::Vec2d& v ); + InputStream& operator>>( osg::Vec3d& v ); + InputStream& operator>>( osg::Vec4d& v ); + InputStream& operator>>( osg::Quat& q ); + InputStream& operator>>( osg::Plane& p ); + InputStream& operator>>( osg::Matrixf& mat ); + InputStream& operator>>( osg::Matrixd& mat ); + + InputStream& operator>>( osg::Array*& a ) { a = readArray(); return *this; } + InputStream& operator>>( osg::Image*& img ) { img = readImage(); return *this; } + InputStream& operator>>( osg::PrimitiveSet*& p ) { p = readPrimitiveSet(); return *this; } + InputStream& operator>>( osg::Object*& obj ) { obj = readObject(); return *this; } + + InputStream& operator>>( osg::ref_ptr& ptr ) { ptr = readArray(); return *this; } + InputStream& operator>>( osg::ref_ptr& ptr ) { ptr = readImage(); return *this; } + InputStream& operator>>( osg::ref_ptr& ptr ) { ptr = readPrimitiveSet(); return *this; } + + template InputStream& operator>>( osg::ref_ptr& ptr ) + { ptr = static_cast(readObject()); return *this; } + + // Convenient methods for reading + bool matchString( const std::string& str ) { return _in->matchString(str); } + void advanceToCurrentEndBracket() { _in->advanceToCurrentEndBracket(); } + void readWrappedString( std::string& str ) { _in->readWrappedString(str); checkStream(); } + void readCharArray( char* s, unsigned int size ) { _in->readCharArray(s, size); } + void readComponentArray( char* s, unsigned int numElements, unsigned int numComponentsPerElements, unsigned int componentSizeInBytes) { _in->readComponentArray( s, numElements, numComponentsPerElements, componentSizeInBytes); } + + // readSize() use unsigned int for all sizes. + unsigned int readSize() { unsigned int size; *this>>size; return size; } + + // Global reading functions + osg::Array* readArray(); + osg::PrimitiveSet* readPrimitiveSet(); + osg::Image* readImage(bool readFromExternal=true); + osg::Object* readObject( osg::Object* existingObj=0 ); + osg::Object* readObjectFields( const std::string& className, unsigned int id, osg::Object* existingObj=0); + + /// set an input iterator, used directly when not using InputStream with a traditional file releated stream. + void setInputIterator( InputIterator* ii ) { _in = ii; } + + /// start reading from InputStream treating it as a traditional file releated stream, handles headers and versioning + ReadType start( InputIterator* ); + + void decompress(); + + // Schema handlers + void readSchema( std::istream& fin ); + void resetSchema(); + + // Exception handlers + inline void throwException( const std::string& msg ); + const InputException* getException() const { return _exception.get(); } + + // Property & mask variables + ObjectProperty PROPERTY; + ObjectMark BEGIN_BRACKET; + ObjectMark END_BRACKET; + +protected: + inline void checkStream(); + void setWrapperSchema( const std::string& name, const std::string& properties ); + + template + void readArrayImplementation( T* a, unsigned int numComponentsPerElements, unsigned int componentSizeInBytes ); + + ArrayMap _arrayMap; + IdentifierMap _identifierMap; + + typedef std::map VersionMap; + VersionMap _domainVersionMap; + int _fileVersion; + bool _useSchemaData; + bool _forceReadingImage; + std::vector _fields; + osg::ref_ptr _in; + osg::ref_ptr _exception; + osg::ref_ptr _options; + + // store here to avoid a new and a leak in InputStream::decompress + std::stringstream* _dataDecompress; +}; + +void InputStream::throwException( const std::string& msg ) +{ + _exception = new InputException(_fields, msg); +} + +void InputStream::checkStream() +{ + _in->checkStream(); + if ( _in->isFailed() ) + throwException( "InputStream: Failed to read from stream." ); +} + +} + +#endif diff --git a/libs/include/android/osgDB/ObjectWrapper b/libs/include/android/osgDB/ObjectWrapper new file mode 100755 index 0000000..d43c5aa --- /dev/null +++ b/libs/include/android/osgDB/ObjectWrapper @@ -0,0 +1,233 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2010 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +// Written by Wang Rui, (C) 2010 + +#ifndef OSGDB_OBJECTWRAPPER +#define OSGDB_OBJECTWRAPPER + +#include + +namespace osgDB +{ + +typedef std::vector StringList; +extern OSGDB_EXPORT void split( const std::string& src, StringList& list, char separator=' ' ); + +class OSGDB_EXPORT BaseCompressor : public osg::Referenced +{ +public: + BaseCompressor() {} + void setName( const std::string& name ) { _name = name; } + const std::string& getName() const { return _name; } + + virtual bool compress( std::ostream&, const std::string& ) = 0; + virtual bool decompress( std::istream&, std::string& ) = 0; + +protected: + std::string _name; +}; + +struct FinishedObjectReadCallback : public osg::Referenced +{ + virtual void objectRead(osgDB::InputStream& is, osg::Object& obj) = 0; +}; + +class OSGDB_EXPORT ObjectWrapper : public osg::Referenced +{ +public: + typedef std::vector< osg::ref_ptr > SerializerList; + typedef std::vector< osg::ref_ptr > FinishedObjectReadCallbackList; + + ObjectWrapper( osg::Object* proto, const std::string& name, + const std::string& associates ); + ObjectWrapper( osg::Object* proto, const std::string& domain, const std::string& name, + const std::string& associates ); + + void setUpdatedVersion( int ver ) { _version = ver; } + int getUpdatedVersion() const { return _version; } + + const osg::Object* getProto() const { return _proto.get(); } + const std::string& getName() const { return _name; } + const StringList& getAssociates() const { return _associates; } + + void addSerializer( BaseSerializer* s, BaseSerializer::Type t=BaseSerializer::RW_UNDEFINED ); + void markSerializerAsRemoved( const std::string& name ); + BaseSerializer* getSerializer( const std::string& name ); + void addFinishedObjectReadCallback ( FinishedObjectReadCallback* forc) { _finishedObjectReadCallbacks.push_back(forc); } + + bool read( InputStream&, osg::Object& ); + bool write( OutputStream&, const osg::Object& ); + + bool readSchema( const StringList& properties, const std::vector& types ); + void writeSchema( StringList& properties, std::vector& types ); + void resetSchema() + { if ( _backupSerializers.size()>0 ) _serializers = _backupSerializers; } + +protected: + ObjectWrapper() : _version(0) {} + virtual ~ObjectWrapper() {} + + osg::ref_ptr _proto; + std::string _domain; + std::string _name; + StringList _associates; + SerializerList _serializers; + SerializerList _backupSerializers; + std::vector _typeList; + FinishedObjectReadCallbackList _finishedObjectReadCallbacks; + int _version; // Last updated version of the wrapper +}; + +struct UpdateWrapperVersionProxy +{ + UpdateWrapperVersionProxy( ObjectWrapper* w, int v ): _wrapper(w) + { + _lastVersion = w->getUpdatedVersion(); + w->setUpdatedVersion(v); + } + + ~UpdateWrapperVersionProxy() + { + _wrapper->setUpdatedVersion(_lastVersion); + } + + ObjectWrapper* _wrapper; + int _lastVersion; +}; + +class Registry; + +class OSGDB_EXPORT ObjectWrapperManager : public osg::Referenced +{ +public: + + // Wrapper handlers + void addWrapper( ObjectWrapper* wrapper ); + void removeWrapper( ObjectWrapper* wrapper ); + ObjectWrapper* findWrapper( const std::string& name ); + + typedef std::map< std::string, osg::ref_ptr > WrapperMap; + WrapperMap& getWrapperMap() { return _wrappers; } + const WrapperMap& getWrapperMap() const { return _wrappers; } + + // Compressor handlers + void addCompressor( BaseCompressor* compressor ); + void removeCompressor( BaseCompressor* compressor ); + BaseCompressor* findCompressor( const std::string& name ); + + typedef std::map< std::string, osg::ref_ptr > CompressorMap; + CompressorMap& getCompressorMap() { return _compressors; } + const CompressorMap& getCompressorMap() const { return _compressors; } + + typedef std::map IntLookupMap; + IntLookup::Value getValue( const std::string& group, const std::string& str ) { return findLookup(group).getValue(str.c_str()); } + const std::string& getString( const std::string& group, IntLookup::Value value ) { return findLookup(group).getString(value); } + +protected: + + friend class osgDB::Registry; + + ObjectWrapperManager(); + virtual ~ObjectWrapperManager(); + + WrapperMap _wrappers; + CompressorMap _compressors; + + IntLookup& findLookup( const std::string& group ) + { + IntLookupMap::iterator itr = _globalMap.find(group); + if ( itr!=_globalMap.end() ) return itr->second; + else return _globalMap["GL"]; + } + + IntLookupMap _globalMap; +}; + + +class OSGDB_EXPORT RegisterWrapperProxy +{ +public: + typedef void (*AddPropFunc)( ObjectWrapper* ); + + RegisterWrapperProxy( osg::Object* proto, const std::string& name, + const std::string& associates, AddPropFunc func ); + + virtual ~RegisterWrapperProxy(); + +protected: + osg::ref_ptr _wrapper; +}; + +class OSGDB_EXPORT RegisterCustomWrapperProxy +{ +public: + typedef void (*AddPropFunc)( const char*, ObjectWrapper* ); + + RegisterCustomWrapperProxy( osg::Object* proto, const std::string& domain, const std::string& name, + const std::string& associates, AddPropFunc func ); + + virtual ~RegisterCustomWrapperProxy(); + +protected: + osg::ref_ptr _wrapper; +}; + +#define REGISTER_OBJECT_WRAPPER(NAME, PROTO, CLASS, ASSOCIATES) \ + extern "C" void wrapper_serializer_##NAME(void) {} \ + extern void wrapper_propfunc_##NAME(osgDB::ObjectWrapper*); \ + static osgDB::RegisterWrapperProxy wrapper_proxy_##NAME( \ + PROTO, #CLASS, ASSOCIATES, &wrapper_propfunc_##NAME); \ + typedef CLASS MyClass; \ + void wrapper_propfunc_##NAME(osgDB::ObjectWrapper* wrapper) + +#define REGISTER_OBJECT_WRAPPER2(NAME, PROTO, CLASS, CLASSNAME, ASSOCIATES) \ + extern "C" void wrapper_serializer_##NAME(void) {} \ + extern void wrapper_propfunc_##NAME(osgDB::ObjectWrapper*); \ + static osgDB::RegisterWrapperProxy wrapper_proxy_##NAME( \ + PROTO, CLASSNAME, ASSOCIATES, &wrapper_propfunc_##NAME); \ + typedef CLASS MyClass; \ + void wrapper_propfunc_##NAME(osgDB::ObjectWrapper* wrapper) + +#define REGISTER_CUSTOM_OBJECT_WRAPPER(DOMAIN, NAME, PROTO, CLASS, ASSOCIATES) \ + extern "C" void wrapper_serializer_##NAME(void) {} \ + extern void wrapper_propfunc_##NAME(const char*, osgDB::ObjectWrapper*); \ + static osgDB::RegisterCustomWrapperProxy wrapper_proxy_##NAME( \ + PROTO, #DOMAIN, #CLASS, ASSOCIATES, &wrapper_propfunc_##NAME); \ + typedef CLASS MyClass; \ + void wrapper_propfunc_##NAME(const char* domain, osgDB::ObjectWrapper* wrapper) + +#define REGISTER_CUSTOM_OBJECT_WRAPPER2(DOMAIN, NAME, PROTO, CLASS, CLASSNAME, ASSOCIATES) \ + extern "C" void wrapper_serializer_##NAME(void) {} \ + extern void wrapper_propfunc_##NAME(const char*, osgDB::ObjectWrapper*); \ + static osgDB::RegisterCustomWrapperProxy wrapper_proxy_##NAME( \ + PROTO, #DOMAIN, CLASSNAME, ASSOCIATES, &wrapper_propfunc_##NAME); \ + typedef CLASS MyClass; \ + void wrapper_propfunc_##NAME(const char* domain, osgDB::ObjectWrapper* wrapper) + +class OSGDB_EXPORT RegisterCompressorProxy +{ +public: + RegisterCompressorProxy( const std::string& name, BaseCompressor* compressor ); + ~RegisterCompressorProxy(); + +protected: + osg::ref_ptr _compressor; +}; + +#define REGISTER_COMPRESSOR(NAME, CLASS) \ + extern "C" void wrapper_compressor_##CLASS(void) {} \ + static osgDB::RegisterCompressorProxy compressor_proxy_##CLASS(NAME, new CLASS); + +} + +#endif diff --git a/libs/include/android/osgDB/Options b/libs/include/android/osgDB/Options new file mode 100755 index 0000000..5ed4ace --- /dev/null +++ b/libs/include/android/osgDB/Options @@ -0,0 +1,273 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGDB_OPTIONS +#define OSGDB_OPTIONS 1 + +#include +#include + +#include +#include +#include + +namespace osgDB { + + +/** Options base class used for passing options into plugins to control their operation.*/ +class OSGDB_EXPORT Options : public osg::Object +{ + public: + + /// bit mask for setting up which object types get cached by readObject/Image/HeightField/Node(filename) calls + enum CacheHintOptions + { /// do not cache objects of any type + CACHE_NONE = 0, + + /// cache nodes loaded via readNode(filename) + CACHE_NODES = 1<<0, + + /// cache images loaded via readImage(filename) + CACHE_IMAGES = 1<<1, + + /// cache heightfield loaded via readHeightField(filename) + CACHE_HEIGHTFIELDS = 1<<2, + + /// cache heightfield loaded via readHeightField(filename) + CACHE_ARCHIVES = 1<<3, + + /// cache objects loaded via readObject(filename) + CACHE_OBJECTS = 1<<4, + + /// cache shaders loaded via readShader(filename) + CACHE_SHADERS = 1<<5, + + /// cache on all read*(filename) calls + CACHE_ALL = CACHE_NODES | + CACHE_IMAGES | + CACHE_HEIGHTFIELDS | + CACHE_ARCHIVES | + CACHE_OBJECTS | + CACHE_SHADERS + }; + + /// Bit mask for which geometry attributes should be imported with double precision where source data is held in double precision + /// This is useful for data that will be pre-processed before rendering. + /// In general the geometry should be converted to floating point before rendering to ensure good performance. + enum PrecisionHint + { + FLOAT_PRECISION_ALL = 0, + + DOUBLE_PRECISION_VERTEX = 1<<0, + DOUBLE_PRECISION_NORMAL = 1<<1, + DOUBLE_PRECISION_COLOR = 1<<2, + DOUBLE_PRECISION_SECONDARY_COLOR = 1<<3, + DOUBLE_PRECISION_FOG_COORD = 1<<4, + DOUBLE_PRECISION_TEX_COORD = 1<<5, + DOUBLE_PRECISION_VERTEX_ATTRIB = 1<<6, + + DOUBLE_PRECISION_ALL = DOUBLE_PRECISION_VERTEX | + DOUBLE_PRECISION_NORMAL | + DOUBLE_PRECISION_COLOR | + DOUBLE_PRECISION_SECONDARY_COLOR | + DOUBLE_PRECISION_FOG_COORD | + DOUBLE_PRECISION_TEX_COORD | + DOUBLE_PRECISION_VERTEX_ATTRIB + }; + + /// range of options of whether to build kdtrees automatically on loading + enum BuildKdTreesHint + { + NO_PREFERENCE, + DO_NOT_BUILD_KDTREES, + BUILD_KDTREES + }; + + + Options(): + osg::Object(true), + _objectCacheHint(CACHE_ARCHIVES), + _precisionHint(FLOAT_PRECISION_ALL), + _buildKdTreesHint(NO_PREFERENCE) {} + + Options(const std::string& str): + osg::Object(true), + _str(str), + _objectCacheHint(CACHE_ARCHIVES), + _precisionHint(FLOAT_PRECISION_ALL), + _buildKdTreesHint(NO_PREFERENCE) + { + parsePluginStringData(str); + } + + Options(const Options& options,const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY); + + META_Object(osgDB,Options); + + Options* cloneOptions(const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY) const { return static_cast(clone(copyop)); } + + /** Set the general Options string.*/ + void setOptionString(const std::string& str) { _str = str; parsePluginStringData(str); } + + /** Get the general Options string.*/ + const std::string& getOptionString() const { return _str; } + + /** Set the database path to use a hint of where to look when loading models.*/ + void setDatabasePath(const std::string& str) { _databasePaths.clear(); _databasePaths.push_back(str); } + + /** Get the database path which is used a hint of where to look when loading models.*/ + FilePathList& getDatabasePathList() { return _databasePaths; } + + /** Get the const database path which is used a hint of where to look when loading models.*/ + const FilePathList& getDatabasePathList() const { return _databasePaths; } + + + /** Set whether the Registry::ObjectCache should be used by default.*/ + void setObjectCacheHint(CacheHintOptions useObjectCache) { _objectCacheHint = useObjectCache; } + + /** Get whether the Registry::ObjectCache should be used by default.*/ + CacheHintOptions getObjectCacheHint() const { return _objectCacheHint; } + + /** Set which geometry attributes plugins should import at double precision. */ + void setPrecisionHint(PrecisionHint hint) { _precisionHint = hint; } + + /** Get which geometry attributes plugins should import at double precision. */ + PrecisionHint getPrecisionHint() const { return _precisionHint; } + + /** Set whether the KdTrees should be built for geometry in the loader model. */ + void setBuildKdTreesHint(BuildKdTreesHint hint) { _buildKdTreesHint = hint; } + + /** Get whether the KdTrees should be built for geometry in the loader model. */ + BuildKdTreesHint getBuildKdTreesHint() const { return _buildKdTreesHint; } + + + /** Set the password map to be used by plugins when access files from secure locations.*/ + void setAuthenticationMap(AuthenticationMap* authenticationMap) { _authenticationMap = authenticationMap; } + + /** Get the password map to be used by plugins when access files from secure locations.*/ + const AuthenticationMap* getAuthenticationMap() const { return _authenticationMap.get(); } + + + /** Sets a plugindata value PluginData with a string */ + void setPluginData(const std::string& s, void* v) const { _pluginData[s] = v; } + + /** Get a value from the PluginData */ + void* getPluginData(const std::string& s) { return _pluginData[s]; } + + /** Get a value from the PluginData */ + const void* getPluginData(const std::string& s) const + { + PluginDataMap::const_iterator itr = _pluginData.find(s); + return (itr == _pluginData.end()) ? 0 : itr->second; + } + + /** Remove a value from the PluginData */ + void removePluginData(const std::string& s) const { _pluginData.erase(s); } + + /** Get number of PluginData values */ + unsigned int getNumPluginData() const { return static_cast(_pluginData.size()); } + + + /** Sets a plugindata value PluginData with a string */ + void setPluginStringData(const std::string& s, const std::string& v) const { _pluginStringData[s] = v; } + + /** Get a string from the PluginStrData */ + std::string& getPluginStringData(const std::string& s) { return _pluginStringData[s]; } + + /** Get a value from the PluginData */ + const std::string getPluginStringData(const std::string& s) const + { + PluginStringDataMap::const_iterator itr = _pluginStringData.find(s); + return (itr == _pluginStringData.end()) ? std::string("") : itr->second; + } + + /** Remove a value from the PluginData */ + void removePluginStringData(const std::string& s) const { _pluginStringData.erase(s); } + + /** Get number of PluginStrData values */ + unsigned int getNumPluginStringData() const { return static_cast(_pluginStringData.size()); } + + /** Parse string into plugin string data. This will be automatically done in Options(const std::string&) */ + void parsePluginStringData(const std::string& str, char separator1=' ', char separator2='='); + + + /** Set the find callback to use in place of the default findFile calls.*/ + void setFindFileCallback( FindFileCallback* cb) { _findFileCallback = cb; } + + /** Get the const findFile callback.*/ + FindFileCallback* getFindFileCallback() const { return _findFileCallback.get(); } + + + /** Set the read callback to use in place of the default readFile calls.*/ + void setReadFileCallback( ReadFileCallback* cb) { _readFileCallback = cb; } + + /** Get the const readFile callback.*/ + ReadFileCallback* getReadFileCallback() const { return _readFileCallback.get(); } + + + /** Set the callback to use in place of the default writeFile calls.*/ + void setWriteFileCallback( WriteFileCallback* cb) { _writeFileCallback = cb; } + + /** Get the const writeFile callback.*/ + WriteFileCallback* getWriteFileCallback() const { return _writeFileCallback.get(); } + + + /** Set the callback to use inform the DatabasePager whether a file is located on local or remote file system.*/ + void setFileLocationCallback( FileLocationCallback* cb) { _fileLocationCallback = cb; } + + /** Get the callback to use inform the DatabasePager whether a file is located on local or remote file system.*/ + FileLocationCallback* getFileLocationCallback() const { return _fileLocationCallback.get(); } + + /** Set the FileCache that is used to manage local storage of files downloaded from the internet.*/ + void setFileCache(FileCache* fileCache) { _fileCache = fileCache; } + + /** Get the FileCache that is used to manage local storage of files downloaded from the internet.*/ + FileCache* getFileCache() const { return _fileCache.get(); } + + + /** Set the terrain observer_ptr, use to decorate any osgTerrain subgraphs.*/ + void setTerrain(osg::observer_ptr& terrain) { _terrain = terrain; } + + /** Get the terrain observer_ptr, use to decorate any osgTerrain subgraphs.*/ + const osg::observer_ptr& getTerrain() const { return _terrain; } + + + protected: + + virtual ~Options() {} + + std::string _str; + FilePathList _databasePaths; + CacheHintOptions _objectCacheHint; + PrecisionHint _precisionHint; + BuildKdTreesHint _buildKdTreesHint; + osg::ref_ptr _authenticationMap; + + typedef std::map PluginDataMap; + mutable PluginDataMap _pluginData; + typedef std::map PluginStringDataMap; + mutable PluginStringDataMap _pluginStringData; + + osg::ref_ptr _findFileCallback; + osg::ref_ptr _readFileCallback; + osg::ref_ptr _writeFileCallback; + osg::ref_ptr _fileLocationCallback; + + osg::ref_ptr _fileCache; + + osg::observer_ptr _terrain; +}; + +} + +#endif // OSGDB_OPTIONS diff --git a/libs/include/android/osgDB/Output b/libs/include/android/osgDB/Output new file mode 100755 index 0000000..316d073 --- /dev/null +++ b/libs/include/android/osgDB/Output @@ -0,0 +1,141 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGDB_OUTPUT +#define OSGDB_OUTPUT 1 + +#include + +#include +#include + +#include +#include + +namespace osgDB { + +/** deprecated. */ +class OSGDB_EXPORT Output : public osgDB::ofstream +{ + public: + + Output(); + Output(const char* name); + + virtual ~Output(); + + + void setOptions(const Options* options); + const Options* getOptions() const { return _options.get(); } + + void setWriteOutDefaultValues(bool flag) { _writeOutDefaultValues = flag; } + bool getWriteOutDefaultValues() const { return _writeOutDefaultValues; } + + void open(const char *name); + + // comment out temporarily to avoid compilation problems, RO Jan 2002. + // void open(const char *name,int mode); + + Output& indent(); + + /** wrap a string with "" quotes and use \" for any internal quotes.*/ + std::string wrapString(const char* str); + + /** wrap a string with "" quotes and use \" for any internal quotes.*/ + std::string wrapString(const std::string& str); + + inline void setIndentStep(int step) { _indentStep = step; } + inline int getIndentStep() const { return _indentStep; } + + inline void setIndent(int indent) { _indent = indent; } + inline int getIndent() const { return _indent; } + + inline void setNumIndicesPerLine(int num) { _numIndicesPerLine = num; } + inline int getNumIndicesPerLine() const { return _numIndicesPerLine; } + + void moveIn(); + void moveOut(); + + virtual bool writeObject(const osg::Object& obj); + virtual void writeBeginObject(const std::string& name); + virtual void writeEndObject(); + virtual void writeUseID(const std::string& id); + virtual void writeUniqueID(const std::string& id); + + bool getUniqueIDForObject(const osg::Object* obj,std::string& uniqueID); + bool createUniqueIDForObject(const osg::Object* obj,std::string& uniqueID); + bool registerUniqueIDForObject(const osg::Object* obj,std::string& uniqueID); + + enum PathNameHint + { + AS_IS, + FULL_PATH, + RELATIVE_PATH, + FILENAME_ONLY + }; + + inline void setPathNameHint(const PathNameHint pnh) { _pathNameHint = pnh; } + inline PathNameHint getPathNameHint() const { return _pathNameHint; } + + virtual std::string getFileNameForOutput(const std::string& filename) const; + const std::string& getFileName() const { return _filename; } + + // Set and get if export texture files during write + void setOutputTextureFiles(bool flag) { _outputTextureFiles = flag; } + bool getOutputTextureFiles() const { return _outputTextureFiles; } + + // support code for OutputTextureFiles + virtual std::string getTextureFileNameForOutput(); + + void setOutputShaderFiles(bool flag) { _outputShaderFiles = flag; } + bool getOutputShaderFiles() const { return _outputShaderFiles; } + + virtual std::string getShaderFileNameForOutput(); + + void setExternalFileWritten(const std::string& filename, bool hasBeenWritten=true); + bool getExternalFileWritten(const std::string& filename) const; + + protected: + + + virtual void init(); + + osg::ref_ptr _options; + + int _indent; + int _indentStep; + + int _numIndicesPerLine; + + typedef std::map UniqueIDToLabelMapping; + UniqueIDToLabelMapping _objectToUniqueIDMap; + + std::string _filename; + + PathNameHint _pathNameHint; + + bool _outputTextureFiles; + unsigned int _textureFileNameNumber; + + bool _outputShaderFiles; + unsigned int _shaderFileNameNumber; + + bool _writeOutDefaultValues; + + typedef std::map ExternalFileWrittenMap; + ExternalFileWrittenMap _externalFileWritten; +}; + +} + +#endif // __SG_OUTPUT_H diff --git a/libs/include/android/osgDB/OutputStream b/libs/include/android/osgDB/OutputStream new file mode 100755 index 0000000..88d5184 --- /dev/null +++ b/libs/include/android/osgDB/OutputStream @@ -0,0 +1,221 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2010 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +// Written by Wang Rui, (C) 2010 + +#ifndef OSGDB_OUTPUTSTREAM +#define OSGDB_OUTPUTSTREAM + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace osgDB +{ + +class OutputException : public osg::Referenced +{ +public: + OutputException( const std::vector& fields, const std::string& err ) : _error(err) + { + for ( unsigned int i=0; i ArrayMap; + typedef std::map ObjectMap; + + enum WriteType + { + WRITE_UNKNOWN = 0, + WRITE_SCENE, + WRITE_IMAGE, + WRITE_OBJECT + }; + + enum WriteImageHint + { + WRITE_USE_IMAGE_HINT = 0, /*!< Use image hint, write inline data or use external */ + WRITE_USE_EXTERNAL, /*!< Use external file on disk and write only the filename */ + WRITE_INLINE_DATA, /*!< Write Image::data() to stream */ + WRITE_INLINE_FILE, /*!< Write the image file itself to stream */ + WRITE_EXTERNAL_FILE /*!< Write Image::data() to disk and use it as external file */ + }; + + OutputStream( const osgDB::Options* options ); + virtual ~OutputStream(); + + void setFileVersion( const std::string& d, int v ) { _domainVersionMap[d] = v; } + int getFileVersion( const std::string& d=std::string() ) const; + + bool isBinary() const { return _out->isBinary(); } + const std::string& getSchemaName() const { return _schemaName; } + const osgDB::Options* getOptions() const { return _options.get(); } + + void setWriteImageHint( WriteImageHint hint ) { _writeImageHint = hint; } + WriteImageHint getWriteImageHint() const { return _writeImageHint; } + + // Serialization related functions + OutputStream& operator<<( bool b ) { _out->writeBool(b); return *this; } + OutputStream& operator<<( char c ) { _out->writeChar(c); return *this; } + OutputStream& operator<<( signed char c) { _out->writeChar(c); return *this; } + OutputStream& operator<<( unsigned char c ) { _out->writeUChar(c); return *this; } + OutputStream& operator<<( short s ) { _out->writeShort(s); return *this; } + OutputStream& operator<<( unsigned short s ) { _out->writeUShort(s); return *this; } + OutputStream& operator<<( int i ) { _out->writeInt(i); return *this; } + OutputStream& operator<<( unsigned int i ) { _out->writeUInt(i); return *this; } + OutputStream& operator<<( long l ) { _out->writeLong(l); return *this; } + OutputStream& operator<<( unsigned long l ) { _out->writeULong(l); return *this; } + OutputStream& operator<<( float f ) { _out->writeFloat(f); return *this; } + OutputStream& operator<<( double d ) { _out->writeDouble(d); return *this; } + OutputStream& operator<<( const std::string& s ) { _out->writeString(s); return *this; } + OutputStream& operator<<( const char* s ) { _out->writeString(s); return *this; } + OutputStream& operator<<( std::ostream& (*fn)(std::ostream&) ) { _out->writeStream(fn); return *this; } + OutputStream& operator<<( std::ios_base& (*fn)(std::ios_base&) ) { _out->writeBase(fn); return *this; } + + OutputStream& operator<<( const ObjectGLenum& value ) { _out->writeGLenum(value); return *this; } + OutputStream& operator<<( const ObjectProperty& prop ) { _out->writeProperty(prop); return *this; } + OutputStream& operator<<( const ObjectMark& mark ) { _out->writeMark(mark); return *this; } + + OutputStream& operator<<( const osg::Vec2b& v ); + OutputStream& operator<<( const osg::Vec3b& v ); + OutputStream& operator<<( const osg::Vec4b& v ); + OutputStream& operator<<( const osg::Vec2ub& v ); + OutputStream& operator<<( const osg::Vec3ub& v ); + OutputStream& operator<<( const osg::Vec4ub& v ); + OutputStream& operator<<( const osg::Vec2s& v ); + OutputStream& operator<<( const osg::Vec3s& v ); + OutputStream& operator<<( const osg::Vec4s& v ); + OutputStream& operator<<( const osg::Vec2us& v ); + OutputStream& operator<<( const osg::Vec3us& v ); + OutputStream& operator<<( const osg::Vec4us& v ); + OutputStream& operator<<( const osg::Vec2i& v ); + OutputStream& operator<<( const osg::Vec3i& v ); + OutputStream& operator<<( const osg::Vec4i& v ); + OutputStream& operator<<( const osg::Vec2ui& v ); + OutputStream& operator<<( const osg::Vec3ui& v ); + OutputStream& operator<<( const osg::Vec4ui& v ); + OutputStream& operator<<( const osg::Vec2f& v ); + OutputStream& operator<<( const osg::Vec3f& v ); + OutputStream& operator<<( const osg::Vec4f& v ); + OutputStream& operator<<( const osg::Vec2d& v ); + OutputStream& operator<<( const osg::Vec3d& v ); + OutputStream& operator<<( const osg::Vec4d& v ); + OutputStream& operator<<( const osg::Quat& q ); + OutputStream& operator<<( const osg::Plane& p ); + OutputStream& operator<<( const osg::Matrixf& mat ); + OutputStream& operator<<( const osg::Matrixd& mat ); + + OutputStream& operator<<( const osg::Array* a ) { writeArray(a); return *this; } + OutputStream& operator<<( const osg::Image* img ) { writeImage(img); return *this; } + OutputStream& operator<<( const osg::PrimitiveSet* p ) { writePrimitiveSet(p); return *this; } + OutputStream& operator<<( const osg::Object* obj ) { writeObject(obj); return *this; } + + OutputStream& operator<<( const osg::ref_ptr& ptr ) { writeArray(ptr.get()); return *this; } + OutputStream& operator<<( const osg::ref_ptr& ptr ) { writeImage(ptr.get()); return *this; } + OutputStream& operator<<( const osg::ref_ptr& ptr ) { writePrimitiveSet(ptr.get()); return *this; } + + template OutputStream& operator<<( const osg::ref_ptr& ptr ) + { writeObject(ptr.get()); return *this; } + + // Convenient methods for writing + void writeWrappedString( const std::string& str ) { _out->writeWrappedString(str); } + void writeCharArray( const char* s, unsigned int size ) { _out->writeCharArray(s, size); } + + // method for converting all data structure sizes to unsigned int to ensure architecture portability. + template + void writeSize(T size) { *this<(size); } + + // Global writing functions + void writeArray( const osg::Array* a ); + void writePrimitiveSet( const osg::PrimitiveSet* p ); + void writeImage( const osg::Image* img ); + void writeObject( const osg::Object* obj ); + void writeObjectFields( const osg::Object* obj ); + + /// set an output iterator, used directly when not using OutputStream with a traditional file releated stream. + void setOutputIterator( OutputIterator* oi ) { _out = oi; } + + /// start writing to OutputStream treating it as a traditional file releated stream, handles headers and versioning + void start( OutputIterator* outIterator, WriteType type ); + + void compress( std::ostream* ostream ); + + // Schema handlers + void writeSchema( std::ostream& fout ); + + // Exception handlers + inline void throwException( const std::string& msg ); + const OutputException* getException() const { return _exception.get(); } + + // Property & mask variables + ObjectProperty PROPERTY; + ObjectMark BEGIN_BRACKET; + ObjectMark END_BRACKET; + +protected: + template + void writeArrayImplementation( const T*, int write_size, unsigned int numInRow=1 ); + + unsigned int findOrCreateArrayID( const osg::Array* array, bool& newID ); + unsigned int findOrCreateObjectID( const osg::Object* obj, bool& newID ); + + ArrayMap _arrayMap; + ObjectMap _objectMap; + + typedef std::map VersionMap; + VersionMap _domainVersionMap; + WriteImageHint _writeImageHint; + bool _useSchemaData; + bool _useRobustBinaryFormat; + + typedef std::map SchemaMap; + SchemaMap _inbuiltSchemaMap; + std::vector _fields; + std::string _schemaName; + std::string _compressorName; + std::stringstream _compressSource; + osg::ref_ptr _out; + osg::ref_ptr _exception; + osg::ref_ptr _options; +}; + +void OutputStream::throwException( const std::string& msg ) +{ + _exception = new OutputException(_fields, msg); +} + +} + +#endif diff --git a/libs/include/android/osgDB/ParameterOutput b/libs/include/android/osgDB/ParameterOutput new file mode 100755 index 0000000..0653c86 --- /dev/null +++ b/libs/include/android/osgDB/ParameterOutput @@ -0,0 +1,186 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGDB_PARAMETEROUTPUT +#define OSGDB_PARAMETEROUTPUT 1 + +#include + +namespace osgDB { + +class ParameterOutput +{ + public: + + ParameterOutput(Output& fw): + _fw(fw), + _numItemsPerLine(fw.getNumIndicesPerLine()), + _column(0) {} + + ParameterOutput(Output& fw,int numItemsPerLine): + _fw(fw), + _numItemsPerLine(numItemsPerLine), + _column(0) {} + + void begin() + { + _fw.indent() << "{"< + void write(const T& t) + { + if (_column==0) _fw.indent(); + + _fw << t; + + ++_column; + if (_column==_numItemsPerLine) + { + _fw << std::endl; + _column = 0; + } + else + { + _fw << " "; + } + + } + + template + void write(Iterator first, Iterator last) + { + for(Iterator itr=first; + itr!=last; + ++itr) + { + write(*itr); + } + + } + + template + void writeAsInts(Iterator first, Iterator last) + { + for(Iterator itr=first; + itr!=last; + ++itr) + { + write((int)*itr); + } + + } + + + protected: + + ParameterOutput& operator = (const ParameterOutput&) { return *this; } + + Output& _fw; + int _numItemsPerLine; + int _column; +}; + + +template +void writeArray(Output& fw, Iterator first, Iterator last,int noItemsPerLine=0) +{ + if (noItemsPerLine==0) noItemsPerLine=fw.getNumIndicesPerLine(); + + fw.indent() << "{"< +void writeArrayAsInts(Output& fw, Iterator first, Iterator last,int noItemsPerLine=0) +{ + if (noItemsPerLine==0) noItemsPerLine=fw.getNumIndicesPerLine(); + + fw.indent() << "{"< +#include + +#include +#include + +#include +#include + +namespace osgDB +{ + +typedef std::list FileNameList; + +FileNameList OSGDB_EXPORT listAllAvailablePlugins(); + +class ReaderWriterInfo : public osg::Referenced +{ + public: + + ReaderWriterInfo() {} + + std::string plugin; + std::string description; + ReaderWriter::FormatDescriptionMap protocols; + ReaderWriter::FormatDescriptionMap extensions; + ReaderWriter::FormatDescriptionMap options; + ReaderWriter::Features features; + + protected: + + virtual ~ReaderWriterInfo() {} +}; + +typedef std::list< osg::ref_ptr > ReaderWriterInfoList; + +bool OSGDB_EXPORT queryPlugin(const std::string& fileName, ReaderWriterInfoList& infoList); + +bool OSGDB_EXPORT outputPluginDetails(std::ostream& out, const std::string& fileName); + +} + +#endif diff --git a/libs/include/android/osgDB/ReadFile b/libs/include/android/osgDB/ReadFile new file mode 100755 index 0000000..0b9298a --- /dev/null +++ b/libs/include/android/osgDB/ReadFile @@ -0,0 +1,300 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGDB_READFILE +#define OSGDB_READFILE 1 + +#include + +#include +#include +#include + +#include +#include + +namespace osgDB { + + +/** Read an osg::Object from file. + * Return valid osg::Object on success, + * return NULL on failure. + * Use the Options object to control cache operations and file search paths in osgDB::Registry. + * The osgDB::Registry is used to load the appropriate ReaderWriter plugin + * for the filename extension, and this plugin then handles the request + * to read the specified file.*/ +extern OSGDB_EXPORT osg::Object* readObjectFile(const std::string& filename,const Options* options); + +/** Read an osg::Object from file. + * Return valid osg::Object on success, + * return NULL on failure. + * The osgDB::Registry is used to load the appropriate ReaderWriter plugin + * for the filename extension, and this plugin then handles the request + * to read the specified file.*/ +inline osg::Object* readObjectFile(const std::string& filename) +{ + return readObjectFile(filename, Registry::instance()->getOptions()); +} + +template +inline T* readFile(const std::string& filename, const Options* options) +{ + osg::ref_ptr object = readObjectFile(filename, options); + osg::ref_ptr t = dynamic_cast(object.get()); + object = 0; + return t.release(); +} + +template +inline T* readFile(const std::string& filename) +{ + return readFile(filename, Registry::instance()->getOptions()); +} + + +/** Read an osg::Image from file. + * Return valid osg::Image on success, + * return NULL on failure. + * Use the Options object to control cache operations and file search paths in osgDB::Registry. + * The osgDB::Registry is used to load the appropriate ReaderWriter plugin + * for the filename extension, and this plugin then handles the request + * to read the specified file.*/ +extern OSGDB_EXPORT osg::Image* readImageFile(const std::string& filename,const Options* options); + +/** Read an osg::Image from file. + * Return valid osg::Image on success, + * return NULL on failure. + * The osgDB::Registry is used to load the appropriate ReaderWriter plugin + * for the filename extension, and this plugin then handles the request + * to read the specified file.*/ +inline osg::Image* readImageFile(const std::string& filename) +{ + return readImageFile(filename,Registry::instance()->getOptions()); +} + +/** Read an osg::HeightField from file. + * Return valid osg::HeightField on success, + * return NULL on failure. + * Use the Options object to control cache operations and file search paths in osgDB::Registry. + * The osgDB::Registry is used to load the appropriate ReaderWriter plugin + * for the filename extension, and this plugin then handles the request + * to read the specified file.*/ +extern OSGDB_EXPORT osg::HeightField* readHeightFieldFile(const std::string& filename,const Options* options); + +/** Read an osg::HeightField from file. + * Return valid osg::HeightField on success, + * return NULL on failure. + * The osgDB::Registry is used to load the appropriate ReaderWriter plugin + * for the filename extension, and this plugin then handles the request + * to read the specified file.*/ +inline osg::HeightField* readHeightFieldFile(const std::string& filename) +{ + return readHeightFieldFile(filename,Registry::instance()->getOptions()); +} + +/** Read an osg::Node from file. + * Return valid osg::Node on success, + * return NULL on failure. + * Use the Options object to control cache operations and file search paths in osgDB::Registry. + * The osgDB::Registry is used to load the appropriate ReaderWriter plugin + * for the filename extension, and this plugin then handles the request + * to read the specified file.*/ +extern OSGDB_EXPORT osg::Node* readNodeFile(const std::string& filename,const Options* options); + +/** Read an osg::Node from file. + * Return valid osg::Node on success, + * return NULL on failure. + * The osgDB::Registry is used to load the appropriate ReaderWriter plugin + * for the filename extension, and this plugin then handles the request + * to read the specified file.*/ +inline osg::Node* readNodeFile(const std::string& filename) +{ + return readNodeFile(filename,Registry::instance()->getOptions()); +} + + +/** Read an osg::Node subgraph from files, creating a osg::Group to contain the nodes if more + * than one subgraph has been loaded. + * Use the Options object to control cache operations and file search paths in osgDB::Registry. + * Does NOT ignore strings beginning with a dash '-' character. */ +extern OSGDB_EXPORT osg::Node* readNodeFiles(std::vector& fileList,const Options* options); + +/** Read an osg::Node subgraph from files, creating a osg::Group to contain the nodes if more + * than one subgraph has been loaded.*/ +inline osg::Node* readNodeFiles(std::vector& fileList) +{ + return readNodeFiles(fileList,Registry::instance()->getOptions()); +} + + +/** Read an osg::Node subgraph from files, creating a osg::Group to contain the nodes if more + * than one subgraph has been loaded. + * Use the Options object to control cache operations and file search paths in osgDB::Registry.*/ +extern OSGDB_EXPORT osg::Node* readNodeFiles(osg::ArgumentParser& parser,const Options* options); + +/** Read an osg::Node subgraph from files, creating a osg::Group to contain the nodes if more + * than one subgraph has been loaded.*/ +inline osg::Node* readNodeFiles(osg::ArgumentParser& parser) +{ + return readNodeFiles(parser,Registry::instance()->getOptions()); +} + +/** Read an osg::Shader from file. + * Return valid osg::Shader on success, + * return NULL on failure. + * Use the Options object to control cache operations and file search paths in osgDB::Registry. + * The osgDB::Registry is used to load the appropriate ReaderWriter plugin + * for the filename extension, and this plugin then handles the request + * to read the specified file.*/ +extern OSGDB_EXPORT osg::Shader* readShaderFile(const std::string& filename,const Options* options); + +/** Read an osg::Shader from file. + * Return valid osg::Shader on success, + * return NULL on failure. + * The osgDB::Registry is used to load the appropriate ReaderWriter plugin + * for the filename extension, and this plugin then handles the request + * to read the specified file.*/ +inline osg::Shader* readShaderFile(const std::string& filename) +{ + return readShaderFile(filename,Registry::instance()->getOptions()); +} + +/** Read an osg::Shader from file and set to specified shader type. + * Return valid osg::Shader on success, + * return NULL on failure. + * Use the Options object to control cache operations and file search paths in osgDB::Registry. + * The osgDB::Registry is used to load the appropriate ReaderWriter plugin + * for the filename extension, and this plugin then handles the request + * to read the specified file.*/ +inline osg::Shader* readShaderFile(osg::Shader::Type type, const std::string& filename,const Options* options) +{ + osg::Shader* shader = readShaderFile(filename, options); + if (shader && type != osg::Shader::UNDEFINED) shader->setType(type); + return shader; +} + +/** Read an osg::Shader from file and set to specified shader type + * Return valid osg::Shader on success, + * return NULL on failure. + * The osgDB::Registry is used to load the appropriate ReaderWriter plugin + * for the filename extension, and this plugin then handles the request + * to read the specified file.*/ +inline osg::Shader* readShaderFile(osg::Shader::Type type, const std::string& filename) +{ + return readShaderFile(type, filename,Registry::instance()->getOptions()); +} + +/** Read an osg::Object from file. + * Return an assigned osg::ref_ptr on success, + * return an osg::ref_ptr with a NULL pointer assigned to it on failure. + * Use the Options object to control cache operations and file search paths in osgDB::Registry. + * The osgDB::Registry is used to load the appropriate ReaderWriter plugin + * for the filename extension, and this plugin then handles the request + * to read the specified file.*/ +extern OSGDB_EXPORT osg::ref_ptr readRefObjectFile(const std::string& filename,const Options* options); + +/** Read an osg::Object from file. + * Return an assigned osg::ref_ptr on success, + * return an osg::ref_ptr with a NULL pointer assigned to it on failure. + * The osgDB::Registry is used to load the appropriate ReaderWriter plugin + * for the filename extension, and this plugin then handles the request + * to read the specified file.*/ +inline osg::ref_ptr readRefObjectFile(const std::string& filename) +{ + return readRefObjectFile(filename,Registry::instance()->getOptions()); +} + +/** Read an osg::Image from file. + * Return an assigned osg::ref_ptr on success, + * return an osg::ref_ptr with a NULL pointer assigned to it on failure. + * Use the Options object to control cache operations and file search paths in osgDB::Registry. + * The osgDB::Registry is used to load the appropriate ReaderWriter plugin + * for the filename extension, and this plugin then handles the request + * to read the specified file.*/ +extern OSGDB_EXPORT osg::ref_ptr readRefImageFile(const std::string& filename,const Options* options); + +/** Read an osg::Image from file. + * Return an assigned osg::ref_ptr on success, + * return an osg::ref_ptr with a NULL pointer assigned to it on failure. + * The osgDB::Registry is used to load the appropriate ReaderWriter plugin + * for the filename extension, and this plugin then handles the request + * to read the specified file.*/ +inline osg::ref_ptr readRefImageFile(const std::string& filename) +{ + return readRefImageFile(filename,Registry::instance()->getOptions()); +} + +/** Read an osg::HeightField from file. + * Return an assigned osg::ref_ptr on success, + * return an osg::ref_ptr with a NULL pointer assigned to it on failure. + * Use the Options object to control cache operations and file search paths in osgDB::Registry. + * The osgDB::Registry is used to load the appropriate ReaderWriter plugin + * for the filename extension, and this plugin then handles the request + * to read the specified file.*/ +extern OSGDB_EXPORT osg::ref_ptr readRefHeightFieldFile(const std::string& filename,const Options* options); + +/** Read an osg::HeightField from file. + * Return an assigned osg::ref_ptr on success, + * return an osg::ref_ptr with a NULL pointer assigned to it on failure. + * The osgDB::Registry is used to load the appropriate ReaderWriter plugin + * for the filename extension, and this plugin then handles the request + * to read the specified file.*/ +inline osg::ref_ptr readRefHeightFieldFile(const std::string& filename) +{ + return readRefHeightFieldFile(filename,Registry::instance()->getOptions()); +} + +/** Read an osg::Node from file. + * Return an assigned osg::ref_ptr on success, + * return an osg::ref_ptr with a NULL pointer assigned to it on failure. + * Use the Options object to control cache operations and file search paths in osgDB::Registry. + * The osgDB::Registry is used to load the appropriate ReaderWriter plugin + * for the filename extension, and this plugin then handles the request + * to read the specified file.*/ +extern OSGDB_EXPORT osg::ref_ptr readRefNodeFile(const std::string& filename,const Options* options); + +/** Read an osg::Node from file. + * Return an assigned osg::ref_ptr on success, + * return an osg::ref_ptr with a NULL pointer assigned to it on failure. + * The osgDB::Registry is used to load the appropriate ReaderWriter plugin + * for the filename extension, and this plugin then handles the request + * to read the specified file.*/ +inline osg::ref_ptr readRefNodeFile(const std::string& filename) +{ + return readRefNodeFile(filename,Registry::instance()->getOptions()); +} + +/** Read an osg::Shader from file. + * Return an assigned osg::ref_ptr on success, + * return an osg::ref_ptr with a NULL pointer assigned to it on failure. + * Use the Options object to control cache operations and file search paths in osgDB::Registry. + * The osgDB::Registry is used to load the appropriate ReaderWriter plugin + * for the filename extension, and this plugin then handles the request + * to read the specified file.*/ +extern OSGDB_EXPORT osg::ref_ptr readRefShaderFile(const std::string& filename,const Options* options); + +/** Read an osg::Shader from file. + * Return an assigned osg::ref_ptr on success, + * return an osg::ref_ptr with a NULL pointer assigned to it on failure. + * The osgDB::Registry is used to load the appropriate ReaderWriter plugin + * for the filename extension, and this plugin then handles the request + * to read the specified file.*/ +inline osg::ref_ptr readRefShaderFile(const std::string& filename) +{ + return readRefShaderFile(filename,Registry::instance()->getOptions()); +} + + +} + +#endif diff --git a/libs/include/android/osgDB/ReaderWriter b/libs/include/android/osgDB/ReaderWriter new file mode 100755 index 0000000..46c98be --- /dev/null +++ b/libs/include/android/osgDB/ReaderWriter @@ -0,0 +1,272 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGDB_READERWRITER +#define OSGDB_READERWRITER 1 + +#include +#include +#include + +#include + +#include +#include +#include + +namespace osgDB { + +class Archive; + +/** List of directories to search through which searching for files. */ +typedef std::deque FilePathList; + +// forward declare +class Options; + +/** Pure virtual base class for reading and writing of non native formats. */ +class OSGDB_EXPORT ReaderWriter : public osg::Object +{ + public: + + + ReaderWriter(): + osg::Object(true) {} + + ReaderWriter(const ReaderWriter& rw,const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY): + osg::Object(rw,copyop) {} + + virtual ~ReaderWriter(); + + META_Object(osgDB,ReaderWriter); + + typedef std::map FormatDescriptionMap; + typedef std::list FeatureList; + + /** Return which protocols are supported by ReaderWriter. */ + virtual const FormatDescriptionMap& supportedProtocols() const { return _supportedProtocols; } + + /** Return which list of file extensions supported by ReaderWriter. */ + virtual const FormatDescriptionMap& supportedExtensions() const { return _supportedExtensions; } + + /** Return which list of file extensions supported by ReaderWriter. */ + virtual const FormatDescriptionMap& supportedOptions() const { return _supportedOptions; } + + /** Return true if ReaderWriter accepts specified file extension.*/ + virtual bool acceptsExtension(const std::string& /*extension*/) const; + + virtual bool acceptsProtocol(const std::string& protocol) const; + + /// Bit mask for setting up which feature types are available for read and/or write + enum Features + { + FEATURE_NONE = 0, + FEATURE_READ_OBJECT = 1<<0, + FEATURE_READ_IMAGE = 1<<1, + FEATURE_READ_HEIGHT_FIELD = 1<<2, + FEATURE_READ_NODE = 1<<3, + FEATURE_READ_SHADER = 1<<4, + FEATURE_WRITE_OBJECT = 1<<5, + FEATURE_WRITE_IMAGE = 1<<6, + FEATURE_WRITE_HEIGHT_FIELD = 1<<7, + FEATURE_WRITE_NODE = 1<<8, + FEATURE_WRITE_SHADER = 1<<9, + FEATURE_ALL = FEATURE_READ_OBJECT | + FEATURE_READ_IMAGE | + FEATURE_READ_HEIGHT_FIELD | + FEATURE_READ_NODE | + FEATURE_READ_SHADER | + FEATURE_WRITE_OBJECT | + FEATURE_WRITE_IMAGE | + FEATURE_WRITE_HEIGHT_FIELD | + FEATURE_WRITE_NODE | + FEATURE_WRITE_SHADER + }; + /** Return available features*/ + virtual Features supportedFeatures() const; + + /** Return feature as string */ + static FeatureList featureAsString(Features feature); + + + + class OSGDB_EXPORT ReadResult + { + public: + + enum ReadStatus + { + NOT_IMPLEMENTED, //!< read*() method not implemented in concrete ReaderWriter. + FILE_NOT_HANDLED, //!< File is not appropriate for this file reader, due to some incompatibility, but *not* a read error. + FILE_NOT_FOUND, //!< File could not be found or could not be read. + ERROR_IN_READING_FILE, //!< File found, loaded, but an error was encountered during processing. + FILE_LOADED, //!< File successfully found, loaded, and converted into osg. + FILE_LOADED_FROM_CACHE, //!< File found in cache and returned. + FILE_REQUESTED, //!< Asynchronous file read has been requested, but returning immediately, keep polling plugin until file read has been completed. + INSUFFICIENT_MEMORY_TO_LOAD //!< File found but not loaded because estimated required memory surpasses available memory. + }; + + ReadResult(ReadStatus status=FILE_NOT_HANDLED):_status(status) {} + ReadResult(const std::string& m):_status(ERROR_IN_READING_FILE),_message(m) {} + ReadResult(osg::Object* obj, ReadStatus status=FILE_LOADED):_status(status),_object(obj) {} + + ReadResult(const ReadResult& rr):_status(rr._status),_message(rr._message),_object(rr._object) {} + ReadResult& operator = (const ReadResult& rr) { if (this==&rr) return *this; _status=rr._status; _message=rr._message;_object=rr._object; return *this; } + + bool operator < (const ReadResult& rhs) const { return _status < rhs._status; } + + osg::Object* getObject(); + osg::Image* getImage(); + osg::HeightField* getHeightField(); + osg::Node* getNode(); + osgDB::Archive* getArchive(); + osg::Shader* getShader(); + + bool validObject() { return _object.valid(); } + bool validImage() { return getImage()!=0; } + bool validHeightField() { return getHeightField()!=0; } + bool validNode() { return getNode()!=0; } + bool validArchive() { return getArchive()!=0; } + bool validShader() { return getShader()!=0; } + + osg::Object* takeObject(); + osg::Image* takeImage(); + osg::HeightField* takeHeightField(); + osg::Node* takeNode(); + osgDB::Archive* takeArchive(); + osg::Shader* takeShader(); + + std::string& message() { return _message; } + const std::string& message() const { return _message; } + + ReadStatus status() const { return _status; } + bool success() const { return _status==FILE_LOADED || _status==FILE_LOADED_FROM_CACHE ; } + bool loadedFromCache() const { return _status==FILE_LOADED_FROM_CACHE; } + bool error() const { return _status==ERROR_IN_READING_FILE; } + bool notHandled() const { return _status==FILE_NOT_HANDLED || _status==NOT_IMPLEMENTED; } + bool notFound() const { return _status==FILE_NOT_FOUND; } + bool notEnoughMemory() const { return _status==INSUFFICIENT_MEMORY_TO_LOAD; } + + protected: + + ReadStatus _status; + std::string _message; + osg::ref_ptr _object; + + }; + + class WriteResult + { + public: + + enum WriteStatus + { + NOT_IMPLEMENTED, //!< write*() method not implemented in concrete ReaderWriter. + FILE_NOT_HANDLED, + ERROR_IN_WRITING_FILE, + FILE_SAVED + }; + + WriteResult(WriteStatus status=FILE_NOT_HANDLED):_status(status) {} + WriteResult(const std::string& m):_status(ERROR_IN_WRITING_FILE),_message(m) {} + + WriteResult(const WriteResult& rr):_status(rr._status),_message(rr._message) {} + WriteResult& operator = (const WriteResult& rr) { if (this==&rr) return *this; _status=rr._status; _message=rr._message; return *this; } + + bool operator < (const WriteResult& rhs) const { return _status < rhs._status; } + + std::string& message() { return _message; } + const std::string& message() const { return _message; } + + WriteStatus status() const { return _status; } + bool success() const { return _status==FILE_SAVED; } + bool error() const { return _status==ERROR_IN_WRITING_FILE; } + bool notHandled() const { return _status==FILE_NOT_HANDLED || _status==NOT_IMPLEMENTED; } + + protected: + + WriteStatus _status; + std::string _message; + }; + + enum ArchiveStatus + { + READ, + WRITE, + CREATE + }; + + typedef osgDB::Options Options; + + /** Determine if a file exists, normally the default implementation will be appropiate for local file access + * but with plugins like the libcurl based one it will return true if the file is accessible at the server. */ + virtual bool fileExists(const std::string& filename, const Options* options) const; + + /** Open an archive for reading, writing, or to create an empty archive for writing to.*/ + virtual ReadResult openArchive(const std::string& /*fileName*/,ArchiveStatus, unsigned int =4096, const Options* =NULL) const { return ReadResult(ReadResult::NOT_IMPLEMENTED); } + + /** Open an archive for reading.*/ + virtual ReadResult openArchive(std::istream& /*fin*/,const Options* =NULL) const { return ReadResult(ReadResult::NOT_IMPLEMENTED); } + + virtual ReadResult readObject(const std::string& /*fileName*/,const Options* =NULL) const { return ReadResult(ReadResult::NOT_IMPLEMENTED); } + virtual ReadResult readImage(const std::string& /*fileName*/,const Options* =NULL) const { return ReadResult(ReadResult::NOT_IMPLEMENTED); } + virtual ReadResult readHeightField(const std::string& /*fileName*/,const Options* =NULL) const { return ReadResult(ReadResult::NOT_IMPLEMENTED); } + virtual ReadResult readNode(const std::string& /*fileName*/,const Options* =NULL) const { return ReadResult(ReadResult::NOT_IMPLEMENTED); } + virtual ReadResult readShader(const std::string& /*fileName*/,const Options* =NULL) const { return ReadResult(ReadResult::NOT_IMPLEMENTED); } + + virtual WriteResult writeObject(const osg::Object& /*obj*/,const std::string& /*fileName*/,const Options* =NULL) const {return WriteResult(WriteResult::NOT_IMPLEMENTED); } + virtual WriteResult writeImage(const osg::Image& /*image*/,const std::string& /*fileName*/,const Options* =NULL) const {return WriteResult(WriteResult::NOT_IMPLEMENTED); } + virtual WriteResult writeHeightField(const osg::HeightField& /*heightField*/,const std::string& /*fileName*/,const Options* =NULL) const {return WriteResult(WriteResult::NOT_IMPLEMENTED); } + virtual WriteResult writeNode(const osg::Node& /*node*/,const std::string& /*fileName*/,const Options* =NULL) const { return WriteResult(WriteResult::NOT_IMPLEMENTED); } + virtual WriteResult writeShader(const osg::Shader& /*shader*/,const std::string& /*fileName*/,const Options* =NULL) const {return WriteResult(WriteResult::NOT_IMPLEMENTED); } + + virtual ReadResult readObject(std::istream& /*fin*/,const Options* =NULL) const { return ReadResult(ReadResult::NOT_IMPLEMENTED); } + virtual ReadResult readImage(std::istream& /*fin*/,const Options* =NULL) const { return ReadResult(ReadResult::NOT_IMPLEMENTED); } + virtual ReadResult readHeightField(std::istream& /*fin*/,const Options* =NULL) const { return ReadResult(ReadResult::NOT_IMPLEMENTED); } + virtual ReadResult readNode(std::istream& /*fin*/,const Options* =NULL) const { return ReadResult(ReadResult::NOT_IMPLEMENTED); } + virtual ReadResult readShader(std::istream& /*fin*/,const Options* =NULL) const { return ReadResult(ReadResult::NOT_IMPLEMENTED); } + + virtual WriteResult writeObject(const osg::Object& /*obj*/,std::ostream& /*fout*/,const Options* =NULL) const { return WriteResult(WriteResult::NOT_IMPLEMENTED); } + virtual WriteResult writeImage(const osg::Image& /*image*/,std::ostream& /*fout*/,const Options* =NULL) const { return WriteResult(WriteResult::NOT_IMPLEMENTED); } + virtual WriteResult writeHeightField(const osg::HeightField& /*heightField*/,std::ostream& /*fout*/,const Options* =NULL) const { return WriteResult(WriteResult::NOT_IMPLEMENTED); } + virtual WriteResult writeNode(const osg::Node& /*node*/,std::ostream& /*fout*/,const Options* =NULL) const { return WriteResult(WriteResult::NOT_IMPLEMENTED); } + virtual WriteResult writeShader(const osg::Shader& /*shader*/,std::ostream& /*fout*/,const Options* =NULL) const { return WriteResult(WriteResult::NOT_IMPLEMENTED); } + + /** Specify fmt string as a supported protocol. + * Please note, this method should usually only be used internally by subclasses of ReaderWriter, Only in special cases + * will a ReaderWriter implementation be able to handle a protocol format that it wasn't originally designed for. + * To know whether it's safe to inject a new protocol format into an existing ReaderWriter you will need to review + * the source code and dependencies of that ReaderWriter. */ + void supportsProtocol(const std::string& fmt, const std::string& description); + + /** Specify ext string as a supported file extension. + * Please note, this method should usually only be used internally by subclasses of ReaderWriter. Only in special cases + * will a ReaderWriter implementation be able to handle a file extension that it wasn't originally designed for. + * To know whether it's safe to inject a new file extension into an existing ReaderWriter you will need to review the + * the source code and dependencies of that ReaderWriter. */ + void supportsExtension(const std::string& ext, const std::string& description); + + /** Specify option string as a supported option string. + * Please note, this should usually only be used internally by subclasses of ReaderWriter. */ + void supportsOption(const std::string& opt, const std::string& description); + + protected: + + FormatDescriptionMap _supportedProtocols; + FormatDescriptionMap _supportedExtensions; + FormatDescriptionMap _supportedOptions; +}; + +} + +#endif // OSGDB_READERWRITER diff --git a/libs/include/android/osgDB/Registry b/libs/include/android/osgDB/Registry new file mode 100755 index 0000000..cc9aa62 --- /dev/null +++ b/libs/include/android/osgDB/Registry @@ -0,0 +1,720 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGDB_REGISTRY +#define OSGDB_REGISTRY 1 + +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +extern "C" +{ + typedef void (* CPluginFunction) (void); +} + +namespace osgDB { + + +/** + Registry is a singleton factory which stores + the reader/writers which are linked in + at runtime for reading non-native file formats. + + The RegisterReaderWriterProxy can be used to automatically + register at runtime a reader/writer with the Registry. +*/ +class OSGDB_EXPORT Registry : public osg::Referenced +{ + public: + + + + + static Registry* instance(bool erase = false); + + /** read the command line arguments.*/ + void readCommandLine(osg::ArgumentParser& commandLine); + + /** register an .fileextension alias to mapExt toExt, the later + * should the the extension name of the readerwriter plugin library. + * For example to map .tif files to the tiff loader, use + * addExtAlias("tif","tiff") which will enable .tif to be read + * by the libdb_tiff readerwriter plugin.*/ + void addFileExtensionAlias(const std::string mapExt, const std::string toExt); + + /** Reads a file that configures extension mappings. File is ASCII text + * and each line contains the parameters to the addFileExtensionAlias + * method. Lines can be commented out with an initial '#' character.*/ + bool readPluginAliasConfigurationFile( const std::string& file ); + + typedef std::map< std::string, std::string> MimeTypeExtensionMap; + + /** Registers a mapping of a mime-type to an extension. A process fetching data + * over HTTP can use this facility to determine the proper ReaderWriter to use + * when there is no filename extension to rely upon. + */ + void addMimeTypeExtensionMapping(const std::string fromMimeType, const std::string toExt); + MimeTypeExtensionMap& getMimeTypeExtensionMap() { return _mimeTypeExtMap; } + const MimeTypeExtensionMap& getMimeTypeExtensionMap() const { return _mimeTypeExtMap; } + + void addReaderWriter(ReaderWriter* rw); + void removeReaderWriter(ReaderWriter* rw); + + void addImageProcessor(ImageProcessor* ip); + void removeImageProcessor(ImageProcessor* ip); + + /** create the platform specific library name associated with file.*/ + std::string createLibraryNameForFile(const std::string& fileName); + + /** create the platform specific library name associated with file extension.*/ + std::string createLibraryNameForExtension(const std::string& ext); + + /** create the platform specific library name associated with nodekit library name.*/ + std::string createLibraryNameForNodeKit(const std::string& name); + + + enum LoadStatus { + NOT_LOADED = 0, + PREVIOUSLY_LOADED, + LOADED + }; + + /** find the library in the OSG_LIBRARY_PATH and load it.*/ + LoadStatus loadLibrary(const std::string& fileName); + + /** close the attached library with specified name.*/ + bool closeLibrary(const std::string& fileName); + + /** close all libraries.*/ + void closeAllLibraries(); + + typedef std::vector< osg::ref_ptr > ReaderWriterList; + + /** get a reader writer which handles specified extension.*/ + ReaderWriter* getReaderWriterForExtension(const std::string& ext); + + /** gets a reader/writer that handles the extension mapped to by one of + * the registered mime-types. */ + ReaderWriter* getReaderWriterForMimeType(const std::string& mimeType); + + /** get list of all registered ReaderWriters.*/ + ReaderWriterList& getReaderWriterList() { return _rwList; } + + /** get const list of all registered ReaderWriters.*/ + const ReaderWriterList& getReaderWriterList() const { return _rwList; } + + /** get a list of registered ReaderWriters which can handle given protocol */ + void getReaderWriterListForProtocol(const std::string& protocol, ReaderWriterList& results) const; + + ReaderWriter* getReaderWriterForProtocolAndExtension(const std::string& protocol, const std::string& extension); + + + typedef std::vector< osg::ref_ptr > ImageProcessorList; + + /** get a image processor if available.*/ + ImageProcessor* getImageProcessor(); + + /** get a image processor which is associated specified extension.*/ + ImageProcessor* getImageProcessorForExtension(const std::string& ext); + + /** get list of all registered ImageProcessors.*/ + ImageProcessorList& getImageProcessorList() { return _ipList; } + + /** get const list of all registered ImageProcessors.*/ + const ImageProcessorList& getImageProcessorList() const { return _ipList; } + + + typedef class osgDB::FindFileCallback FindFileCallback; + typedef class osgDB::ReadFileCallback ReadFileCallback; + typedef class osgDB::WriteFileCallback WriteFileCallback; + typedef class osgDB::FileLocationCallback FileLocationCallback; + + /** Set the Registry callback to use in place of the default findFile calls.*/ + void setFindFileCallback( FindFileCallback* cb) { _findFileCallback = cb; } + + /** Get the findFile callback.*/ + FindFileCallback* getFindFileCallback() { return _findFileCallback.get(); } + + /** Get the const findFile callback.*/ + const FindFileCallback* getFindFileCallback() const { return _findFileCallback.get(); } + + + std::string findDataFile(const std::string& fileName, const Options* options, CaseSensitivity caseSensitivity) + { + if (options && options->getFindFileCallback()) return options->getFindFileCallback()->findDataFile(fileName, options, caseSensitivity); + else if (_findFileCallback.valid()) return _findFileCallback->findDataFile(fileName, options, caseSensitivity); + else return findDataFileImplementation(fileName, options, caseSensitivity); + } + std::string findDataFileImplementation(const std::string& fileName, const Options* options, CaseSensitivity caseSensitivity); + + std::string findLibraryFile(const std::string& fileName, const Options* options, CaseSensitivity caseSensitivity) + { + if (options && options->getFindFileCallback()) return options->getFindFileCallback()->findLibraryFile(fileName, options, caseSensitivity); + else if (_findFileCallback.valid()) return _findFileCallback->findLibraryFile(fileName, options, caseSensitivity); + else return findLibraryFileImplementation(fileName, options, caseSensitivity); + } + std::string findLibraryFileImplementation(const std::string& fileName, const Options* options, CaseSensitivity caseSensitivity); + + + + /** Set the Registry callback to use in place of the default readFile calls.*/ + void setReadFileCallback( ReadFileCallback* cb) { _readFileCallback = cb; } + + /** Get the readFile callback.*/ + ReadFileCallback* getReadFileCallback() { return _readFileCallback.get(); } + + /** Get the const readFile callback.*/ + const ReadFileCallback* getReadFileCallback() const { return _readFileCallback.get(); } + + + ReaderWriter::ReadResult openArchive(const std::string& fileName,ReaderWriter::ArchiveStatus status, unsigned int indexBlockSizeHint, const Options* options) + { + if (options && options->getReadFileCallback()) return options->getReadFileCallback()->openArchive(fileName, status, indexBlockSizeHint, options); + else if (_readFileCallback.valid()) return _readFileCallback->openArchive(fileName, status, indexBlockSizeHint, options); + else return openArchiveImplementation(fileName, status, indexBlockSizeHint, options); + } + ReaderWriter::ReadResult openArchiveImplementation(const std::string& fileName, ReaderWriter::ArchiveStatus status, unsigned int indexBlockSizeHint, const Options* options); + + ReaderWriter::ReadResult readObject(const std::string& fileName,const Options* options, bool buildKdTreeIfRequired=true) + { + ReaderWriter::ReadResult result; + if (options && options->getReadFileCallback()) result = options->getReadFileCallback()->readObject(fileName,options); + else if (_readFileCallback.valid()) result = _readFileCallback->readObject(fileName,options); + else result = readObjectImplementation(fileName,options); + + if (buildKdTreeIfRequired) _buildKdTreeIfRequired(result, options); + + return result; + } + ReaderWriter::ReadResult readObjectImplementation(const std::string& fileName,const Options* options); + + ReaderWriter::ReadResult readImage(const std::string& fileName,const Options* options) + { + if (options && options->getReadFileCallback()) return options->getReadFileCallback()->readImage(fileName,options); + else if (_readFileCallback.valid()) return _readFileCallback->readImage(fileName,options); + else return readImageImplementation(fileName,options); + } + ReaderWriter::ReadResult readImageImplementation(const std::string& fileName,const Options* options); + + ReaderWriter::ReadResult readHeightField(const std::string& fileName,const Options* options) + { + if (options && options->getReadFileCallback()) return options->getReadFileCallback()->readHeightField(fileName,options); + else if (_readFileCallback.valid()) return _readFileCallback->readHeightField(fileName,options); + else return readHeightFieldImplementation(fileName,options); + } + ReaderWriter::ReadResult readHeightFieldImplementation(const std::string& fileName,const Options* options); + + ReaderWriter::ReadResult readNode(const std::string& fileName,const Options* options, bool buildKdTreeIfRequired=true) + { + ReaderWriter::ReadResult result; + if (options && options->getReadFileCallback()) result = options->getReadFileCallback()->readNode(fileName,options); + else if (_readFileCallback.valid()) result = _readFileCallback->readNode(fileName,options); + else result = readNodeImplementation(fileName,options); + + if (buildKdTreeIfRequired) _buildKdTreeIfRequired(result, options); + + return result; + } + ReaderWriter::ReadResult readNodeImplementation(const std::string& fileName,const Options* options); + + ReaderWriter::ReadResult readShader(const std::string& fileName,const Options* options) + { + if (options && options->getReadFileCallback()) return options->getReadFileCallback()->readShader(fileName,options); + if (_readFileCallback.valid()) return _readFileCallback->readShader(fileName,options); + else return readShaderImplementation(fileName,options); + } + ReaderWriter::ReadResult readShaderImplementation(const std::string& fileName,const Options* options); + + + /** Set the Registry callback to use in place of the default writeFile calls.*/ + void setWriteFileCallback( WriteFileCallback* cb) { _writeFileCallback = cb; } + + /** Get the writeFile callback.*/ + WriteFileCallback* getWriteFileCallback() { return _writeFileCallback.get(); } + + /** Get the const writeFile callback.*/ + const WriteFileCallback* getWriteFileCallback() const { return _writeFileCallback.get(); } + + + ReaderWriter::WriteResult writeObject(const osg::Object& obj, const std::string& fileName,const Options* options) + { + if (options && options->getWriteFileCallback()) return options->getWriteFileCallback()->writeObject(obj,fileName,options); + else if (_writeFileCallback.valid()) return _writeFileCallback->writeObject(obj,fileName,options); + else return writeObjectImplementation(obj,fileName,options); + } + ReaderWriter::WriteResult writeObjectImplementation(const osg::Object& obj, const std::string& fileName,const Options* options); + + ReaderWriter::WriteResult writeImage(const osg::Image& obj, const std::string& fileName,const Options* options) + { + if (options && options->getWriteFileCallback()) return options->getWriteFileCallback()->writeImage(obj,fileName,options); + else if (_writeFileCallback.valid()) return _writeFileCallback->writeImage(obj,fileName,options); + else return writeImageImplementation(obj,fileName,options); + } + ReaderWriter::WriteResult writeImageImplementation(const osg::Image& obj, const std::string& fileName,const Options* options); + + ReaderWriter::WriteResult writeHeightField(const osg::HeightField& obj, const std::string& fileName,const Options* options) + { + if (options && options->getWriteFileCallback()) return options->getWriteFileCallback()->writeHeightField(obj,fileName,options); + else if (_writeFileCallback.valid()) return _writeFileCallback->writeHeightField(obj,fileName,options); + else return writeHeightFieldImplementation(obj,fileName,options); + } + ReaderWriter::WriteResult writeHeightFieldImplementation(const osg::HeightField& obj, const std::string& fileName,const Options* options); + + ReaderWriter::WriteResult writeNode(const osg::Node& node, const std::string& fileName,const Options* options) + { + if (options && options->getWriteFileCallback()) return options->getWriteFileCallback()->writeNode(node,fileName,options); + else if (_writeFileCallback.valid()) return _writeFileCallback->writeNode(node,fileName,options); + else return writeNodeImplementation(node,fileName,options); + } + ReaderWriter::WriteResult writeNodeImplementation(const osg::Node& node, const std::string& fileName,const Options* options); + + ReaderWriter::WriteResult writeShader(const osg::Shader& obj, const std::string& fileName,const Options* options) + { + if (options && options->getWriteFileCallback()) return options->getWriteFileCallback()->writeShader(obj,fileName,options); + else if (_writeFileCallback.valid()) return _writeFileCallback->writeShader(obj,fileName,options); + else return writeShaderImplementation(obj,fileName,options); + } + ReaderWriter::WriteResult writeShaderImplementation(const osg::Shader& obj, const std::string& fileName,const Options* options); + + + inline void _buildKdTreeIfRequired(ReaderWriter::ReadResult& result, const Options* options) + { + bool doKdTreeBuilder = (options && options->getBuildKdTreesHint()!=Options::NO_PREFERENCE) ? + options->getBuildKdTreesHint() == Options::BUILD_KDTREES : + _buildKdTreesHint == Options::BUILD_KDTREES; + + if (doKdTreeBuilder && _kdTreeBuilder.valid() && result.validNode()) + { + osg::ref_ptr builder = _kdTreeBuilder->clone(); + result.getNode()->accept(*builder); + } + } + + /** Set the callback to use inform to the DatabasePager whether a file is located on local or remote file system.*/ + void setFileLocationCallback( FileLocationCallback* cb) { _fileLocationCallback = cb; } + + /** Get the callback to use inform to the DatabasePager whether a file is located on local or remote file system.*/ + FileLocationCallback* getFileLocationCallback() const { return _fileLocationCallback.get(); } + + + + /** Set whether the KdTrees should be built for geometry in the loader model. */ + void setBuildKdTreesHint(Options::BuildKdTreesHint hint) { _buildKdTreesHint = hint; } + + /** Get whether the KdTrees should be built for geometry in the loader model. */ + Options::BuildKdTreesHint getBuildKdTreesHint() const { return _buildKdTreesHint; } + + /** Set the KdTreeBuilder visitor that is used to build KdTree on loaded models.*/ + void setKdTreeBuilder(osg::KdTreeBuilder* builder) { _kdTreeBuilder = builder; } + + /** Get the KdTreeBuilder visitor that is used to build KdTree on loaded models.*/ + osg::KdTreeBuilder* getKdTreeBuilder() { return _kdTreeBuilder.get(); } + + + /** Set the FileCache that is used to manage local storage of files downloaded from the internet.*/ + void setFileCache(FileCache* fileCache) { _fileCache = fileCache; } + + /** Get the FileCache that is used to manage local storage of files downloaded from the internet.*/ + FileCache* getFileCache() { return _fileCache.get(); } + + /** Get the const FileCache that is used to manage local storage of files downloaded from the internet.*/ + const FileCache* getFileCache() const { return _fileCache.get(); } + + + /** Set the password map to be used by plugins when access files from secure locations.*/ + void setAuthenticationMap(AuthenticationMap* authenticationMap) { _authenticationMap = authenticationMap; } + + /** Get the password map to be used by plugins when access files from secure locations.*/ + AuthenticationMap* getAuthenticationMap() { return _authenticationMap.get(); } + + /** Get the password map to be used by plugins when access files from secure locations.*/ + const AuthenticationMap* getAuthenticationMap() const { return _authenticationMap.get(); } + + + void setCreateNodeFromImage(bool flag) { _createNodeFromImage = flag; } + bool getCreateNodeFromImage() const { return _createNodeFromImage; } + + + void setOptions(Options* opt) { _options = opt; } + Options* getOptions() { return _options.get(); } + const Options* getOptions() const { return _options.get(); } + + + /** initialize both the Data and Library FilePaths, by default called by the + * constructor, so it should only be required if you want to force + * the re-reading of environmental variables.*/ + void initFilePathLists() { initDataFilePathList(); initLibraryFilePathList(); } + + /** initialize the Data FilePath by reading the OSG_FILE_PATH environmental variable.*/ + void initDataFilePathList(); + + /** Set the data file path using a list of paths stored in a FilePath, which is used when search for data files.*/ + void setDataFilePathList(const FilePathList& filepath) { _dataFilePath = filepath; } + + /** Set the data file path using a single string delimited either with ';' (Windows) or ':' (All other platforms), which is used when search for data files.*/ + void setDataFilePathList(const std::string& paths); + + /** get the data file path which is used when search for data files.*/ + FilePathList& getDataFilePathList() { return _dataFilePath; } + + /** get the const data file path which is used when search for data files.*/ + const FilePathList& getDataFilePathList() const { return _dataFilePath; } + + /** initialize the Library FilePath by reading the OSG_LIBRARY_PATH + * and the appropriate system environmental variables*/ + void initLibraryFilePathList(); + + /** Set the library file path using a list of paths stored in a FilePath, which is used when search for data files.*/ + void setLibraryFilePathList(const FilePathList& filepath) { _libraryFilePath = filepath; } + + /** Set the library file path using a single string delimited either with ';' (Windows) or ':' (All other platforms), which is used when search for data files.*/ + void setLibraryFilePathList(const std::string& paths); + + /** get the library file path which is used when search for library (dso/dll's) files.*/ + FilePathList& getLibraryFilePathList() { return _libraryFilePath; } + + /** get the const library file path which is used when search for library (dso/dll's) files.*/ + const FilePathList& getLibraryFilePathList() const { return _libraryFilePath; } + + /** For each object in the cache which has an reference count greater than 1 + * (and therefore referenced by elsewhere in the application) set the time stamp + * for that object in the cache to specified time. + * This would typically be called once per frame by applications which are doing database paging, + * and need to prune objects that are no longer required. + * The time used is taken from the FrameStamp::getReferenceTime().*/ + void updateTimeStampOfObjectsInCacheWithExternalReferences(const osg::FrameStamp& frameStamp); + + /** Removed object in the cache which have a time stamp at or before the specified expiry time. + * This would typically be called once per frame by applications which are doing database paging, + * and need to prune objects that are no longer required, and called after the a called + * after the call to updateTimeStampOfObjectsInCacheWithExternalReferences(frameStamp).*/ + void removeExpiredObjectsInCache(const osg::FrameStamp& frameStamp); + + /** set hint to viewer code calling removeExpiredObjectsInCache to specify how long it should give before expiring objects in Registry cache,*/ + void setExpiryDelay(double expiryDelay) { _expiryDelay = expiryDelay; } + + double getExpiryDelay() const { return _expiryDelay; } + + + /** Remove all objects in the cache regardless of having external references or expiry times.*/ + void clearObjectCache(); + + /** Add a filename,object,timestamp triple to the Registry::ObjectCache.*/ + void addEntryToObjectCache(const std::string& filename, osg::Object* object, double timestamp = 0.0); + + /** Remove Object from cache.*/ + void removeFromObjectCache(const std::string& fileName); + + /** Get an Object from the object cache*/ + osg::Object* getFromObjectCache(const std::string& fileName); + + /** Get an ref_ptr from the object cache*/ + osg::ref_ptr getRefFromObjectCache(const std::string& fileName); + + + + /** Add archive to archive cache so that future calls reference this archive.*/ + void addToArchiveCache(const std::string& fileName, osgDB::Archive* archive); + + /** Remove Archive from cache.*/ + void removeFromArchiveCache(const std::string& fileName); + + /** Get an Archive from the archive cache.*/ + osgDB::Archive* getFromArchiveCache(const std::string& fileName); + + /** Get an ref_ptr from the archive cache.*/ + osg::ref_ptr getRefFromArchiveCache(const std::string& fileName); + + /** Remove all archives from the archive cache.*/ + void clearArchiveCache(); + + /** If State is non-zero, this function releases OpenGL objects for + * the specified graphics context. Otherwise, releases OpenGL objexts + * for all graphics contexts. */ + void releaseGLObjects(osg::State* state=0); + + /** get the attached library with specified name.*/ + DynamicLibrary* getLibrary(const std::string& fileName); + + /** Set the SharedStateManager.*/ + void setSharedStateManager(SharedStateManager* SharedStateManager) { _sharedStateManager = SharedStateManager; } + + /** Get the SharedStateManager, creating one if one is not already created.*/ + SharedStateManager* getOrCreateSharedStateManager(); + + /** Get the SharedStateManager. Return 0 if no SharedStateManager has been assigned.*/ + SharedStateManager* getSharedStateManager() { return _sharedStateManager.get(); } + + /** Add an Archive extension.*/ + void addArchiveExtension(const std::string ext); + + /** registers a protocol */ + void registerProtocol(const std::string& protocol); + + /** returns true, if named protocol is registered */ + bool isProtocolRegistered(const std::string& protocol); + + /** Get the ObjectWrapperManager that is used to store all the ObjectWrappers. */ + ObjectWrapperManager* getObjectWrapperManager() { return _objectWrapperManager.get(); } + + /** Get the ObjectWrapperManager that is used to store all the ObjectWrappers. */ + DeprecatedDotOsgWrapperManager* getDeprecatedDotOsgObjectWrapperManager() { return _deprecatedDotOsgWrapperManager.get(); } + + typedef std::vector< std::string> ArchiveExtensionList; + const ArchiveExtensionList& getArchiveExtensions() const { return _archiveExtList; } + + protected: + + virtual ~Registry(); + + typedef std::vector< osg::ref_ptr > DynamicLibraryList; + typedef std::map< std::string, std::string> ExtensionAliasMap; + + typedef std::pair, double > ObjectTimeStampPair; + typedef std::map ObjectCache; + typedef std::map > ArchiveCache; + + typedef std::set RegisteredProtocolsSet; + + /** constructor is private, as its a singleton, preventing + construction other than via the instance() method and + therefore ensuring only one copy is ever constructed*/ + Registry(); + + /** get the attached library with specified name.*/ + DynamicLibraryList::iterator getLibraryItr(const std::string& fileName); + + Options::BuildKdTreesHint _buildKdTreesHint; + osg::ref_ptr _kdTreeBuilder; + + osg::ref_ptr _fileCache; + + osg::ref_ptr _authenticationMap; + + bool _createNodeFromImage; + + RegisteredProtocolsSet _registeredProtocols; + + public: + /** Functor used in internal implementations.*/ + struct ReadFunctor + { + ReadFunctor(const std::string& filename, const Options* options): + _filename(filename), + _options(options) {} + + virtual ~ReadFunctor() {} + virtual ReaderWriter::ReadResult doRead(ReaderWriter& rw) const = 0; + virtual bool isValid(ReaderWriter::ReadResult& readResult) const = 0; + virtual bool isValid(osg::Object* object) const = 0; + + virtual ReadFunctor* cloneType(const std::string& filename, const Options* options) const = 0; + + std::string _filename; + const Options* _options; + }; + + protected: + + void destruct(); + + // forward declare helper classes + struct ReadObjectFunctor; + struct ReadImageFunctor; + struct ReadHeightFieldFunctor; + struct ReadNodeFunctor; + struct ReadArchiveFunctor; + struct ReadShaderFunctor; + + // make helper classes friends to get round VS6.0 "issues" + friend struct ReadFunctor; + friend struct ReadObjectFunctor; + friend struct ReadImageFunctor; + friend struct ReadHeightFieldFunctor; + friend struct ReadNodeFunctor; + friend struct ReadArchiveFunctor; + friend struct ReadShaderFunctor; + + ReaderWriter::ReadResult read(const ReadFunctor& readFunctor); + ReaderWriter::ReadResult readImplementation(const ReadFunctor& readFunctor,Options::CacheHintOptions cacheHint); + + + // forward declare helper class + class AvailableReaderWriterIterator; + friend class AvailableReaderWriterIterator; + class AvailableArchiveIterator; + friend class AvailableArchiveIterator; + + + osg::ref_ptr _findFileCallback; + osg::ref_ptr _readFileCallback; + osg::ref_ptr _writeFileCallback; + osg::ref_ptr _fileLocationCallback; + + OpenThreads::ReentrantMutex _pluginMutex; + ReaderWriterList _rwList; + ImageProcessorList _ipList; + DynamicLibraryList _dlList; + + OpenThreads::ReentrantMutex _archiveCacheMutex; + ArchiveCache _archiveCache; + + bool _openingLibrary; + + // map to alias to extensions to plugins. + ExtensionAliasMap _extAliasMap; + + // maps mime-types to extensions. + MimeTypeExtensionMap _mimeTypeExtMap; + + // Utility: Removes whitespace from both ends of a string. + static std::string trim( const std::string& str ); + + // options to pass to reader writers. + osg::ref_ptr _options; + + FilePathList _dataFilePath; + FilePathList _libraryFilePath; + + double _expiryDelay; + ObjectCache _objectCache; + OpenThreads::Mutex _objectCacheMutex; + + + ArchiveExtensionList _archiveExtList; + + osg::ref_ptr _sharedStateManager; + + osg::ref_ptr _objectWrapperManager; + osg::ref_ptr _deprecatedDotOsgWrapperManager; +}; + +/** read the command line arguments.*/ +inline void readCommandLine(osg::ArgumentParser& parser) +{ + Registry::instance()->readCommandLine(parser); +} + +/** Proxy class for automatic registration of reader/writers with the Registry.*/ +template +class RegisterReaderWriterProxy +{ + public: + RegisterReaderWriterProxy() + { + if (Registry::instance()) + { + _rw = new T; + Registry::instance()->addReaderWriter(_rw.get()); + } + } + + ~RegisterReaderWriterProxy() + { + if (Registry::instance()) + { + Registry::instance()->removeReaderWriter(_rw.get()); + } + } + + T* get() { return _rw.get(); } + + protected: + osg::ref_ptr _rw; +}; + + +/** Proxy class for automatic registration of reader/writers with the Registry.*/ +template +class RegisterImageProcessorProxy +{ + public: + RegisterImageProcessorProxy() + { + if (Registry::instance()) + { + _rw = new T; + Registry::instance()->addImageProcessor(_rw.get()); + } + } + + ~RegisterImageProcessorProxy() + { + if (Registry::instance()) + { + Registry::instance()->removeImageProcessor(_rw.get()); + } + } + + T* get() { return _rw.get(); } + + protected: + osg::ref_ptr _rw; +}; + +struct PluginFunctionProxy +{ + PluginFunctionProxy(CPluginFunction function) { (function)(); } +}; + +#define USE_OSGPLUGIN(ext) \ + extern "C" void osgdb_##ext(void); \ + static osgDB::PluginFunctionProxy proxy_##ext(osgdb_##ext); + +#define USE_DOTOSGWRAPPER(classname) \ + extern "C" void dotosgwrapper_##classname(void); \ + static osgDB::PluginFunctionProxy proxy_dotosgwrapper_##classname(dotosgwrapper_##classname); + +#define USE_DOTOSGWRAPPER_LIBRARY(libname) \ + extern "C" void dotosgwrapper_library_##libname(void); \ + static osgDB::PluginFunctionProxy proxy_dotosgwrapper_library_##libname(dotosgwrapper_library_##libname); + +#define USE_SERIALIZER_WRAPPER(classname) \ + extern "C" void wrapper_serializer_##classname(void); \ + static osgDB::PluginFunctionProxy proxy_serializer_##classname(wrapper_serializer_##classname); + +#define USE_SERIALIZER_WRAPPER_LIBRARY(libname) \ + extern "C" void wrapper_serializer_library_##libname(void); \ + static osgDB::PluginFunctionProxy proxy_serializer_library_##libname(wrapper_serializer_library_##libname); + +#define USE_COMPRESSOR_WRAPPER(classname) \ + extern "C" void wrapper_compressor_##classname(void); \ + static osgDB::PluginFunctionProxy proxy_compressor_##classname(wrapper_compressor_##classname); + +#define REGISTER_OSGPLUGIN(ext, classname) \ + extern "C" void osgdb_##ext(void) {} \ + static osgDB::RegisterReaderWriterProxy g_proxy_##classname; + +#define REGISTER_OSGIMAGEPROCESSOR(ext, classname) \ + extern "C" void osgdb_##ext(void) {} \ + static osgDB::RegisterImageProcessorProxy g_proxy_##classname; + +} + +#endif diff --git a/libs/include/android/osgDB/Serializer b/libs/include/android/osgDB/Serializer new file mode 100755 index 0000000..c1db372 --- /dev/null +++ b/libs/include/android/osgDB/Serializer @@ -0,0 +1,1065 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2010 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +// Written by Wang Rui, (C) 2010 + +#ifndef OSGDB__SERIALIZER +#define OSGDB__SERIALIZER + +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace osgDB +{ + +#ifndef OBJECT_CAST + #define OBJECT_CAST static_cast +#endif + +class IntLookup +{ +public: + typedef int Value; + typedef std::map StringToValue; + typedef std::map ValueToString; + + IntLookup() {} + unsigned int size() const { return static_cast(_stringToValue.size()); } + + void add( const char* str, Value value ) + { + if ( _valueToString.find(value)!=_valueToString.end() ) + { + osg::notify(osg::WARN) << "Duplicate enum value " << value + << " with old string: " << _valueToString[value] + << " and new string: " << str << std::endl; + } + _valueToString[value] = str; + _stringToValue[str] = value; + } + + Value getValue( const char* str ) + { + StringToValue::iterator itr = _stringToValue.find(str); + if ( itr==_stringToValue.end() ) + { + Value value; + std::stringstream stream; + stream << str; stream >> value; + _stringToValue[str] = value; + return value; + } + return itr->second; + } + + const std::string& getString( Value value ) + { + ValueToString::iterator itr = _valueToString.find(value); + if ( itr==_valueToString.end() ) + { + std::string str; + std::stringstream stream; + stream << value; stream >> str; + _valueToString[value] = str; + return _valueToString[value]; + } + return itr->second; + } + +protected: + StringToValue _stringToValue; + ValueToString _valueToString; +}; + +class UserLookupTableProxy +{ +public: + typedef void (*AddValueFunc)( IntLookup* lookup ); + UserLookupTableProxy( AddValueFunc func ) { if ( func ) (*func)(&_lookup); } + + IntLookup _lookup; +}; + +#define BEGIN_USER_TABLE(NAME, CLASS) \ + static void add_user_value_func_##NAME(osgDB::IntLookup*); \ + static osgDB::UserLookupTableProxy s_user_lookup_table_##NAME(&add_user_value_func_##NAME); \ + static void add_user_value_func_##NAME(osgDB::IntLookup* lookup) { typedef CLASS MyClass +#define ADD_USER_VALUE(VALUE) lookup->add(#VALUE, MyClass::VALUE) +#define END_USER_TABLE() } + +#define USER_READ_FUNC(NAME, FUNCNAME) \ + static int FUNCNAME(osgDB::InputStream& is) { \ + int value; if (is.isBinary()) is >> value; \ + else { std::string str; is >> str; \ + value = (s_user_lookup_table_##NAME)._lookup.getValue(str.c_str()); } \ + return value; } + +#define USER_WRITE_FUNC(NAME, FUNCNAME) \ + static void FUNCNAME(osgDB::OutputStream& os, int value) { \ + if (os.isBinary()) os << value; \ + else os << (s_user_lookup_table_##NAME)._lookup.getString(value); } \ + +class BaseSerializer : public osg::Referenced +{ + friend class ObjectWrapper; +public: + enum Type + { + RW_UNDEFINED = 0, RW_USER, RW_OBJECT, RW_IMAGE, RW_LIST, + RW_BOOL, RW_CHAR, RW_UCHAR, RW_SHORT, RW_USHORT, RW_INT, RW_UINT, RW_FLOAT, RW_DOUBLE, + RW_VEC2F, RW_VEC2D, RW_VEC3F, RW_VEC3D, RW_VEC4F, RW_VEC4D, RW_QUAT, RW_PLANE, + RW_MATRIXF, RW_MATRIXD, RW_MATRIX, RW_GLENUM, RW_STRING, RW_ENUM, + RW_VEC2B, RW_VEC2UB, RW_VEC2S, RW_VEC2US, RW_VEC2I, RW_VEC2UI, + RW_VEC3B, RW_VEC3UB, RW_VEC3S, RW_VEC3US, RW_VEC3I, RW_VEC3UI, + RW_VEC4B, RW_VEC4UB, RW_VEC4S, RW_VEC4US, RW_VEC4I, RE_VEC4UI + }; + + BaseSerializer() : _firstVersion(0), _lastVersion(INT_MAX) {} + + virtual bool read( InputStream&, osg::Object& ) = 0; + virtual bool write( OutputStream&, const osg::Object& ) = 0; + virtual const std::string& getName() const = 0; + +protected: + int _firstVersion; // Library version when the serializer is first introduced + int _lastVersion; // Library version when the serializer is last required. +}; + +template +class UserSerializer : public BaseSerializer +{ +public: + typedef bool (*Checker)( const C& ); + typedef bool (*Reader)( InputStream&, C& ); + typedef bool (*Writer)( OutputStream&, const C& ); + + UserSerializer( const char* name, Checker cf, Reader rf, Writer wf ) + : BaseSerializer(), _name(name), _checker(cf), _reader(rf), _writer(wf) {} + + virtual bool read( InputStream& is, osg::Object& obj ) + { + C& object = OBJECT_CAST(obj); + if ( is.isBinary() ) + { + bool ok = false; is >> ok; + if ( !ok ) return true; + } + else + { + if ( !is.matchString(_name) ) + return true; + } + return (*_reader)(is, object); + } + + virtual bool write( OutputStream& os, const osg::Object& obj ) + { + const C& object = OBJECT_CAST(obj); + bool ok = (*_checker)(object); + if ( os.isBinary() ) + { + os << ok; + if ( !ok ) return true; + } + else + { + if ( !ok ) return true; + os << os.PROPERTY(_name.c_str()); + } + return (*_writer)(os, object); + } + + virtual const std::string& getName() const { return _name; } + +protected: + std::string _name; + Checker _checker; + +public: + Reader _reader; + Writer _writer; +}; + +template +class TemplateSerializer : public BaseSerializer +{ +public: + + TemplateSerializer( const char* name, P def) + : BaseSerializer(), _name(name), _defaultValue(def) {} + + virtual bool read( InputStream& is, osg::Object& obj ) = 0; + virtual bool write( OutputStream& os, const osg::Object& obj ) = 0; + virtual const std::string& getName() const { return _name; } + +protected: + std::string _name; + P _defaultValue; +}; + +template +class PropByValSerializer : public TemplateSerializer

+{ +public: + typedef TemplateSerializer

ParentType; + typedef P (C::*Getter)() const; + typedef void (C::*Setter)( P ); + + PropByValSerializer( const char* name, P def, Getter gf, Setter sf, bool useHex=false ) + : ParentType(name, def), _getter(gf), _setter(sf), _useHex(useHex) {} + + virtual bool read( InputStream& is, osg::Object& obj ) + { + C& object = OBJECT_CAST(obj); + P value; + if ( is.isBinary() ) + { + is >> value; + if ( ParentType::_defaultValue!=value ) + (object.*_setter)( value ); + } + else if ( is.matchString(ParentType::_name) ) + { + if ( _useHex ) is >> std::hex; + is >> value; + if ( _useHex ) is >> std::dec; + (object.*_setter)( value ); + } + return true; + } + + virtual bool write( OutputStream& os, const osg::Object& obj ) + { + const C& object = OBJECT_CAST(obj); + P value = (object.*_getter)(); + if ( os.isBinary() ) + { + os << value; + } + else if ( ParentType::_defaultValue!=value ) + { + os << os.PROPERTY((ParentType::_name).c_str()); + if ( _useHex ) { os << std::hex << std::showbase; } + os << value; + if ( _useHex ) os << std::dec << std::noshowbase; + os << std::endl; + } + return true; + } + +public: + Getter _getter; + Setter _setter; + +protected: + bool _useHex; +}; + +template +class PropByRefSerializer : public TemplateSerializer

+{ +public: + typedef TemplateSerializer

ParentType; + typedef const P& CP; + typedef CP (C::*Getter)() const; + typedef void (C::*Setter)( CP ); + + PropByRefSerializer( const char* name, CP def, Getter gf, Setter sf ) + : ParentType(name, def), _getter(gf), _setter(sf) {} + + virtual bool read( InputStream& is, osg::Object& obj ) + { + C& object = OBJECT_CAST(obj); + P value; + if ( is.isBinary() ) + { + is >> value; + if ( ParentType::_defaultValue!=value ) + (object.*_setter)( value ); + } + else if ( is.matchString(ParentType::_name) ) + { + is >> value; + (object.*_setter)( value ); + } + return true; + } + + virtual bool write( OutputStream& os, const osg::Object& obj ) + { + const C& object = OBJECT_CAST(obj); + CP value = (object.*_getter)(); + if ( os.isBinary() ) + { + os << value; + } + else if ( ParentType::_defaultValue!=value ) + { + os << os.PROPERTY((ParentType::_name).c_str()) << value << std::endl; + } + return true; + } + +public: + Getter _getter; + Setter _setter; +}; + +template +class MatrixSerializer : public TemplateSerializer +{ +public: + typedef TemplateSerializer ParentType; + typedef const osg::Matrix& (C::*Getter)() const; + typedef void (C::*Setter)( const osg::Matrix& ); + + MatrixSerializer( const char* name, const osg::Matrix& def, Getter gf, Setter sf ) + : ParentType(name, def), _getter(gf), _setter(sf) {} + + virtual bool read( InputStream& is, osg::Object& obj ) + { + C& object = OBJECT_CAST(obj); + osg::Matrix value; + if ( is.isBinary() ) + { + readMatrixImplementation( is, value ); + if ( ParentType::_defaultValue!=value ) + (object.*_setter)( value ); + } + else if ( is.matchString(ParentType::_name) ) + { + readMatrixImplementation( is, value ); + (object.*_setter)( value ); + } + return true; + } + + virtual bool write( OutputStream& os, const osg::Object& obj ) + { + + const C& object = OBJECT_CAST(obj); + const osg::Matrix& value = (object.*_getter)(); + if ( os.isBinary() ) + { + os << value; + } + else if ( ParentType::_defaultValue!=value ) + { + os << os.PROPERTY((ParentType::_name).c_str()) << value << std::endl; + } + return true; + } + +protected: + void readMatrixImplementation( InputStream& is, osg::Matrix& matrix ) + { +#if 1 + is >> matrix; +#else + if ( is.getUseFloatMatrix() ) + { + osg::Matrixf realValue; is >> realValue; + matrix = realValue; + } + else + { + osg::Matrixd realValue; is >> realValue; + matrix = realValue; + } +#endif + } + +public: + Getter _getter; + Setter _setter; +}; + +template +class GLenumSerializer : public TemplateSerializer

+{ +public: + typedef TemplateSerializer

ParentType; + typedef P (C::*Getter)() const; + typedef void (C::*Setter)( P ); + + GLenumSerializer( const char* name, P def, Getter gf, Setter sf ) + : ParentType(name, def), _getter(gf), _setter(sf) {} + + virtual bool read( InputStream& is, osg::Object& obj ) + { + C& object = OBJECT_CAST(obj); + if ( is.isBinary() ) + { + GLenum value; is >> value; + if ( ParentType::_defaultValue!=static_cast

(value) ) + (object.*_setter)( static_cast

(value) ); + } + else if ( is.matchString(ParentType::_name) ) + { + DEF_GLENUM(value); is >> value; + (object.*_setter)( static_cast

(value.get()) ); + } + return true; + } + + virtual bool write( OutputStream& os, const osg::Object& obj ) + { + const C& object = OBJECT_CAST(obj); + const P value = (object.*_getter)(); + if ( os.isBinary() ) + { + os << static_cast(value); + } + else if ( ParentType::_defaultValue!=value ) + { + os << os.PROPERTY((ParentType::_name).c_str()) << GLENUM(value) << std::endl; + } + return true; + } + +public: + Getter _getter; + Setter _setter; +}; + +template +class StringSerializer : public TemplateSerializer +{ +public: + typedef TemplateSerializer ParentType; + typedef const std::string& (C::*Getter)() const; + typedef void (C::*Setter)( const std::string& ); + + StringSerializer( const char* name, const std::string& def, Getter gf, Setter sf ) + : ParentType(name, def), _getter(gf), _setter(sf) {} + + virtual bool read( InputStream& is, osg::Object& obj ) + { + C& object = OBJECT_CAST(obj); + std::string value; + if ( is.isBinary() ) + { + is >> value; + if ( ParentType::_defaultValue!=value ) + (object.*_setter)( value ); + } + else if ( is.matchString(ParentType::_name) ) + { + is.readWrappedString( value ); + if ( !value.empty() ) + (object.*_setter)( value ); + } + return true; + } + + virtual bool write( OutputStream& os, const osg::Object& obj ) + { + const C& object = OBJECT_CAST(obj); + const std::string& value = (object.*_getter)(); + if ( os.isBinary() ) + { + os << value; + } + else if ( ParentType::_defaultValue!=value ) + { + os << os.PROPERTY((ParentType::_name).c_str()); + os.writeWrappedString( value ); + os << std::endl; + } + return true; + } + +public: + Getter _getter; + Setter _setter; +}; + +template +class ObjectSerializer : public TemplateSerializer +{ +public: + typedef TemplateSerializer ParentType; + typedef const P* (C::*Getter)() const; + typedef void (C::*Setter)( P* ); + + ObjectSerializer( const char* name, P* def, Getter gf, Setter sf ) + : ParentType(name, def), _getter(gf), _setter(sf) {} + + virtual bool read( InputStream& is, osg::Object& obj ) + { + C& object = OBJECT_CAST(obj); + bool hasObject = false; + if ( is.isBinary() ) + { + is >> hasObject; + if ( hasObject ) + { + P* value = dynamic_cast( is.readObject() ); + if ( ParentType::_defaultValue!=value ) + (object.*_setter)( value ); + } + } + else if ( is.matchString(ParentType::_name) ) + { + is >> hasObject; + if ( hasObject ) + { + is >> is.BEGIN_BRACKET; + P* value = dynamic_cast( is.readObject() ); + if ( ParentType::_defaultValue!=value ) + (object.*_setter)( value ); + is >> is.END_BRACKET; + } + } + return true; + } + + virtual bool write( OutputStream& os, const osg::Object& obj ) + { + const C& object = OBJECT_CAST(obj); + const P* value = (object.*_getter)(); + bool hasObject = (value!=NULL); + if ( os.isBinary() ) + { + os << hasObject; + os.writeObject( value ); + } + else if ( ParentType::_defaultValue!=value ) + { + os << os.PROPERTY((ParentType::_name).c_str()) << hasObject; + if ( hasObject ) + { + os << os.BEGIN_BRACKET << std::endl; + os.writeObject( value ); + os << os.END_BRACKET; + } + os << std::endl; + } + return true; + } + +public: + Getter _getter; + Setter _setter; +}; + +template +class ImageSerializer : public TemplateSerializer +{ +public: + typedef TemplateSerializer ParentType; + typedef const P* (C::*Getter)() const; + typedef void (C::*Setter)( P* ); + + ImageSerializer( const char* name, P* def, Getter gf, Setter sf ) + : ParentType(name, def), _getter(gf), _setter(sf) {} + + virtual bool read( InputStream& is, osg::Object& obj ) + { + C& object = OBJECT_CAST(obj); + bool hasObject = false; + if ( is.isBinary() ) + { + is >> hasObject; + if ( hasObject ) + { + P* value = dynamic_cast( is.readImage() ); + if ( ParentType::_defaultValue!=value ) + (object.*_setter)( value ); + } + } + else if ( is.matchString(ParentType::_name) ) + { + is >> hasObject; + if ( hasObject ) + { + is >> is.BEGIN_BRACKET; + P* value = dynamic_cast( is.readImage() ); + if ( ParentType::_defaultValue!=value ) + (object.*_setter)( value ); + is >> is.END_BRACKET; + } + } + return true; + } + + virtual bool write( OutputStream& os, const osg::Object& obj ) + { + const C& object = OBJECT_CAST(obj); + const P* value = (object.*_getter)(); + bool hasObject = (value!=NULL); + if ( os.isBinary() ) + { + os << hasObject; + os.writeImage( value ); + } + else if ( ParentType::_defaultValue!=value ) + { + os << os.PROPERTY((ParentType::_name).c_str()) << hasObject; + if ( hasObject ) + { + os << os.BEGIN_BRACKET << std::endl; + os.writeImage( value ); + os << os.END_BRACKET; + } + os << std::endl; + } + return true; + } + +public: + Getter _getter; + Setter _setter; +}; + +template +class EnumSerializer : public TemplateSerializer

+{ +public: + typedef TemplateSerializer

ParentType; + typedef P (C::*Getter)() const; + typedef B (C::*Setter)( P ); + + EnumSerializer( const char* name, P def, Getter gf, Setter sf ) + : ParentType(name, def), _getter(gf), _setter(sf) {} + + void add( const char* str, P value ) + { _lookup.add(str, static_cast(value)); } + + P getValue( const char* str ) + { return static_cast

(_lookup.getValue(str)); } + + const std::string& getString( P value ) + { return _lookup.getString(static_cast(value)); } + + virtual bool read( InputStream& is, osg::Object& obj ) + { + C& object = OBJECT_CAST(obj); + IntLookup::Value value; + if ( is.isBinary() ) + { + is >> value; + if ( ParentType::_defaultValue!=static_cast

(value) ) + (object.*_setter)( static_cast

(value) ); + } + else if ( is.matchString(ParentType::_name) ) + { + std::string str; is >> str; + (object.*_setter)( getValue(str.c_str()) ); + } + return true; + } + + virtual bool write( osgDB::OutputStream& os, const osg::Object& obj ) + { + const C& object = OBJECT_CAST(obj); + const P value = (object.*_getter)(); + if ( os.isBinary() ) + { + os << (IntLookup::Value)value; + } + else if ( ParentType::_defaultValue!=value ) + { + os << os.PROPERTY((ParentType::_name).c_str()) << getString(value) << std::endl; + } + return true; + } + +public: + Getter _getter; + Setter _setter; + +protected: + IntLookup _lookup; +}; + + +template +class ListSerializer : public BaseSerializer +{ +public: + typedef typename P::value_type ValueType; + typedef typename P::const_iterator ConstIterator; + typedef const P& (C::*Getter)() const; + typedef void (C::*Setter)( const P& ); + + ListSerializer( const char* name, Getter gf, Setter sf ) + : _name(name), _getter(gf), _setter(sf) {} + + virtual const std::string& getName() const { return _name; } + + virtual bool read( InputStream& is, osg::Object& obj ) + { + C& object = OBJECT_CAST(obj); + unsigned int size = 0; + P list; + if ( is.isBinary() ) + { + is >> size; + for ( unsigned int i=0; i> value; + list.push_back( value ); + } + if ( size>0 ) (object.*_setter)( list ); + } + else if ( is.matchString(_name) ) + { + is >> size; + if ( size>0 ) is >> is.BEGIN_BRACKET; + for ( unsigned int i=0; i> value; + list.push_back( value ); + } + if ( size>0 ) + { + is >> is.END_BRACKET; + (object.*_setter)( list ); + } + } + return true; + } + + virtual bool write( OutputStream& os, const osg::Object& obj ) + { + const C& object = OBJECT_CAST(obj); + const P& list = (object.*_getter)(); + unsigned int size = (unsigned int)list.size(); + if ( os.isBinary() ) + { + os << size; + for ( ConstIterator itr=list.begin(); + itr!=list.end(); ++itr ) + { + os << (*itr); + } + } + else if ( size>0 ) + { + os << os.PROPERTY((_name).c_str()) << size << os.BEGIN_BRACKET << std::endl; + for ( ConstIterator itr=list.begin(); + itr!=list.end(); ++itr ) + { + os << (*itr); + } + os << std::endl; + os << os.END_BRACKET << std::endl; + } + return true; + } + +public: + std::string _name; + Getter _getter; + Setter _setter; +}; + +// ADDING MANIPULATORS +#define ADD_SERIALIZER(S) \ + wrapper->addSerializer( (S) ) + +#define ADD_USER_SERIALIZER(PROP) \ + wrapper->addSerializer( new osgDB::UserSerializer( \ + #PROP, &check##PROP, &read##PROP, &write##PROP), osgDB::BaseSerializer::RW_USER ) + +#define ADD_BOOL_SERIALIZER(PROP, DEF) \ + wrapper->addSerializer( new osgDB::PropByValSerializer< MyClass, bool >( \ + #PROP, DEF, &MyClass::get##PROP, &MyClass::set##PROP), osgDB::BaseSerializer::RW_BOOL ) + +#define ADD_CHAR_SERIALIZER(PROP, DEF) \ + wrapper->addSerializer( new osgDB::PropByValSerializer< MyClass, char >( \ + #PROP, DEF, &MyClass::get##PROP, &MyClass::set##PROP), osgDB::BaseSerializer::RW_CHAR ) + +#define ADD_UCHAR_SERIALIZER(PROP, DEF) \ + wrapper->addSerializer( new osgDB::PropByValSerializer< MyClass, unsigned char >( \ + #PROP, DEF, &MyClass::get##PROP, &MyClass::set##PROP), osgDB::BaseSerializer::RW_UCHAR ) + +#define ADD_SHORT_SERIALIZER(PROP, DEF) \ + wrapper->addSerializer( new osgDB::PropByValSerializer< MyClass, short >( \ + #PROP, DEF, &MyClass::get##PROP, &MyClass::set##PROP), osgDB::BaseSerializer::RW_SHORT ) + +#define ADD_USHORT_SERIALIZER(PROP, DEF) \ + wrapper->addSerializer( new osgDB::PropByValSerializer< MyClass, unsigned short >( \ + #PROP, DEF, &MyClass::get##PROP, &MyClass::set##PROP), osgDB::BaseSerializer::RW_USHORT ) + +#define ADD_HEXSHORT_SERIALIZER(PROP, DEF) \ + wrapper->addSerializer( new osgDB::PropByValSerializer< MyClass, unsigned short >( \ + #PROP, DEF, &MyClass::get##PROP, &MyClass::set##PROP, true), osgDB::BaseSerializer::RW_USHORT ) + +#define ADD_INT_SERIALIZER(PROP, DEF) \ + wrapper->addSerializer( new osgDB::PropByValSerializer< MyClass, int >( \ + #PROP, DEF, &MyClass::get##PROP, &MyClass::set##PROP), osgDB::BaseSerializer::RW_INT ) + +#define ADD_UINT_SERIALIZER(PROP, DEF) \ + wrapper->addSerializer( new osgDB::PropByValSerializer< MyClass, unsigned int >( \ + #PROP, DEF, &MyClass::get##PROP, &MyClass::set##PROP), osgDB::BaseSerializer::RW_UINT ) + +#define ADD_GLINT_SERIALIZER(PROP, DEF) \ + wrapper->addSerializer( new osgDB::PropByValSerializer< MyClass, GLint >( \ + #PROP, ((int)(DEF)), &MyClass::get##PROP, &MyClass::set##PROP), osgDB::BaseSerializer::RW_INT ) + +#define ADD_HEXINT_SERIALIZER(PROP, DEF) \ + wrapper->addSerializer( new osgDB::PropByValSerializer< MyClass, unsigned int >( \ + #PROP, DEF, &MyClass::get##PROP, &MyClass::set##PROP, true), osgDB::BaseSerializer::RW_UINT ) + +#define ADD_FLOAT_SERIALIZER(PROP, DEF) \ + wrapper->addSerializer( new osgDB::PropByValSerializer< MyClass, float >( \ + #PROP, DEF, &MyClass::get##PROP, &MyClass::set##PROP), osgDB::BaseSerializer::RW_FLOAT ) + +#define ADD_DOUBLE_SERIALIZER(PROP, DEF) \ + wrapper->addSerializer( new osgDB::PropByValSerializer< MyClass, double >( \ + #PROP, DEF, &MyClass::get##PROP, &MyClass::set##PROP), osgDB::BaseSerializer::RW_DOUBLE ) + +#define ADD_REF_BOOL_SERIALIZER(PROP, DEF) \ + wrapper->addSerializer( new osgDB::PropByRefSerializer< MyClass, bool >( \ + #PROP, DEF, &MyClass::get##PROP, &MyClass::set##PROP), osgDB::BaseSerializer::RW_BOOL ) + +#define ADD_REF_CHAR_SERIALIZER(PROP, DEF) \ + wrapper->addSerializer( new osgDB::PropByRefSerializer< MyClass, char >( \ + #PROP, DEF, &MyClass::get##PROP, &MyClass::set##PROP), osgDB::BaseSerializer::RW_CHAR ) + +#define ADD_REF_UCHAR_SERIALIZER(PROP, DEF) \ + wrapper->addSerializer( new osgDB::PropByRefSerializer< MyClass, unsigned char >( \ + #PROP, DEF, &MyClass::get##PROP, &MyClass::set##PROP), osgDB::BaseSerializer::RW_UCHAR ) + +#define ADD_REF_SHORT_SERIALIZER(PROP, DEF) \ + wrapper->addSerializer( new osgDB::PropByRefSerializer< MyClass, short >( \ + #PROP, DEF, &MyClass::get##PROP, &MyClass::set##PROP), osgDB::BaseSerializer::RW_SHORT ) + +#define ADD_REF_USHORT_SERIALIZER(PROP, DEF) \ + wrapper->addSerializer( new osgDB::PropByRefSerializer< MyClass, unsigned short >( \ + #PROP, DEF, &MyClass::get##PROP, &MyClass::set##PROP), osgDB::BaseSerializer::RW_USHORT ) + +#define ADD_REF_HEXSHORT_SERIALIZER(PROP, DEF) \ + wrapper->addSerializer( new osgDB::PropByRefSerializer< MyClass, unsigned short >( \ + #PROP, DEF, &MyClass::get##PROP, &MyClass::set##PROP, true), osgDB::BaseSerializer::RW_USHORT ) + +#define ADD_REF_INT_SERIALIZER(PROP, DEF) \ + wrapper->addSerializer( new osgDB::PropByRefSerializer< MyClass, int >( \ + #PROP, DEF, &MyClass::get##PROP, &MyClass::set##PROP), osgDB::BaseSerializer::RW_INT ) + +#define ADD_REF_UINT_SERIALIZER(PROP, DEF) \ + wrapper->addSerializer( new osgDB::PropByRefSerializer< MyClass, unsigned int >( \ + #PROP, DEF, &MyClass::get##PROP, &MyClass::set##PROP), osgDB::BaseSerializer::RW_UINT ) + +#define ADD_REF_GLINT_SERIALIZER(PROP, DEF) \ + wrapper->addSerializer( new osgDB::PropByRefSerializer< MyClass, GLint >( \ + #PROP, ((int)(DEF)), &MyClass::get##PROP, &MyClass::set##PROP), osgDB::BaseSerializer::RW_INT ) + +#define ADD_REF_HEXINT_SERIALIZER(PROP, DEF) \ + wrapper->addSerializer( new osgDB::PropByRefSerializer< MyClass, unsigned int >( \ + #PROP, DEF, &MyClass::get##PROP, &MyClass::set##PROP, true), osgDB::BaseSerializer::RW_UINT ) + +#define ADD_REF_FLOAT_SERIALIZER(PROP, DEF) \ + wrapper->addSerializer( new osgDB::PropByRefSerializer< MyClass, float >( \ + #PROP, DEF, &MyClass::get##PROP, &MyClass::set##PROP), osgDB::BaseSerializer::RW_FLOAT ) + +#define ADD_REF_DOUBLE_SERIALIZER(PROP, DEF) \ + wrapper->addSerializer( new osgDB::PropByRefSerializer< MyClass, double >( \ + #PROP, DEF, &MyClass::get##PROP, &MyClass::set##PROP), osgDB::BaseSerializer::RW_DOUBLE ) + + +#define ADD_VEC2B_SERIALIZER(PROP, DEF) \ + wrapper->addSerializer( new osgDB::PropByRefSerializer< MyClass, osg::Vec2b >( \ + #PROP, DEF, &MyClass::get##PROP, &MyClass::set##PROP), osgDB::BaseSerializer::RW_VEC2B ) + +#define ADD_VEC2UB_SERIALIZER(PROP, DEF) \ + wrapper->addSerializer( new osgDB::PropByRefSerializer< MyClass, osg::Vec2ub >( \ + #PROP, DEF, &MyClass::get##PROP, &MyClass::set##PROP), osgDB::BaseSerializer::RW_VEC2UB ) + +#define ADD_VEC2S_SERIALIZER(PROP, DEF) \ + wrapper->addSerializer( new osgDB::PropByRefSerializer< MyClass, osg::Vec2s >( \ + #PROP, DEF, &MyClass::get##PROP, &MyClass::set##PROP), osgDB::BaseSerializer::RW_VEC2S ) + +#define ADD_VEC2US_SERIALIZER(PROP, DEF) \ + wrapper->addSerializer( new osgDB::PropByRefSerializer< MyClass, osg::Vec2us >( \ + #PROP, DEF, &MyClass::get##PROP, &MyClass::set##PROP), osgDB::BaseSerializer::RW_VEC2US ) + +#define ADD_VEC2I_SERIALIZER(PROP, DEF) \ + wrapper->addSerializer( new osgDB::PropByRefSerializer< MyClass, osg::Vec2i >( \ + #PROP, DEF, &MyClass::get##PROP, &MyClass::set##PROP), osgDB::BaseSerializer::RW_VEC2I ) + +#define ADD_VEC2UI_SERIALIZER(PROP, DEF) \ + wrapper->addSerializer( new osgDB::PropByRefSerializer< MyClass, osg::Vec2ui >( \ + #PROP, DEF, &MyClass::get##PROP, &MyClass::set##PROP), osgDB::BaseSerializer::RW_VEC2UI ) + +#define ADD_VEC2F_SERIALIZER(PROP, DEF) \ + wrapper->addSerializer( new osgDB::PropByRefSerializer< MyClass, osg::Vec2f >( \ + #PROP, DEF, &MyClass::get##PROP, &MyClass::set##PROP), osgDB::BaseSerializer::RW_VEC2F ) + +#define ADD_VEC2D_SERIALIZER(PROP, DEF) \ + wrapper->addSerializer( new osgDB::PropByRefSerializer< MyClass, osg::Vec2d >( \ + #PROP, DEF, &MyClass::get##PROP, &MyClass::set##PROP), osgDB::BaseSerializer::RW_VEC2D ) + +#define ADD_VEC2_SERIALIZER(PROP, DEF) ADD_VEC2F_SERIALIZER(PROP, DEF) + + +#define ADD_VEC3B_SERIALIZER(PROP, DEF) \ + wrapper->addSerializer( new osgDB::PropByRefSerializer< MyClass, osg::Vec3b >( \ + #PROP, DEF, &MyClass::get##PROP, &MyClass::set##PROP), osgDB::BaseSerializer::RW_VEC3B ) + +#define ADD_VEC3UB_SERIALIZER(PROP, DEF) \ + wrapper->addSerializer( new osgDB::PropByRefSerializer< MyClass, osg::Vec3ub >( \ + #PROP, DEF, &MyClass::get##PROP, &MyClass::set##PROP), osgDB::BaseSerializer::RW_VEC3UB ) + +#define ADD_VEC3S_SERIALIZER(PROP, DEF) \ + wrapper->addSerializer( new osgDB::PropByRefSerializer< MyClass, osg::Vec3s >( \ + #PROP, DEF, &MyClass::get##PROP, &MyClass::set##PROP), osgDB::BaseSerializer::RW_VEC3S ) + +#define ADD_VEC3US_SERIALIZER(PROP, DEF) \ + wrapper->addSerializer( new osgDB::PropByRefSerializer< MyClass, osg::Vec3us >( \ + #PROP, DEF, &MyClass::get##PROP, &MyClass::set##PROP), osgDB::BaseSerializer::RW_VEC3US ) + +#define ADD_VEC3I_SERIALIZER(PROP, DEF) \ + wrapper->addSerializer( new osgDB::PropByRefSerializer< MyClass, osg::Vec3i >( \ + #PROP, DEF, &MyClass::get##PROP, &MyClass::set##PROP), osgDB::BaseSerializer::RW_VEC3I ) + +#define ADD_VEC3UI_SERIALIZER(PROP, DEF) \ + wrapper->addSerializer( new osgDB::PropByRefSerializer< MyClass, osg::Vec3ui >( \ + #PROP, DEF, &MyClass::get##PROP, &MyClass::set##PROP), osgDB::BaseSerializer::RW_VEC3UI ) + +#define ADD_VEC3F_SERIALIZER(PROP, DEF) \ + wrapper->addSerializer( new osgDB::PropByRefSerializer< MyClass, osg::Vec3f >( \ + #PROP, DEF, &MyClass::get##PROP, &MyClass::set##PROP), osgDB::BaseSerializer::RW_VEC3F ) + +#define ADD_VEC3D_SERIALIZER(PROP, DEF) \ + wrapper->addSerializer( new osgDB::PropByRefSerializer< MyClass, osg::Vec3d >( \ + #PROP, DEF, &MyClass::get##PROP, &MyClass::set##PROP), osgDB::BaseSerializer::RW_VEC3D ) + +#define ADD_VEC3_SERIALIZER(PROP, DEF) ADD_VEC3F_SERIALIZER(PROP, DEF) + +#define ADD_VEC4B_SERIALIZER(PROP, DEF) \ + wrapper->addSerializer( new osgDB::PropByRefSerializer< MyClass, osg::Vec4b >( \ + #PROP, DEF, &MyClass::get##PROP, &MyClass::set##PROP), osgDB::BaseSerializer::RW_VEC4B ) + +#define ADD_VEC4UB_SERIALIZER(PROP, DEF) \ + wrapper->addSerializer( new osgDB::PropByRefSerializer< MyClass, osg::Vec4ub >( \ + #PROP, DEF, &MyClass::get##PROP, &MyClass::set##PROP), osgDB::BaseSerializer::RW_VEC4UB ) + +#define ADD_VEC4S_SERIALIZER(PROP, DEF) \ + wrapper->addSerializer( new osgDB::PropByRefSerializer< MyClass, osg::Vec4s >( \ + #PROP, DEF, &MyClass::get##PROP, &MyClass::set##PROP), osgDB::BaseSerializer::RW_VEC4S ) + +#define ADD_VEC4US_SERIALIZER(PROP, DEF) \ + wrapper->addSerializer( new osgDB::PropByRefSerializer< MyClass, osg::Vec4us >( \ + #PROP, DEF, &MyClass::get##PROP, &MyClass::set##PROP), osgDB::BaseSerializer::RW_VEC4US ) + +#define ADD_VEC4I_SERIALIZER(PROP, DEF) \ + wrapper->addSerializer( new osgDB::PropByRefSerializer< MyClass, osg::Vec4i >( \ + #PROP, DEF, &MyClass::get##PROP, &MyClass::set##PROP), osgDB::BaseSerializer::RW_VEC4I ) + +#define ADD_VEC4UI_SERIALIZER(PROP, DEF) \ + wrapper->addSerializer( new osgDB::PropByRefSerializer< MyClass, osg::Vec4ui >( \ + #PROP, DEF, &MyClass::get##PROP, &MyClass::set##PROP), osgDB::BaseSerializer::RW_VEC4UI ) + +#define ADD_VEC4F_SERIALIZER(PROP, DEF) \ + wrapper->addSerializer( new osgDB::PropByRefSerializer< MyClass, osg::Vec4f >( \ + #PROP, DEF, &MyClass::get##PROP, &MyClass::set##PROP), osgDB::BaseSerializer::RW_VEC4F ) + +#define ADD_VEC4D_SERIALIZER(PROP, DEF) \ + wrapper->addSerializer( new osgDB::PropByRefSerializer< MyClass, osg::Vec4d >( \ + #PROP, DEF, &MyClass::get##PROP, &MyClass::set##PROP), osgDB::BaseSerializer::RW_VEC4D ) + +#define ADD_VEC4_SERIALIZER(PROP, DEF) ADD_VEC4F_SERIALIZER(PROP, DEF) + +#define ADD_QUAT_SERIALIZER(PROP, DEF) \ + wrapper->addSerializer( new osgDB::PropByRefSerializer< MyClass, osg::Quat >( \ + #PROP, DEF, &MyClass::get##PROP, &MyClass::set##PROP), osgDB::BaseSerializer::RW_QUAT ) + +#define ADD_PLANE_SERIALIZER(PROP, DEF) \ + wrapper->addSerializer( new osgDB::PropByRefSerializer< MyClass, osg::Plane >( \ + #PROP, DEF, &MyClass::get##PROP, &MyClass::set##PROP), osgDB::BaseSerializer::RW_PLANE ) + +#define ADD_MATRIXF_SERIALIZER(PROP, DEF) \ + wrapper->addSerializer( new osgDB::PropByRefSerializer< MyClass, osg::Matrixf >( \ + #PROP, DEF, &MyClass::get##PROP, &MyClass::set##PROP), osgDB::BaseSerializer::RW_MATRIXF ) + +#define ADD_MATRIXD_SERIALIZER(PROP, DEF) \ + wrapper->addSerializer( new osgDB::PropByRefSerializer< MyClass, osg::Matrixd >( \ + #PROP, DEF, &MyClass::get##PROP, &MyClass::set##PROP), osgDB::BaseSerializer::RW_MATRIXD ) + +#define ADD_MATRIX_SERIALIZER(PROP, DEF) \ + wrapper->addSerializer( new osgDB::MatrixSerializer< MyClass >( \ + #PROP, DEF, &MyClass::get##PROP, &MyClass::set##PROP), osgDB::BaseSerializer::RW_MATRIX ) + +#define ADD_GLENUM_SERIALIZER(PROP, TYPE, DEF) \ + wrapper->addSerializer( new osgDB::GLenumSerializer< MyClass, TYPE >( \ + #PROP, DEF, &MyClass::get##PROP, &MyClass::set##PROP), osgDB::BaseSerializer::RW_GLENUM ) + +#define ADD_STRING_SERIALIZER(PROP, DEF) \ + wrapper->addSerializer( new osgDB::StringSerializer< MyClass >( \ + #PROP, DEF, &MyClass::get##PROP, &MyClass::set##PROP), osgDB::BaseSerializer::RW_STRING ) + +#define ADD_OBJECT_SERIALIZER(PROP, TYPE, DEF) \ + wrapper->addSerializer( new osgDB::ObjectSerializer< MyClass, TYPE >( \ + #PROP, DEF, &MyClass::get##PROP, &MyClass::set##PROP), osgDB::BaseSerializer::RW_OBJECT ) + +#define ADD_IMAGE_SERIALIZER(PROP, TYPE, DEF) \ + wrapper->addSerializer( new osgDB::ImageSerializer< MyClass, TYPE >( \ + #PROP, DEF, &MyClass::get##PROP, &MyClass::set##PROP), osgDB::BaseSerializer::RW_IMAGE ) + +#define ADD_LIST_SERIALIZER(PROP, TYPE) \ + wrapper->addSerializer( new osgDB::ListSerializer< MyClass, TYPE >( \ + #PROP, &MyClass::get##PROP, &MyClass::set##PROP), osgDB::BaseSerializer::RW_LIST ) + +#define BEGIN_ENUM_SERIALIZER(PROP, DEF) \ + { typedef osgDB::EnumSerializer MySerializer; \ + osg::ref_ptr serializer = new MySerializer( \ + #PROP, MyClass::DEF, &MyClass::get##PROP, &MyClass::set##PROP) + +#define BEGIN_ENUM_SERIALIZER2(PROP, TYPE, DEF) \ + { typedef osgDB::EnumSerializer MySerializer; \ + osg::ref_ptr serializer = new MySerializer( \ + #PROP, MyClass::DEF, &MyClass::get##PROP, &MyClass::set##PROP) + +#define BEGIN_ENUM_SERIALIZER3(PROP, DEF) \ + { typedef osgDB::EnumSerializer MySerializer; \ + osg::ref_ptr serializer = new MySerializer( \ + #PROP, MyClass::DEF, &MyClass::get##PROP, &MyClass::set##PROP) + +#define BEGIN_ENUM_SERIALIZER4(PROPERTIES_CLASS, PROP, DEF) \ + { typedef osgDB::EnumSerializer MySerializer; \ + osg::ref_ptr serializer = new MySerializer( \ + #PROP, PROPERTIES_CLASS::DEF, &MyClass::get##PROP, &MyClass::set##PROP) + +#define ADD_ENUM_VALUE(VALUE) \ + serializer->add(#VALUE, MyClass::VALUE) + +#define ADD_ENUM_CLASS_VALUE(CLASS, VALUE) \ + serializer->add(#VALUE, CLASS::VALUE) + +#define END_ENUM_SERIALIZER() \ + wrapper->addSerializer(serializer.get(), osgDB::BaseSerializer::RW_ENUM); } + +// VERSION CONTROL OPERATORS +#define UPDATE_TO_VERSION(VER) \ + wrapper->setUpdatedVersion( (VER) ); + +#define UPDATE_TO_VERSION_SCOPED(VER) \ + osgDB::UpdateWrapperVersionProxy uwvp(wrapper, (VER)); + +#define REMOVE_SERIALIZER(PROP) \ + wrapper->markSerializerAsRemoved( #PROP ); + +} + +#endif diff --git a/libs/include/android/osgDB/SharedStateManager b/libs/include/android/osgDB/SharedStateManager new file mode 100755 index 0000000..08c30df --- /dev/null +++ b/libs/include/android/osgDB/SharedStateManager @@ -0,0 +1,141 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGDB_SHAREDSTATEMANAGER +#define OSGDB_SHAREDSTATEMANAGER 1 + + +#include +#include + +#include + +#include + +#include + + +namespace osgDB { + + class OSGDB_EXPORT SharedStateManager : public osg::NodeVisitor + { + public: + + enum ShareMode + { + SHARE_NONE = 0, + SHARE_STATIC_TEXTURES = 1<<0, + SHARE_UNSPECIFIED_TEXTURES = 1<<1, + SHARE_DYNAMIC_TEXTURES = 1<<2, + SHARE_STATIC_STATESETS = 1<<3, + SHARE_UNSPECIFIED_STATESETS = 1<<4, + SHARE_DYNAMIC_STATESETS = 1<<5, + SHARE_TEXTURES = SHARE_STATIC_TEXTURES | SHARE_UNSPECIFIED_TEXTURES, + SHARE_STATESETS = SHARE_STATIC_STATESETS | SHARE_UNSPECIFIED_STATESETS, + SHARE_ALL = SHARE_TEXTURES | + SHARE_STATESETS + }; + + SharedStateManager(unsigned int mode = SHARE_ALL); + + META_NodeVisitor(osgDB, SharedStateManager) + + void setShareMode(unsigned int mode); + + unsigned int getShareMode() { return _shareMode; } + + // Call right after each unload and before Registry cache prune. + void prune(); + + // Call right after each load + void share(osg::Node *node, OpenThreads::Mutex *mt=0); + + void apply(osg::Node& node); + void apply(osg::Geode& geode); + + // Answers the question "Will this state set be eliminated by + // the SharedStateManager because an equivalent one has been + // seen already?" Safe to call from the pager thread. + bool isShared(osg::StateSet* stateSet); + + bool isShared(osg::Texture* texture); + + void releaseGLObjects(osg::State* state ) const; + + protected: + + inline bool shareTexture(osg::Object::DataVariance variance) + { + return _shareTexture[variance]; + } + + inline bool shareStateSet(osg::Object::DataVariance variance) + { + return _shareStateSet[variance]; + } + + + void process(osg::StateSet* ss, osg::Object* parent); + osg::StateAttribute *find(osg::StateAttribute *sa); + osg::StateSet *find(osg::StateSet *ss); + void setStateSet(osg::StateSet* ss, osg::Object* object); + void shareTextures(osg::StateSet* ss); + + struct CompareStateAttributes + { + bool operator()(const osg::ref_ptr& lhs, + const osg::ref_ptr& rhs) const + { + return *lhs < *rhs; + } + }; + + struct CompareStateSets + { + bool operator()(const osg::ref_ptr& lhs, + const osg::ref_ptr& rhs) const + { + return lhs->compare(*rhs, true) < 0; + } + }; + + // Lists of shared objects + typedef std::set< osg::ref_ptr, CompareStateAttributes > TextureSet; + TextureSet _sharedTextureList; + + typedef std::set< osg::ref_ptr, CompareStateSets > StateSetSet; + StateSetSet _sharedStateSetList; + + // Temporary lists just to avoid unnecessary find calls + typedef std::pair TextureSharePair; + typedef std::map TextureTextureSharePairMap; + TextureTextureSharePairMap tmpSharedTextureList; + + typedef std::pair StateSetSharePair; + typedef std::map StateSetStateSetSharePairMap; + StateSetStateSetSharePairMap tmpSharedStateSetList; + + unsigned int _shareMode; + bool _shareTexture[3]; + bool _shareStateSet[3]; + + // Share connection mutex + + OpenThreads::Mutex *_mutex; + // Mutex for doing isShared queries from other threads + mutable OpenThreads::Mutex _listMutex; + }; + +} + +#endif diff --git a/libs/include/android/osgDB/StreamOperator b/libs/include/android/osgDB/StreamOperator new file mode 100755 index 0000000..3c352e2 --- /dev/null +++ b/libs/include/android/osgDB/StreamOperator @@ -0,0 +1,137 @@ +#ifndef OSGDB_STREAMOPERATOR +#define OSGDB_STREAMOPERATOR + +#include +#include +#include +#include +#include + +namespace osgDB +{ + +// forward declare +class InputStream; + +class OSGDB_EXPORT OutputIterator : public osg::Referenced +{ +public: + OutputIterator() : _out(0), _supportBinaryBrackets(false) {} + virtual ~OutputIterator() {} + + void setStream( std::ostream* ostream ) { _out = ostream; } + std::ostream* getStream() { return _out; } + const std::ostream* getStream() const { return _out; } + + void setSupportBinaryBrackets( bool b ) { _supportBinaryBrackets = b; } + bool getSupportBinaryBrackets() const { return _supportBinaryBrackets; } + + virtual bool isBinary() const = 0; + + virtual void writeBool( bool b ) = 0; + virtual void writeChar( char c ) = 0; + virtual void writeUChar( unsigned char c ) = 0; + virtual void writeShort( short s ) = 0; + virtual void writeUShort( unsigned short s ) = 0; + virtual void writeInt( int i ) = 0; + virtual void writeUInt( unsigned int i ) = 0; + virtual void writeLong( long l ) = 0; + virtual void writeULong( unsigned long l ) = 0; + virtual void writeFloat( float f ) = 0; + virtual void writeDouble( double d ) = 0; + virtual void writeString( const std::string& s ) = 0; + virtual void writeStream( std::ostream& (*fn)(std::ostream&) ) = 0; + virtual void writeBase( std::ios_base& (*fn)(std::ios_base&) ) = 0; + + virtual void writeGLenum( const ObjectGLenum& value ) = 0; + virtual void writeProperty( const ObjectProperty& prop ) = 0; + virtual void writeMark( const ObjectMark& mark ) = 0; + virtual void writeCharArray( const char* s, unsigned int size ) = 0; + virtual void writeWrappedString( const std::string& str ) = 0; + + virtual void flush() { _out->flush(); } + +protected: + // Return true if the manipulator is std::endl + bool isEndl( std::ostream& (*fn)(std::ostream&) ) + { +#ifdef __sun + // What a mess, but solaris does not like taking the address below + std::stringstream ss; + ss << fn; + std::string s = ss.str(); + return !s.empty() && s[0] == '\n'; +#else + return fn==static_cast(std::endl); +#endif + } + + std::ostream* _out; + bool _supportBinaryBrackets; +}; + +class OSGDB_EXPORT InputIterator : public osg::Referenced +{ +public: + InputIterator() : _in(0), _inputStream(0), _byteSwap(0), _supportBinaryBrackets(false), _failed(false) {} + virtual ~InputIterator() {} + + void setStream( std::istream* istream ) { _in = istream; } + std::istream* getStream() { return _in; } + const std::istream* getStream() const { return _in; } + + void setInputStream( InputStream* inputStream) { _inputStream = inputStream; } + InputStream* getInputStream() { return _inputStream; } + const InputStream* getInputStream() const { return _inputStream; } + + void setByteSwap(int byteSwap) { _byteSwap = byteSwap; } + int getByteSwap() const { return _byteSwap; } + + void setSupportBinaryBrackets( bool b ) { _supportBinaryBrackets = b; } + bool getSupportBinaryBrackets() const { return _supportBinaryBrackets; } + + void checkStream() const { if (_in->rdstate()&_in->failbit) _failed = true; } + bool isFailed() const { return _failed; } + + virtual bool isBinary() const = 0; + + virtual void readBool( bool& b ) = 0; + virtual void readChar( char& c ) = 0; + virtual void readSChar( signed char& c ) = 0; + virtual void readUChar( unsigned char& c ) = 0; + virtual void readShort( short& s ) = 0; + virtual void readUShort( unsigned short& s ) = 0; + virtual void readInt( int& i ) = 0; + virtual void readUInt( unsigned int& i ) = 0; + virtual void readLong( long& l ) = 0; + virtual void readULong( unsigned long& l ) = 0; + virtual void readFloat( float& f ) = 0; + virtual void readDouble( double& d ) = 0; + virtual void readString( std::string& s ) = 0; + virtual void readStream( std::istream& (*fn)(std::istream&) ) = 0; + virtual void readBase( std::ios_base& (*fn)(std::ios_base&) ) = 0; + + virtual void readGLenum( ObjectGLenum& value ) = 0; + virtual void readProperty( ObjectProperty& prop ) = 0; + virtual void readMark( ObjectMark& mark ) = 0; + virtual void readCharArray( char* s, unsigned int size ) = 0; + virtual void readWrappedString( std::string& str ) = 0; + + virtual bool matchString( const std::string& /*str*/ ) { return false; } + virtual void advanceToCurrentEndBracket() {} + + void throwException( const std::string& msg ); + + void readComponentArray( char* s, unsigned int numElements, unsigned int numComponentsPerElements, unsigned int componentSizeInBytes); + +protected: + std::istream* _in; + osgDB::InputStream* _inputStream; + int _byteSwap; + bool _supportBinaryBrackets; + mutable bool _failed; +}; + +} + +#endif diff --git a/libs/include/android/osgDB/Version b/libs/include/android/osgDB/Version new file mode 100755 index 0000000..089c97c --- /dev/null +++ b/libs/include/android/osgDB/Version @@ -0,0 +1,46 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGDB_VERSION +#define OSGDB_VERSION 1 + +#include + +extern "C" { + +/** + * osgDBGetVersion() returns the library version number. + * Numbering convention : OpenSceneGraph-1.0 will return 1.0 from osgDBGetVersion. + * + * This C function can be also used to check for the existence of the OpenSceneGraph + * library using autoconf and its m4 macro AC_CHECK_LIB. + * + * Here is the code to add to your configure.in: + \verbatim + # + # Check for the OpenSceneGraph (OSG) DB library + # + AC_CHECK_LIB(osg, osgDBGetVersion, , + [AC_MSG_ERROR(OpenSceneGraph DB library not found. See http://www.openscenegraph.org)],) + \endverbatim +*/ +extern OSGDB_EXPORT const char* osgDBGetVersion(); + +/** + * getLibraryName() returns the library name in human friendly form. +*/ +extern OSGDB_EXPORT const char* osgDBGetLibraryName(); + +} + +#endif diff --git a/libs/include/android/osgDB/WriteFile b/libs/include/android/osgDB/WriteFile new file mode 100755 index 0000000..d6ad7b8 --- /dev/null +++ b/libs/include/android/osgDB/WriteFile @@ -0,0 +1,130 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGDB_WRITEFILE +#define OSGDB_WRITEFILE 1 + +#include +#include +#include + +#include +#include + +#include + +namespace osgDB { + +/** Write an osg::Object to file. + * Return true on success, + * return false on failure. + * Use the Options object to control cache operations and file search paths in osgDB::Registry. + * The osgDB::Registry is used to load the appropriate ReaderWriter plugin + * for the filename extension, and this plugin then handles the request + * to write the specified file.*/ +extern OSGDB_EXPORT bool writeObjectFile(const osg::Object& object, const std::string& filename, const Options* options ); + +/** Write an osg::Object to file. + * Return true on success, + * return false on failure. + * The osgDB::Registry is used to load the appropriate ReaderWriter plugin + * for the filename extension, and this plugin then handles the request + * to write the specified file.*/ +inline bool writeObjectFile(const osg::Object& object, const std::string& filename) +{ + return writeObjectFile( object, filename, Registry::instance()->getOptions() ); +} + +/** Write an osg::Image to file. + * Return true on success, + * return false on failure. + * Use the Options object to control cache operations and file search paths in osgDB::Registry. + * The osgDB::Registry is used to load the appropriate ReaderWriter plugin + * for the filename extension, and this plugin then handles the request + * to write the specified file.*/ +extern OSGDB_EXPORT bool writeImageFile(const osg::Image& image, const std::string& filename, const Options* options ); + +/** Write an osg::Image to file. + * Return true on success, + * return false on failure. + * The osgDB::Registry is used to load the appropriate ReaderWriter plugin + * for the filename extension, and this plugin then handles the request + * to write the specified file.*/ +inline bool writeImageFile(const osg::Image& image, const std::string& filename) +{ + return writeImageFile( image, filename, Registry::instance()->getOptions() ); +} + +/** Write an osg::HeightField to file. + * Return true on success, + * return false on failure. + * Use the Options object to control cache operations and file search paths in osgDB::Registry. + * The osgDB::Registry is used to load the appropriate ReaderWriter plugin + * for the filename extension, and this plugin then handles the request + * to write the specified file.*/ +extern OSGDB_EXPORT bool writeHeightFieldFile(const osg::HeightField& hf, const std::string& filename, const Options* options ); + +/** Write an osg::HeightField to file. + * Return true on success, + * return false on failure. + * The osgDB::Registry is used to load the appropriate ReaderWriter plugin + * for the filename extension, and this plugin then handles the request + * to write the specified file.*/ +inline bool writeHeightFieldFile(const osg::HeightField& hf, const std::string& filename) +{ + return writeHeightFieldFile( hf, filename, Registry::instance()->getOptions() ); +} + +/** Write an osg::Node to file. + * Return true on success, + * return false on failure. + * Use the Options object to control cache operations and file search paths in osgDB::Registry. + * The osgDB::Registry is used to load the appropriate ReaderWriter plugin + * for the filename extension, and this plugin then handles the request + * to write the specified file.*/ +extern OSGDB_EXPORT bool writeNodeFile(const osg::Node& node, const std::string& filename, const Options* options ); + +/** Write an osg::Node to file. + * Return true on success, + * return false on failure. + * The osgDB::Registry is used to load the appropriate ReaderWriter plugin + * for the filename extension, and this plugin then handles the request + * to write the specified file.*/ +inline bool writeNodeFile(const osg::Node& node, const std::string& filename) +{ + return writeNodeFile( node, filename, Registry::instance()->getOptions() ); +} + +/** Write an osg::Shader to file. + * Return true on success, + * return false on failure. + * Use the Options object to control cache operations and file search paths in osgDB::Registry. + * The osgDB::Registry is used to load the appropriate ReaderWriter plugin + * for the filename extension, and this plugin then handles the request + * to write the specified file.*/ +extern OSGDB_EXPORT bool writeShaderFile(const osg::Shader& shader, const std::string& filename, const Options* options ); + +/** Write an osg::Shader to file. + * Return true on success, + * return false on failure. + * The osgDB::Registry is used to load the appropriate ReaderWriter plugin + * for the filename extension, and this plugin then handles the request + * to write the specified file.*/ +inline bool writeShaderFile(const osg::Shader& shader, const std::string& filename) +{ + return writeShaderFile( shader, filename, Registry::instance()->getOptions() ); +} + +} + +#endif diff --git a/libs/include/android/osgDB/XmlParser b/libs/include/android/osgDB/XmlParser new file mode 100755 index 0000000..e95f0e2 --- /dev/null +++ b/libs/include/android/osgDB/XmlParser @@ -0,0 +1,156 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2009 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGDB_XML_PARSER +#define OSGDB_XML_PARSER 1 + +#include + +namespace osgDB { + +// forward declare +class XmlNode; + +/** read an Xml file, find the file in Options DataFilePathList.*/ +extern OSGDB_EXPORT XmlNode* readXmlFile(const std::string& filename,const Options* options); + +/** read an Xml file, find the file in osgDB::Registry's eaderWriter::Options DataFilePathList.*/ +inline XmlNode* readXmlFile(const std::string& filename) +{ + return readXmlFile(filename, osgDB::Registry::instance()->getOptions()); +} + +/** read an Xml from from an istream.*/ +extern OSGDB_EXPORT XmlNode* readXmlStream(std::istream& fin); + +extern OSGDB_EXPORT std::string trimEnclosingSpaces(const std::string& str); + +/** XmlNode class for very basic reading and writing of xml files.*/ +class OSGDB_EXPORT XmlNode : public osg::Referenced +{ + public: + + XmlNode(); + + enum NodeType + { + UNASSIGNED, + ATOM, + NODE, + GROUP, + ROOT, + COMMENT, + INFORMATION + }; + + typedef std::map< std::string, std::string > Properties; + typedef std::vector< osg::ref_ptr > Children; + + NodeType type; + std::string name; + std::string contents; + Properties properties; + Children children; + + std::string getTrimmedContents() const { return trimEnclosingSpaces(contents); } + + public: + + class OSGDB_EXPORT ControlMap + { + public: + ControlMap(); + + typedef std::map< std::string, int > ControlToCharacterMap; + typedef std::map< int, std::string> CharacterToControlMap; + + void addControlToCharacter(const std::string& control, int c); + + ControlToCharacterMap _controlToCharacterMap; + CharacterToControlMap _characterToControlMap; + + private: + + void setUpControlMappings(); + + }; + + class OSGDB_EXPORT Input : public ControlMap + { + public: + + Input(); + Input(const Input&); + + ~Input(); + + typedef std::string::size_type size_type; + + void open(const std::string& filename); + void attach(std::istream& istream); + + void readAllDataIntoBuffer(); + + operator bool () const { return _currentPos<_buffer.size(); } + + size_type currentPosition() const { return _currentPos; } + + int get() { if (_currentPos<_buffer.size()) return _buffer[_currentPos++]; else return -1; } + + int operator [] (size_type i) const { if ((_currentPos+i)<_buffer.size()) return _buffer[_currentPos+i]; else return -1; } + + void operator ++ () { if (_currentPos<_buffer.size()) ++_currentPos; } + + void operator += (size_type n) { if ((_currentPos+n)<_buffer.size()) _currentPos+=n; else _currentPos = _buffer.size(); } + + void skipWhiteSpace(); + + std::string substr(size_type pos, size_type n=std::string::npos) { return (_currentPos<_buffer.size()) ? _buffer.substr(_currentPos+pos,n) : std::string(); } + + size_type find(const std::string& str) + { + if (_currentPos<_buffer.size()) + { + size_type pos = _buffer.find(str, _currentPos); + if (pos==std::string::npos) return std::string::npos; + else return pos-_currentPos; + } else return std::string::npos; + } + + bool match(const std::string& str) { return (_currentPos<_buffer.size()) ? _buffer.compare(_currentPos, str.size(), str)==0 : false; } + + private: + + size_type _currentPos; + + std::ifstream _fin; + std::string _buffer; + + }; + + bool read(Input& input); + bool write(std::ostream& fout, const std::string& indent = "") const; + + bool write(const ControlMap& controlMap, std::ostream& fout, const std::string& indent = "") const; + bool writeString(const ControlMap& controlMap, std::ostream& fout, const std::string& str) const; + + protected: + + bool writeChildren(const ControlMap& controlMap, std::ostream& fout, const std::string& indent) const; + bool writeProperties(const ControlMap& controlMap, std::ostream& fout) const; + + bool readAndReplaceControl(std::string& contents, Input& input); +}; + +} +#endif diff --git a/libs/include/android/osgDB/fstream b/libs/include/android/osgDB/fstream new file mode 100755 index 0000000..cb3c1bd --- /dev/null +++ b/libs/include/android/osgDB/fstream @@ -0,0 +1,60 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2008 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGDB_FSTREAM +#define OSGDB_FSTREAM 1 + +#include +#include + +#include + + +namespace osgDB +{ + +/** +* Convenience function for fstream open , std::ifstream, and std::ofstream to +* automatically handle UTF-8 to UTF-16 filename conversion. Always use one +* of these classes in any OpenSceneGraph code instead of the STL equivalent. +*/ + +void OSGDB_EXPORT open(std::fstream& fs, const char* filename,std::ios_base::openmode mode); + +class OSGDB_EXPORT ifstream : public std::ifstream +{ +public: + ifstream(); + explicit ifstream(const char* filename, + std::ios_base::openmode mode = std::ios_base::in); + ~ifstream(); + + void open(const char* filename, + std::ios_base::openmode mode = std::ios_base::in); +}; + +class OSGDB_EXPORT ofstream : public std::ofstream +{ +public: + ofstream(); + explicit ofstream(const char* filename, + std::ios_base::openmode mode = std::ios_base::out); + ~ofstream(); + + void open(const char* filename, + std::ios_base::openmode mode = std::ios_base::out); +}; + +} + +#endif diff --git a/libs/include/android/osgFX/AnisotropicLighting b/libs/include/android/osgFX/AnisotropicLighting new file mode 100755 index 0000000..caff002 --- /dev/null +++ b/libs/include/android/osgFX/AnisotropicLighting @@ -0,0 +1,122 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +//osgFX - Copyright (C) 2003 Marco Jez + +#ifndef OSGFX_ANISOTROPICLIGHTING_ +#define OSGFX_ANISOTROPICLIGHTING_ + +#include +#include + +#include +#include + +namespace osgFX +{ + + /** + This single-pass effect implements a sort of anisotropic + lighting that replaces the standard OpenGL lighting model. + The final color of vertices is not computed directly, it is + the result of a texture lookup on a user-supplied lighting + image map. A vertex program is used to compute the s and t + texture coordinates as follows: s = (N dot H) ; t = (N dot L) + where N is the vertex normal, L is the light-to-vertex vector, + H is the half-way vector. This is a good example of how you + can use the State::getInitialViewMatrix() method to retrieve + the view matrix and perform view-dependant effects without + fakes of any kind. + This effect requires the ARB_vertex_program extension. + */ + class OSGFX_EXPORT AnisotropicLighting: public Effect { + public: + AnisotropicLighting(); + AnisotropicLighting(const AnisotropicLighting& copy, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY); + + META_Effect(osgFX, AnisotropicLighting, + + "Anisotropic Lighting", + + "This single-pass effect implements a sort of anisotropic " + "lighting that replaces the standard OpenGL lighting model.\n" + "The final color of vertices is not computed directly, it is " + "the result of a texture lookup on a user-supplied lighting " + "image map. A vertex program is used to compute the s and t " + "texture coordinates as follows: s = (N dot H) ; t = (N dot L) " + "where N is the vertex normal, L is the light-to-vertex vector, " + "H is the half-way vector. This is a good example of how you " + "can use the State::getInitialViewMatrix() method to retrieve " + "the view matrix and perform view-dependant effects without " + "fakes of any kind.\n" + "This effect requires the ARB_vertex_program extension.", + + "Marco Jez"); + + + /** get the lighting map */ + inline osg::Image* getLightingMap(); + + /** get the const lighting map */ + inline const osg::Image* getLightingMap() const; + + /** set the lighting map */ + inline void setLightingMap(osg::Image* image); + + /** get the OpenGL light number */ + inline int getLightNumber() const; + + /** set the OpenGL light number that will be used in lighting computations */ + inline void setLightNumber(int n); + + protected: + virtual ~AnisotropicLighting() {} + AnisotropicLighting& operator=(const AnisotropicLighting&) { return *this; } + + bool define_techniques(); + + private: + int _lightnum; + osg::ref_ptr _texture; + }; + + // INLINE METHODS + + inline osg::Image* AnisotropicLighting::getLightingMap() + { + return _texture->getImage(); + } + + inline const osg::Image* AnisotropicLighting::getLightingMap() const + { + return _texture->getImage(); + } + + inline void AnisotropicLighting::setLightingMap(osg::Image* image) + { + _texture->setImage(image); + } + + inline int AnisotropicLighting::getLightNumber() const + { + return _lightnum; + } + + inline void AnisotropicLighting::setLightNumber(int n) + { + _lightnum = n; + dirtyTechniques(); + } + +} + +#endif diff --git a/libs/include/android/osgFX/BumpMapping b/libs/include/android/osgFX/BumpMapping new file mode 100755 index 0000000..c7819ba --- /dev/null +++ b/libs/include/android/osgFX/BumpMapping @@ -0,0 +1,198 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +//osgFX - Copyright (C) 2003 Marco Jez + +#ifndef OSGFX_BUMPMAPPING_ +#define OSGFX_BUMPMAPPING_ + +#include +#include + +#include +#include + +namespace osgFX +{ + + /** + This effect makes surfaces appear bumpy. Children nodes must use two textures, + one for diffuse color and one for the normal map (which can be created + from a height map with tools like nVIDIA's normal map generator). Furthermore, + tangent-space basis vectors must be created and assigned to each Geometry; this + can be done quickly by calling BumpMapping::prepareChildren(). Note that both + diffuse and normal map textures must have corresponding UV maps defined in + Geometry objects. + This effect defines a preferred technique which uses ARB vertex & fragment + programs, and a fallback technique which doesn't use fragment programs. The + latter is more limited though since it can't handle ambient and specular + components. + */ + class OSGFX_EXPORT BumpMapping: public Effect { + public: + BumpMapping(); + BumpMapping(const BumpMapping& copy, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY); + + META_Effect(osgFX, BumpMapping, + + "Bump Mapping", + + "This effect makes surfaces appear bumpy. Children nodes must use two textures, " + "one for diffuse color and one for the normal map (which can be created " + "from a height map with tools like nVIDIA's normal map generator). Furthermore, " + "tangent-space basis vectors must be created and assigned to each Geometry; this " + "can be done quickly by calling BumpMapping::prepareChildren(). Note that both " + "diffuse and normal map textures must have corresponding UV maps defined in " + "Geometry objects.\n" + "This effect defines a preferred technique which uses ARB vertex & fragment " + "programs, and a fallback technique which doesn't use fragment programs. The " + "latter is more limited though since it can't handle ambient and specular " + "components.", + + "Marco Jez"); + + + /** get the OpenGL light number */ + inline int getLightNumber() const; + + /** set the OpenGL light number that will be used in lighting computations */ + inline void setLightNumber(int n); + + /** get the texture unit that contains diffuse color texture. Default is 1 */ + inline int getDiffuseTextureUnit() const; + + /** set the texture unit that contains diffuse color texture. Default is 1 */ + inline void setDiffuseTextureUnit(int n); + + /** get the texture unit that contains normal map texture. Default is 0 */ + inline int getNormalMapTextureUnit() const; + + /** set the texture unit that contains normal map texture. Default is 0 */ + inline void setNormalMapTextureUnit(int n); + + /** get the diffuse color texture that overrides children's texture */ + inline osg::Texture2D* getOverrideDiffuseTexture(); + + /** get the const diffuse color texture that overrides children's texture */ + inline const osg::Texture2D* getOverrideDiffuseTexture() const; + + /** set the diffuse color texture that overrides children's texture */ + inline void setOverrideDiffuseTexture(osg::Texture2D* texture); + + /** get the normal map texture that overrides children's texture */ + inline osg::Texture2D* getOverrideNormalMapTexture(); + + /** get the const normal map texture that overrides children's texture */ + inline const osg::Texture2D* getOverrideNormalMapTexture() const; + + /** set the normal map texture that overrides children's texture */ + inline void setOverrideNormalMapTexture(osg::Texture2D* texture); + + /** + prepare a Geometry for bump lighting. Tangent-space basis vectors are + generated and attached to the geometry as vertex attribute arrays. + */ + void prepareGeometry(osg::Geometry* geo); + + /** prepare a Node for bump lighting, calling prepareGeometry() for each Geometry */ + void prepareNode(osg::Node* node); + + /** prepare children for bump lighting. Actually calls prepareNode() for each child */ + void prepareChildren(); + + /** set up a demo environment with predefined diffuse and normal maps, as well as texture coordinates */ + void setUpDemo(); + + protected: + virtual ~BumpMapping() {} + BumpMapping &operator=(const BumpMapping &) { return *this; } + + bool define_techniques(); + + private: + int _lightnum; + int _diffuse_unit; + int _normal_unit; + osg::ref_ptr _diffuse_tex; + osg::ref_ptr _normal_tex; + }; + + // INLINE METHODS + + inline int BumpMapping::getLightNumber() const + { + return _lightnum; + } + + inline void BumpMapping::setLightNumber(int n) + { + _lightnum = n; + dirtyTechniques(); + } + + inline int BumpMapping::getDiffuseTextureUnit() const + { + return _diffuse_unit; + } + + inline void BumpMapping::setDiffuseTextureUnit(int n) + { + _diffuse_unit = n; + dirtyTechniques(); + } + + inline int BumpMapping::getNormalMapTextureUnit() const + { + return _normal_unit; + } + + inline void BumpMapping::setNormalMapTextureUnit(int n) + { + _normal_unit = n; + dirtyTechniques(); + } + + inline osg::Texture2D* BumpMapping::getOverrideDiffuseTexture() + { + return _diffuse_tex.get(); + } + + inline const osg::Texture2D* BumpMapping::getOverrideDiffuseTexture() const + { + return _diffuse_tex.get(); + } + + inline void BumpMapping::setOverrideDiffuseTexture(osg::Texture2D* texture) + { + _diffuse_tex = texture; + dirtyTechniques(); + } + + inline osg::Texture2D* BumpMapping::getOverrideNormalMapTexture() + { + return _normal_tex.get(); + } + + inline const osg::Texture2D* BumpMapping::getOverrideNormalMapTexture() const + { + return _normal_tex.get(); + } + + inline void BumpMapping::setOverrideNormalMapTexture(osg::Texture2D* texture) + { + _normal_tex = texture; + dirtyTechniques(); + } + +} + +#endif diff --git a/libs/include/android/osgFX/Cartoon b/libs/include/android/osgFX/Cartoon new file mode 100755 index 0000000..361a22e --- /dev/null +++ b/libs/include/android/osgFX/Cartoon @@ -0,0 +1,122 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +//osgFX - Copyright (C) 2003 Marco Jez + +#ifndef OSGFX_CARTOON_ +#define OSGFX_CARTOON_ + +#include +#include + +#include +#include + +namespace osgFX +{ + + /** + This effect implements a technique called 'Cel-Shading' to produce a + cartoon-style (non photorealistic) rendering. Two passes are required: + the first one draws solid surfaces, the second one draws the outlines. + A vertex program is used to setup texture coordinates for a sharp lighting + texture on unit 0 which is generated on-the-fly. + This effect requires the ARB_vertex_program extension. + */ + class OSGFX_EXPORT Cartoon: public Effect { + public: + Cartoon(); + Cartoon(const Cartoon& copy, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY); + + // effect class informations + META_Effect( + osgFX, + Cartoon, + + "Cartoon", + + "This effect implements a technique called 'Cel-Shading' to produce a " + "cartoon-style (non photorealistic) rendering. Two passes are required: " + "the first one draws solid surfaces, the second one draws the outlines. " + "A vertex program is used to setup texture coordinates for a sharp lighting " + "texture on unit 0 which is generated on-the-fly.\n" + "This effect requires the ARB_vertex_program extension " + "or OpenGL Shading Language.", + + "Marco Jez; OGLSL port by Mike Weiblen"); + + /** get the outline color */ + inline const osg::Vec4& getOutlineColor() const; + + /** set the outline color */ + inline void setOutlineColor(const osg::Vec4& color); + + /** get the outline line width */ + inline float getOutlineLineWidth() const; + + /** set the outline line width */ + inline void setOutlineLineWidth(float w); + + /** get the OpenGL light number */ + inline int getLightNumber() const; + + /** set the OpenGL light number that will be used in lighting computations */ + inline void setLightNumber(int n); + + protected: + virtual ~Cartoon() {} + Cartoon& operator=(const Cartoon&) { return *this; } + + bool define_techniques(); + + private: + osg::ref_ptr _wf_mat; + osg::ref_ptr _wf_lw; + int _lightnum; + }; + + // INLINE METHODS + + inline const osg::Vec4& Cartoon::getOutlineColor() const + { + return _wf_mat->getEmission(osg::Material::FRONT_AND_BACK); + } + + inline void Cartoon::setOutlineColor(const osg::Vec4& color) + { + _wf_mat->setEmission(osg::Material::FRONT_AND_BACK, color); + } + + inline float Cartoon::getOutlineLineWidth() const + { + return _wf_lw->getWidth(); + } + + inline void Cartoon::setOutlineLineWidth(float w) + { + _wf_lw->setWidth(w); + } + + inline int Cartoon::getLightNumber() const + { + return _lightnum; + } + + inline void Cartoon::setLightNumber(int n) + { + _lightnum = n; + dirtyTechniques(); + } + +} + +#endif diff --git a/libs/include/android/osgFX/Effect b/libs/include/android/osgFX/Effect new file mode 100755 index 0000000..205e2e8 --- /dev/null +++ b/libs/include/android/osgFX/Effect @@ -0,0 +1,217 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +//osgFX - Copyright (C) 2003 Marco Jez + +#ifndef OSGFX__effect +#define OSGFX__effect + +#include +#include + +#include +#include +#include +#include +#include +#include + +#include + +/** + An helper macro that defines the methods like effectName() and effectDescription() + making them return the strings passed as parameters, after the usual library name + and class name. + */ +#define META_Effect(library, classname, effectname, effectdescription, effectauthor) \ + META_Node(library, classname) \ + virtual const char *effectName() const { return effectname; } \ + virtual const char *effectDescription() const { return effectdescription; } \ + virtual const char *effectAuthor() const { return effectauthor; } + + +namespace osgFX +{ + + /** + The base class for special effects. An effect is basically a collection of + state attributes and an interface for configuring them in a predefined + fashion. The Effect class does more however, as it handles multipass + rendering transparently and it allows more than one "technique" to be + defined. Each technique tries to implement the effect in a different way, + often using different OpenGL extensions. The active technique can be + selected either manually, with selectTechnique(), or automatically, in which + case the first technique that is supported by all active rendering contexts + is chosen. + If you are an Effect user, then simply use it as a node group. Create an + instance of your desired effect, add it to your scene graph and call its + addChild() method to add a child node as you would do with a Group. + If you are an Effect developer, you will have to implement the method + define_techniques() to define the different techniques that can be used + for obtaining the desired effect. In define_techniques() you will usually + create one or more instances of custom classes derived from Technique and + you will add them to the effect with addTechnique(). The order is important: + techniques added first will have higher priority and will be used first as + soon as all rendering contexts support it. + */ + class OSGFX_EXPORT Effect: public osg::Group { + public: + Effect(); + Effect(const Effect& copy, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY); + + virtual inline bool isSameKindAs(const osg::Object* obj) const { return dynamic_cast(obj) != NULL; } + virtual inline const char* libraryName() const { return "osgFX"; } + virtual inline const char* className() const { return "Effect"; } + + /** get the name of this Effect */ + virtual const char *effectName() const = 0; + + /** get a brief description of this Effect*/ + virtual const char *effectDescription() const = 0; + + /** get the effect author's name */ + virtual const char *effectAuthor() const = 0; + + /** get whether the effect is enabled or not */ + inline bool getEnabled() const; + + /** set whether the effect is enabled or not */ + inline void setEnabled(bool v); + + /** + optional: set effect parameters to produce a visually significant + result to be used in demo applications like osgfxbrowser. Default + is to do nothing. + */ + inline virtual void setUpDemo() {} + + /** get the number of techniques defined for this Effect */ + inline int getNumTechniques() const; + + /** get the i-th Technique */ + inline Technique* getTechnique(int i); + + /** get the i-th const Technique */ + inline const Technique* getTechnique(int i) const; + + /** get the index of the currently selected Technique */ + inline int getSelectedTechnique() const; + + enum TechniqueSelection { + AUTO_DETECT = -1 + }; + + /** select a technique or enable automatic detection */ + inline void selectTechnique(int i = AUTO_DETECT); + + /** custom traversal */ + virtual void traverse(osg::NodeVisitor& nv); + + /** default traversal */ + inline void inherited_traverse(osg::NodeVisitor& nv); + + protected: + virtual ~Effect(); + Effect &operator=(const Effect &) { return *this; } + + /** force rebuilding of techniques on next traversal */ + inline void dirtyTechniques(); + + /** add a technique to the Effect */ + inline void addTechnique(Technique* tech); + + /** + abstract method to be implemented in derived classes; its purpose + if to create the techniques that can be used for obtaining the + desired effect. You will usually call addTechnique() inside + this method. + */ + virtual bool define_techniques() = 0; + + private: + friend class Validator; + + bool _enabled; + + typedef std::vector > Technique_list; + Technique_list _techs; + + mutable osg::buffered_value _sel_tech; + + // use int instead of bool to avoid errors + mutable osg::buffered_value _tech_selected; + + int _global_sel_tech; + + bool _techs_defined; + + osg::ref_ptr _dummy_for_validation; + + void build_dummy_node(); + }; + + // INLINE METHODS + + inline bool Effect::getEnabled() const + { + return _enabled; + } + + inline void Effect::setEnabled(bool v) + { + _enabled = v; + } + + inline int Effect::getNumTechniques() const + { + return static_cast(_techs.size()); + } + + inline Technique* Effect::getTechnique(int i) + { + return _techs[i].get(); + } + + inline const Technique* Effect::getTechnique(int i) const + { + return _techs[i].get(); + } + + inline int Effect::getSelectedTechnique() const + { + return _global_sel_tech; + } + + inline void Effect::selectTechnique(int i) + { + _global_sel_tech = i; + } + + inline void Effect::addTechnique(Technique* tech) + { + _techs.push_back(tech); + } + + inline void Effect::dirtyTechniques() + { + _techs_defined = false; + } + + inline void Effect::inherited_traverse(osg::NodeVisitor& nv) + { + typedef osg::Group inherited; + inherited::traverse(nv); + } + +} + +#endif diff --git a/libs/include/android/osgFX/Export b/libs/include/android/osgFX/Export new file mode 100755 index 0000000..0268895 --- /dev/null +++ b/libs/include/android/osgFX/Export @@ -0,0 +1,40 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +//osgFX - Copyright (C) 2003 Marco Jez + +#ifndef OSGFX_EXPORT_ +#define OSGFX_EXPORT_ + +#if defined(_MSC_VER) || defined(__CYGWIN__) || defined(__MINGW32__) || defined( __BCPLUSPLUS__) || defined( __MWERKS__) + # if defined( OSG_LIBRARY_STATIC ) + # define OSGFX_EXPORT + # elif defined( OSGFX_LIBRARY ) + # define OSGFX_EXPORT __declspec(dllexport) + # else + # define OSGFX_EXPORT __declspec(dllimport) + # endif +#else + # define OSGFX_EXPORT +#endif + +/** + +\namespace osgFX + +The osgFX library is a NodeKit that extends the core scene graph to provide a special effects framework. +osgFX's framework allows multiple rendering techniques to be provide for each effect, thereby provide the use +appropriate rendering techniques for each different class of graphics hardware, i.e. support for both modern +programmable graphics hardware and still have standard OpenGL 1.1 support as a fallback. +*/ + +#endif diff --git a/libs/include/android/osgFX/MultiTextureControl b/libs/include/android/osgFX/MultiTextureControl new file mode 100755 index 0000000..659b1dd --- /dev/null +++ b/libs/include/android/osgFX/MultiTextureControl @@ -0,0 +1,53 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGFX_MULTITEXTURECONTROL +#define OSGFX_MULTITEXTURECONTROL + +#include + +#include + +namespace osgFX +{ + /** + This node provides control over the which texture units are active and the + blending weighting between them. + */ + class OSGFX_EXPORT MultiTextureControl: public osg::Group { + public: + + MultiTextureControl(); + MultiTextureControl(const MultiTextureControl& copy, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY); + + META_Node(osgFX, MultiTextureControl); + + void setTextureWeight(unsigned int unit, float weight); + + float getTextureWeight(unsigned int unit) const { return (unit<_textureWeightList.size()) ? _textureWeightList[unit] : 0.0f; } + + unsigned int getNumTextureWeights() const { return _textureWeightList.size(); } + + protected: + virtual ~MultiTextureControl() {} + MultiTextureControl& operator = (const MultiTextureControl&) { return *this; } + + void updateStateSet(); + + typedef std::vector TextureWeightList; + TextureWeightList _textureWeightList; + }; + +} + +#endif diff --git a/libs/include/android/osgFX/Outline b/libs/include/android/osgFX/Outline new file mode 100755 index 0000000..efd9703 --- /dev/null +++ b/libs/include/android/osgFX/Outline @@ -0,0 +1,97 @@ +// -*-c++-*- + +/* + * OpenSceneGraph - Copyright (C) 1998-2009 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. + */ + +/* + * osgFX::Outline - Copyright (C) 2004,2009 Ulrich Hertlein + */ + +#ifndef OSGFX_OUTLINE_ +#define OSGFX_OUTLINE_ + +#include +#include + +namespace osgFX +{ + /** + * Outline effect. + * This effect draws a stencil buffer-based outline around an object. + * Color and width of the outline can be modified. + * To function correctly the context must be setup with a stencil buffer + * and the stencil buffer must be cleared to zero before each render. + * + * osg::DisplaySettings::instance()->setMinimumNumStencilBits(1); + * camera->setClearMask(clearMask | GL_STENCIL_BUFFER_BIT); + * camera->setClearStencil(0); + */ + class OSGFX_EXPORT Outline : public Effect + { + public: + /// Constructor. + Outline(); + + /// Copy constructor. + Outline(const Outline& copy, const osg::CopyOp& op = osg::CopyOp::SHALLOW_COPY) : Effect(copy, op) { + _width = copy._width; + _color = copy._color; + _technique = copy._technique; + } + + // Effect class info + META_Effect(osgFX, Outline, "Outline", + "Stencil buffer based object outline effect.\n" + "This effect needs a properly setup stencil buffer.", + "Ulrich Hertlein"); + + /// Set outline width. + void setWidth(float w); + + /// Get outline width. + float getWidth() const { + return _width; + } + + /// Set outline color. + void setColor(const osg::Vec4& color); + + /// Get outline color. + const osg::Vec4& getColor() const { + return _color; + } + + protected: + /// Destructor. + virtual ~Outline() { + } + + /// Define available techniques. + bool define_techniques(); + + private: + /// Outline width. + float _width; + + /// Outline color. + osg::Vec4 _color; + + /// Technique. + class OutlineTechnique; + OutlineTechnique* _technique; + }; + +} + +#endif diff --git a/libs/include/android/osgFX/Registry b/libs/include/android/osgFX/Registry new file mode 100755 index 0000000..a504a22 --- /dev/null +++ b/libs/include/android/osgFX/Registry @@ -0,0 +1,92 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +//osgFX - Copyright (C) 2003 Marco Jez + +#ifndef OSGFX_REGISTRY_ +#define OSGFX_REGISTRY_ + +#include +#include + +#include + +#include +#include + +namespace osgFX +{ + + class OSGFX_EXPORT Registry : public osg::Referenced + { + public: + + struct Proxy { + Proxy(const Effect* effect): _effect(effect) + { + Registry::instance()->registerEffect(effect); + } + + ~Proxy() + { + Registry::instance()->removeEffect(_effect.get()); + } + private: + osg::ref_ptr _effect; + }; + + typedef std::map > EffectMap; + + static Registry* instance(); + + inline void registerEffect(const Effect* effect); + + inline void removeEffect(const Effect* effect); + + inline const EffectMap& getEffectMap() const; + + protected: + + // Registry is a singleton; constructor and destructor must be protected + Registry(); + ~Registry() {} + + private: + EffectMap _effects; + }; + + // INLINE METHODS + + + + inline const Registry::EffectMap& Registry::getEffectMap() const + { + return _effects; + } + + inline void Registry::registerEffect(const Effect* effect) + { + _effects[effect->effectName()] = effect; + } + + inline void Registry::removeEffect(const Effect* effect) + { + EffectMap::iterator itr = _effects.find(effect->effectName()); + if (itr != _effects.end()) + { + _effects.erase(itr); + } + } + +} + +#endif diff --git a/libs/include/android/osgFX/Scribe b/libs/include/android/osgFX/Scribe new file mode 100755 index 0000000..3b28285 --- /dev/null +++ b/libs/include/android/osgFX/Scribe @@ -0,0 +1,101 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +//osgFX - Copyright (C) 2003 Marco Jez + +#ifndef OSGFX_SCRIBE_ +#define OSGFX_SCRIBE_ + +#include +#include + +#include +#include + +namespace osgFX +{ + + /** + This is a two-passes effect; the first pass renders the subgraph as usual + while the second pass switches to wireframe mode, sets up lighting and + material to obtain a fixed (user-defined) color and then renders the subgraph. + This effect uses the PolygonOffset attribute to avoid Z-fighting, so it + requires at least OpenGL version 1.1. + */ + class OSGFX_EXPORT Scribe: public Effect { + public: + Scribe(); + Scribe(const Scribe& copy, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY); + + // effect class informations + META_Effect( + osgFX, + Scribe, + + "Scribe", + + "This is a two-passes effect; the first pass renders the subgraph as usual " + "while the second pass switches to wireframe mode, sets up lighting and " + "material to obtain a fixed (user-defined) color and then renders the subgraph.\n" + "This effect uses the PolygonOffset attribute to avoid Z-fighting, so it " + "requires at least OpenGL version 1.1.", + + "Marco Jez"); + + /** get the wireframe color */ + inline const osg::Vec4& getWireframeColor() const; + + /** set the wireframe color */ + inline void setWireframeColor(const osg::Vec4& color); + + /** get the wireframe line width */ + inline float getWireframeLineWidth() const; + + /** set the wireframe line width */ + inline void setWireframeLineWidth(float w); + + protected: + virtual ~Scribe() {} + Scribe& operator=(const Scribe&) { return *this; } + + bool define_techniques(); + + private: + osg::ref_ptr _wf_mat; + osg::ref_ptr _wf_lw; + }; + + // INLINE METHODS + + inline const osg::Vec4& Scribe::getWireframeColor() const + { + return _wf_mat->getEmission(osg::Material::FRONT_AND_BACK); + } + + inline void Scribe::setWireframeColor(const osg::Vec4& color) + { + _wf_mat->setEmission(osg::Material::FRONT_AND_BACK, color); + } + + inline float Scribe::getWireframeLineWidth() const + { + return _wf_lw->getWidth(); + } + + inline void Scribe::setWireframeLineWidth(float w) + { + _wf_lw->setWidth(w); + } + +} + +#endif diff --git a/libs/include/android/osgFX/SpecularHighlights b/libs/include/android/osgFX/SpecularHighlights new file mode 100755 index 0000000..5fa820f --- /dev/null +++ b/libs/include/android/osgFX/SpecularHighlights @@ -0,0 +1,138 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +//osgFX - Copyright (C) 2003 Marco Jez + +#ifndef OSGFX_SPECULARHIGHLIGHTS_ +#define OSGFX_SPECULARHIGHLIGHTS_ + +#include +#include + +namespace osgFX +{ + + /** + This effect applies additive specular highlights at fragment level (instead + of OpenGL's vertex-level lighting) by using a cube map and reflective texgen. + A texture matrix is computed to rotate the cube map automatically; this makes + the specular effect consistent with respect to view direction and light position. + The user can choose which light should be used to compute the texture matrix. + This effect requires the GL_ARB_texture_env_add extension and one of the cube map + extensions (GL_EXT_texture_cube_map, GL_ARB_texture_cube_map or OpenGL v1.3). + */ + class OSGFX_EXPORT SpecularHighlights: public Effect { + public: + SpecularHighlights(); + SpecularHighlights(const SpecularHighlights& copy, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY); + + META_Effect(osgFX, SpecularHighlights, + + "Specular Highlights", + + "This effect applies additive specular highlights at fragment level (instead " + "of OpenGL's vertex-level lighting) by using a cube map and reflective texgen. " + "A texture matrix is computed to rotate the cube map automatically; this makes " + "the specular effect consistent with respect to view direction and light position. " + "The user can choose which light should be used to compute the texture matrix.\n" + "This effect requires the GL_ARB_texture_env_add extension and one of the cube map " + "extensions (GL_EXT_texture_cube_map, GL_ARB_texture_cube_map or OpenGL v1.3).", + + "Marco Jez"); + + + /** get the OpenGL light number */ + inline int getLightNumber() const; + + /** set the OpenGL light number that will be used in lighting computations */ + inline void setLightNumber(int n); + + /** get the texture unit number */ + inline int getTextureUnit() const; + + /** set the texture unit that will be used to apply the cube map */ + inline void setTextureUnit(int n); + + /** get the specular color */ + inline const osg::Vec4& getSpecularColor() const; + + /** set the specular color */ + inline void setSpecularColor(const osg::Vec4& color); + + /** get the specular exponent */ + inline float getSpecularExponent() const; + + /** set the specular exponent */ + inline void setSpecularExponent(float e); + + protected: + virtual ~SpecularHighlights() {} + SpecularHighlights& operator=(const SpecularHighlights&) { return *this; } + + bool define_techniques(); + + private: + int _lightnum; + int _unit; + osg::Vec4 _color; + float _sexp; + }; + + // INLINE METHODS + + inline int SpecularHighlights::getLightNumber() const + { + return _lightnum; + } + + inline void SpecularHighlights::setLightNumber(int n) + { + _lightnum = n; + dirtyTechniques(); + } + + inline int SpecularHighlights::getTextureUnit() const + { + return _unit; + } + + inline void SpecularHighlights::setTextureUnit(int n) + { + _unit = n; + dirtyTechniques(); + } + + inline const osg::Vec4& SpecularHighlights::getSpecularColor() const + { + return _color; + } + + inline void SpecularHighlights::setSpecularColor(const osg::Vec4& color) + { + _color = color; + dirtyTechniques(); + } + + inline float SpecularHighlights::getSpecularExponent() const + { + return _sexp; + } + + inline void SpecularHighlights::setSpecularExponent(float e) + { + _sexp = e; + dirtyTechniques(); + } + +} + +#endif diff --git a/libs/include/android/osgFX/Technique b/libs/include/android/osgFX/Technique new file mode 100755 index 0000000..dac5fdb --- /dev/null +++ b/libs/include/android/osgFX/Technique @@ -0,0 +1,158 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +//osgFX - Copyright (C) 2003 Marco Jez + +#ifndef OSGFX_TECHNIQUE_ +#define OSGFX_TECHNIQUE_ + +#include + +#include +#include +#include +#include + +#include +#include + +/** + An helper macro that defines the methods techniqueName() and + techniqueDescription() making them return the strings passed as parameters. + */ +#define META_Technique(name, description) \ + inline virtual const char *techniqueName() { return name; } \ + inline virtual const char *techniqueDescription() { return description; } + + +namespace osgFX +{ + + class Effect; + + /** + This is the base class for effect techniques. A technique represents one + of the possible ways to implement a special effect. This base class is + abstract, you will have to subclass your own techniques for your custom + effects. + Derived classes will have to implement the define_passes() method to + configure the rendering pass(es) that make up the technique. Usually + you will create one StateSet object for each rendering pass and then + you'll call addPass(stateset). + The validate() method should return true if the technique is valid within + the current rendering context, false otherwise. The default implementation + of validate() calls getRequiredExtensions() and tests whether all required + extensions are supported or not, returning false if at least one extension + is not supported. + */ + class OSGFX_EXPORT Technique: public osg::Referenced { + public: + Technique(); + + /** get the name of this Technique */ + virtual const char *techniqueName() { return "Default"; } + + /** get a brief description of this Technique */ + virtual const char *techniqueDescription() { return "This is the default technique"; } + + /** + collect the GL extension strings which are required for this technique + to work properly. This method is called from the default implementation + of validate(). + */ + virtual void getRequiredExtensions(std::vector& /*extensions*/) const {}; + + /** + tests whether this technique is valid for the current rendering context. + The default behavior is to call getRequiredExtensions() and check for + extension availability. + */ + virtual bool validate(osg::State& ) const; + + /** get the number of rendering passes defined in this Technique */ + inline int getNumPasses() const; + + /** get the StateSet object associated to the i-th pass */ + inline osg::StateSet* getPassStateSet(int i); + + /** get the const StateSet object associated to the i-th pass */ + inline const osg::StateSet* getPassStateSet(int i) const; + + /** + traverse children with multipass if necessary. By default this method + simply calls the protected method traverse_implementation(); you can + override it to change the default behavior. + Don't call this method directly as it is called by osgFX::Effect + */ + inline virtual void traverse(osg::NodeVisitor& nv, Effect* fx); + + protected: + Technique(const Technique &): osg::Referenced() {} // copying is nonsense ;) + virtual ~Technique() {} + Technique &operator=(const Technique &) { return *this; } + + /** force rebuilding of pass nodes on next traversal */ + inline void dirtyPasses(); + + /** create a new pass node, add it to the technique and associate a StateSet */ + void addPass(osg::StateSet* ss = 0); + + /** optional: return a node that overrides the child node on a specified pass */ + inline virtual osg::Node* getOverrideChild(int) { return 0; } + + /** + define the rendering passes that make up this technique. You must + implement this method in derived classes to add the required passes. + */ + virtual void define_passes() = 0; + + /** + traverse children with multipass if necessary. Don't call this method + directly unless you are in a customized version of traverse(). + */ + void traverse_implementation(osg::NodeVisitor& nv, Effect* fx); + + private: + typedef std::vector > Pass_list; + Pass_list _passes; + }; + + // INLINE METHODS + + inline int Technique::getNumPasses() const + { + return static_cast(_passes.size()); + } + + inline osg::StateSet* Technique::getPassStateSet(int i) + { + return _passes[i].get(); + } + + inline const osg::StateSet* Technique::getPassStateSet(int i) const + { + return _passes[i].get(); + } + + inline void Technique::dirtyPasses() + { + _passes.clear(); + } + + inline void Technique::traverse(osg::NodeVisitor& nv, Effect* fx) + { + traverse_implementation(nv, fx); + } + +} + +#endif diff --git a/libs/include/android/osgFX/Validator b/libs/include/android/osgFX/Validator new file mode 100755 index 0000000..2450429 --- /dev/null +++ b/libs/include/android/osgFX/Validator @@ -0,0 +1,75 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +//osgFX - Copyright (C) 2003 Marco Jez + +#ifndef OSGFX_VALIDATOR_ +#define OSGFX_VALIDATOR_ + +#include + +#include +#include + +#include + +namespace osgFX +{ + + /** + This class is used internally by osgFX::Effect to choose between different + techniques dynamically. The apply() method will call each technique's + validate() method and store the results in a buffered array. The Effect + class will then choose the first technique that could be validated in all + active rendering contexts. + */ + class OSGFX_EXPORT Validator: public osg::StateAttribute { + public: + + Validator(); + Validator(Effect* effect); + Validator(const Validator& copy, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY); + + META_StateAttribute(osgFX, Validator, VALIDATOR); + + void apply(osg::State& state) const; + void compileGLObjects(osg::State& state) const; + + inline int compare(const osg::StateAttribute& sa) const; + + inline void disable() { _effect = 0; } + + protected: + virtual ~Validator() {} + Validator& operator=(const Validator&) { return *this; } + + private: + mutable Effect* _effect; + }; + + // INLINE METHODS + + inline int Validator::compare(const osg::StateAttribute& sa) const + { + // check the types are equal and then create the rhs variable + //used by the COMPARE_StateAttribute_Parameter macros below. + COMPARE_StateAttribute_Types(Validator,sa) + + // compare parameters + COMPARE_StateAttribute_Parameter(_effect) + + return 0; + } + +} + +#endif diff --git a/libs/include/android/osgFX/Version b/libs/include/android/osgFX/Version new file mode 100755 index 0000000..0cf66b2 --- /dev/null +++ b/libs/include/android/osgFX/Version @@ -0,0 +1,46 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGFX_VERSION +#define OSGFX_VERSION 1 + +#include + +extern "C" { + +/** + * osgFXGetVersion() returns the library version number. + * Numbering convention : OpenSceneGraph-1.0 will return 1.0 from osgFXGetVersion. + * + * This C function can be also used to check for the existence of the OpenSceneGraph + * library using autoconf and its m4 macro AC_CHECK_LIB. + * + * Here is the code to add to your configure.in: + \verbatim + # + # Check for the OpenSceneGraph (OSG) FX library + # + AC_CHECK_LIB(osg, osgFXGetVersion, , + [AC_MSG_ERROR(OpenSceneGraph FX library not found. See http://www.openscenegraph.org)],) + \endverbatim +*/ +extern OSGFX_EXPORT const char* osgFXGetVersion(); + +/** + * getLibraryName() returns the library name in human friendly form. +*/ +extern OSGFX_EXPORT const char* osgFXGetLibraryName(); + +} + +#endif diff --git a/libs/include/android/osgGA/AnimationPathManipulator b/libs/include/android/osgGA/AnimationPathManipulator new file mode 100755 index 0000000..4e4efab --- /dev/null +++ b/libs/include/android/osgGA/AnimationPathManipulator @@ -0,0 +1,121 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGGA_ANIMATION_PATH_MANIPULATOR +#define OSGGA_ANIMATION_PATH_MANIPULATOR 1 + +#include +#include +#include + +namespace osgGA{ + +// +// The AnimationPathManipulator is a Matrix Manipulator that reads an +// animation path from a file and plays it back. The file is expected +// to be ascii and a succession of lines with 8 floating point values +// per line. The succession of values are: +// time px py pz ax ay az aw +// where: +// time = elapsed time in seconds from the beginning of the animation +// px py pz = World position in cartesian coordinates +// ax ay az aw = Orientation (attitude) defined as a quaternion + +class OSGGA_EXPORT AnimationPathManipulator : public CameraManipulator +{ + public: + + AnimationPathManipulator( osg::AnimationPath* animationPath=0 ); + + AnimationPathManipulator( const std::string& filename ); + + virtual const char* className() const { return "AnimationPath"; } + + void setTimeScale(double s) { _timeScale = s; } + double getTimeScale() const { return _timeScale; } + + void setTimeOffset(double o) { _timeOffset = o; } + double getTimeOffset() const { return _timeOffset; } + + struct AnimationCompletedCallback : public virtual osg::Referenced + { + virtual void completed(const AnimationPathManipulator* apm) = 0; + }; + + void setAnimationCompletedCallback(AnimationCompletedCallback* acc) { _animationCompletedCallback = acc; } + AnimationCompletedCallback* getAnimationCompletedCallback() { return _animationCompletedCallback.get(); } + const AnimationCompletedCallback* getAnimationCompletedCallback() const { return _animationCompletedCallback.get(); } + + void setPrintOutTimingInfo(bool printOutTimingInfo) { _printOutTimingInfo=printOutTimingInfo; } + bool getPrintOutTimingInfo() const { return _printOutTimingInfo; } + + /** set the position of the matrix manipulator using a 4x4 Matrix.*/ + virtual void setByMatrix(const osg::Matrixd& matrix) { _matrix = matrix; } + + /** set the position of the matrix manipulator using a 4x4 Matrix.*/ + virtual void setByInverseMatrix(const osg::Matrixd& matrix) { _matrix.invert(matrix); } + + /** get the position of the manipulator as 4x4 Matrix.*/ + virtual osg::Matrixd getMatrix() const { return _matrix; } + + /** get the position of the manipulator as a inverse matrix of the manipulator, typically used as a model view matrix.*/ + virtual osg::Matrixd getInverseMatrix() const { return osg::Matrixd::inverse(_matrix); } + + + void setAnimationPath( osg::AnimationPath* animationPath ) { _animationPath=animationPath; } + + osg::AnimationPath* getAnimationPath() { return _animationPath.get(); } + + const osg::AnimationPath* getAnimationPath() const { return _animationPath.get(); } + + bool valid() const { return _animationPath.valid(); } + + void init(const GUIEventAdapter& ea,GUIActionAdapter& us); + + void home(const GUIEventAdapter& ea,GUIActionAdapter& us); + void home(double currentTime); + + virtual bool handle(const GUIEventAdapter& ea,GUIActionAdapter& us); + + /** Get the keyboard and mouse usage of this manipulator.*/ + virtual void getUsage(osg::ApplicationUsage& usage) const; + + protected: + + bool _valid; + + bool _printOutTimingInfo; + + void handleFrame( double time ); + + osg::ref_ptr _animationPath; + + double _timeOffset; + double _timeScale; + + osg::ref_ptr _animationCompletedCallback; + + double _pauseTime; + bool _isPaused; + + double _realStartOfTimedPeriod; + double _animStartOfTimedPeriod; + int _numOfFramesSinceStartOfTimedPeriod; + + osg::Matrixd _matrix; + +}; + +} + +#endif diff --git a/libs/include/android/osgGA/CameraManipulator b/libs/include/android/osgGA/CameraManipulator new file mode 100755 index 0000000..761dbd0 --- /dev/null +++ b/libs/include/android/osgGA/CameraManipulator @@ -0,0 +1,192 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGGA_CameraManipulator +#define OSGGA_CameraManipulator 1 + +#include +#include +#include + +#include + +#include +#include +#include +#include + +namespace osgGA{ + +#define NEW_HOME_POSITION + +/** + +CameraManipulator is an abstract base class defining the interface, and a certain +amount of default functionality, for classes which wish to control OSG cameras +in response to GUI events. + +*/ +class OSGGA_EXPORT CameraManipulator : public GUIEventHandler +{ + typedef GUIEventHandler inherited; + + public: + + // We are not using META_Object as this is abstract class. + // Use META_Object(osgGA,YourManipulator); in your descendant non-abstract classes. + virtual const char* className() const { return "CameraManipulator"; } + + /** callback class to use to allow matrix manipulators to query the application for the local coordinate frame.*/ + class CoordinateFrameCallback : public osg::Referenced + { + public: + virtual osg::CoordinateFrame getCoordinateFrame(const osg::Vec3d& position) const = 0; + protected: + virtual ~CoordinateFrameCallback() {} + }; + + /** set the coordinate frame which callback tells the manipulator which way is up, east and north.*/ + virtual void setCoordinateFrameCallback(CoordinateFrameCallback* cb) { _coordinateFrameCallback = cb; } + + /** get the coordinate frame callback which tells the manipulator which way is up, east and north.*/ + CoordinateFrameCallback* getCoordinateFrameCallback() { return _coordinateFrameCallback.get(); } + + /** get the coordinate frame callback which tells the manipulator which way is up, east and north.*/ + const CoordinateFrameCallback* getCoordinateFrameCallback() const { return _coordinateFrameCallback.get(); } + + /** get the coordinate frame.*/ + osg::CoordinateFrame getCoordinateFrame(const osg::Vec3d& position) const + { + if (_coordinateFrameCallback.valid()) return _coordinateFrameCallback->getCoordinateFrame(position); + return osg::CoordinateFrame(); + } + + osg::Vec3d getSideVector(const osg::CoordinateFrame& cf) const { return osg::Vec3d(cf(0,0),cf(0,1),cf(0,2)); } + osg::Vec3d getFrontVector(const osg::CoordinateFrame& cf) const { return osg::Vec3d(cf(1,0),cf(1,1),cf(1,2)); } + osg::Vec3d getUpVector(const osg::CoordinateFrame& cf) const { return osg::Vec3d(cf(2,0),cf(2,1),cf(2,2)); } + + /** set the position of the matrix manipulator using a 4x4 Matrix.*/ + virtual void setByMatrix(const osg::Matrixd& matrix) = 0; + + /** set the position of the matrix manipulator using a 4x4 Matrix.*/ + virtual void setByInverseMatrix(const osg::Matrixd& matrix) = 0; + + /** get the position of the manipulator as 4x4 Matrix.*/ + virtual osg::Matrixd getMatrix() const = 0; + + /** get the position of the manipulator as a inverse matrix of the manipulator, typically used as a model view matrix.*/ + virtual osg::Matrixd getInverseMatrix() const = 0; + + /** update the camera for the current frame, typically called by the viewer classes. + Default implementation simply set the camera view matrix. */ + virtual void updateCamera(osg::Camera& camera) { camera.setViewMatrix(getInverseMatrix()); } + + /** Get the FusionDistanceMode. Used by SceneView for setting up stereo convergence.*/ + virtual osgUtil::SceneView::FusionDistanceMode getFusionDistanceMode() const { return osgUtil::SceneView::PROPORTIONAL_TO_SCREEN_DISTANCE; } + + /** Get the FusionDistanceValue. Used by SceneView for setting up stereo convergence.*/ + virtual float getFusionDistanceValue() const { return 1.0f; } + + /** Set the mask to use when set up intersection traversal such as used in manipulators that follow terrain or have collision detection. + * The intersection traversal mask is useful for controlling what parts of the scene graph should be used for intersection purposes.*/ + void setIntersectTraversalMask(unsigned int mask) { _intersectTraversalMask = mask; } + + /** Get the mask to use when set up intersection traversal such as used in manipulators that follow terrain or have collision detection.*/ + unsigned int getIntersectTraversalMask() const { return _intersectTraversalMask; } + + /** + Attach a node to the manipulator, automatically detaching any previously attached node. + setNode(NULL) detaches previous nodes. + May be ignored by manipulators which do not require a reference model. + */ + virtual void setNode(osg::Node*) {} + + /** Return const node if attached.*/ + virtual const osg::Node* getNode() const { return NULL; } + + /** Return node if attached.*/ + virtual osg::Node* getNode() { return NULL; } + + /** Manually set the home position, and set the automatic compute of home position. */ + virtual void setHomePosition(const osg::Vec3d& eye, const osg::Vec3d& center, const osg::Vec3d& up, bool autoComputeHomePosition=false) + { + setAutoComputeHomePosition(autoComputeHomePosition); + _homeEye = eye; + _homeCenter = center; + _homeUp = up; + } + + /** Get the manually set home position. */ + virtual void getHomePosition(osg::Vec3d& eye, osg::Vec3d& center, osg::Vec3d& up) const + { + eye = _homeEye; + center = _homeCenter; + up = _homeUp; + } + + /** Set whether the automatic compute of the home position is enabled.*/ + virtual void setAutoComputeHomePosition(bool flag) { _autoComputeHomePosition = flag; } + + /** Get whether the automatic compute of the home position is enabled.*/ + bool getAutoComputeHomePosition() const { return _autoComputeHomePosition; } + + /** Compute the home position.*/ + virtual void computeHomePosition(const osg::Camera *camera = NULL, bool useBoundingBox = false); + + /** + Move the camera to the default position. + May be ignored by manipulators if home functionality is not appropriate. + */ + virtual void home(const GUIEventAdapter& ,GUIActionAdapter&) {} + + /** + Move the camera to the default position. + This version does not require GUIEventAdapter and GUIActionAdapter so may be + called from somewhere other than a handle() method in GUIEventHandler. Application + must be aware of implications. + */ + virtual void home(double /*currentTime*/) {} + + /** + Start/restart the manipulator. + FIXME: what does this actually mean? Provide examples. + */ + virtual void init(const GUIEventAdapter& ,GUIActionAdapter&) {} + + /** Handle events, return true if handled, false otherwise. */ + virtual bool handle(const GUIEventAdapter& ea,GUIActionAdapter& us); + + protected: + + CameraManipulator(); + CameraManipulator(const CameraManipulator& mm, const osg::CopyOp& copyOp = osg::CopyOp::SHALLOW_COPY); + + virtual ~CameraManipulator(); + + std::string getManipulatorName() const; + + unsigned int _intersectTraversalMask; + + bool _autoComputeHomePosition; + + osg::Vec3d _homeEye; + osg::Vec3d _homeCenter; + osg::Vec3d _homeUp; + + osg::ref_ptr _coordinateFrameCallback; + +}; + +} + +#endif diff --git a/libs/include/android/osgGA/CameraViewSwitchManipulator b/libs/include/android/osgGA/CameraViewSwitchManipulator new file mode 100755 index 0000000..fd6fca7 --- /dev/null +++ b/libs/include/android/osgGA/CameraViewSwitchManipulator @@ -0,0 +1,79 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGGA_VIEWLISTMANIPULATOR +#define OSGGA_VIEWLISTMANIPULATOR 1 + +#include +#include +#include + +namespace osgGA{ + +class OSGGA_EXPORT CameraViewSwitchManipulator : public CameraManipulator +{ + public: + CameraViewSwitchManipulator() {} + + virtual const char* className() const { return "CameraViewSwitcher"; } + + /** set the position of the matrix manipulator using a 4x4 Matrix.*/ + virtual void setByMatrix(const osg::Matrixd& /*matrix*/) {} + + /** set the position of the matrix manipulator using a 4x4 Matrix.*/ + virtual void setByInverseMatrix(const osg::Matrixd& /*matrix*/) {} + + /** get the position of the manipulator as 4x4 Matrix.*/ + virtual osg::Matrixd getMatrix() const; + + /** get the position of the manipulator as a inverse matrix of the manipulator, typically used as a model view matrix.*/ + virtual osg::Matrixd getInverseMatrix() const; + + + /** Attach a node to the manipulator. + Automatically detaches previously attached node. + setNode(NULL) detaches previously nodes. + Is ignored by manipulators which do not require a reference model.*/ + virtual void setNode(osg::Node*); + + /** Return node if attached.*/ + virtual const osg::Node* getNode() const { return _node.get();} + + /** Return node if attached.*/ + virtual osg::Node* getNode() { return _node.get();} + + /** Start/restart the manipulator.*/ + virtual void init(const GUIEventAdapter& /*ea*/,GUIActionAdapter& /*aa*/) { _currentView = 0; } + + /** handle events, return true if handled, false otherwise.*/ + virtual bool handle(const GUIEventAdapter& ea,GUIActionAdapter& us); + + /** Get the keyboard and mouse usage of this manipulator.*/ + virtual void getUsage(osg::ApplicationUsage& usage) const; + + typedef std::vector< osg::ref_ptr > CameraViewList; + + protected: + + virtual ~CameraViewSwitchManipulator() {} + + osg::ref_ptr _node; + + CameraViewList _cameraViews; + unsigned int _currentView; +}; + +} + +#endif + diff --git a/libs/include/android/osgGA/Device b/libs/include/android/osgGA/Device new file mode 100755 index 0000000..d7cfc4d --- /dev/null +++ b/libs/include/android/osgGA/Device @@ -0,0 +1,65 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGGA_EVENTSOURCE +#define OSGGA_EVENTSOURCE 1 + +#include + +namespace osgGA { + +/** + * Device base class from abstracting away from devices/windows that can generate events. + */ +class OSGGA_EXPORT Device : public osg::Object +{ + public: + enum { + UNKNOWN = 0, + RECEIVE_EVENTS = 1, + SEND_EVENTS = 2 + } Capabilities; + + Device(); + Device(const Device& es, const osg::CopyOp& copyop); + + META_Object(osgGA,Device); + + int getCapabilities() const { return _capabilities; } + + virtual bool checkEvents() { return _eventQueue.valid() ? !(getEventQueue()->empty()) : false; } + virtual void sendEvent(const GUIEventAdapter& ea); + virtual void sendEvents(const EventQueue::Events& events); + + void setEventQueue(osgGA::EventQueue* eventQueue) { _eventQueue = eventQueue; } + osgGA::EventQueue* getEventQueue() { return _eventQueue.get(); } + const osgGA::EventQueue* getEventQueue() const { return _eventQueue.get(); } + + protected: + void setCapabilities(int capabilities) { _capabilities = capabilities; } + + virtual ~Device(); + + /** Prevent unwanted copy operator.*/ + Device& operator = (const Device&) { return *this; } + + osg::ref_ptr _eventQueue; + + private: + int _capabilities; + +}; + +} + +#endif diff --git a/libs/include/android/osgGA/DriveManipulator b/libs/include/android/osgGA/DriveManipulator new file mode 100755 index 0000000..d645fa0 --- /dev/null +++ b/libs/include/android/osgGA/DriveManipulator @@ -0,0 +1,123 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGGA_DRIVEMANIPULATOR +#define OSGGA_DRIVEMANIPULATOR 1 + +#include +#include + +namespace osgGA{ + +/** +DriveManipulator is a camera manipulator which provides drive-like +functionality. By default, the left mouse button accelerates, the right +mouse button decelerates, and the middle mouse button (or left and +right simultaneously) stops dead. +*/ + +class OSGGA_EXPORT DriveManipulator : public CameraManipulator +{ + public: + + DriveManipulator(); + + virtual const char* className() const { return "Drive"; } + + /** Get the position of the matrix manipulator using a 4x4 Matrix.*/ + virtual void setByMatrix(const osg::Matrixd& matrix); + + /** Set the position of the matrix manipulator using a 4x4 Matrix.*/ + virtual void setByInverseMatrix(const osg::Matrixd& matrix) { setByMatrix(osg::Matrixd::inverse(matrix)); } + + /** Get the position of the manipulator as 4x4 Matrix.*/ + virtual osg::Matrixd getMatrix() const; + + /** Get the position of the manipulator as a inverse matrix of the manipulator, typically used as a model view matrix.*/ + virtual osg::Matrixd getInverseMatrix() const; + + virtual void setNode(osg::Node*); + + virtual const osg::Node* getNode() const; + + virtual osg::Node* getNode(); + + virtual void computeHomePosition(); + + virtual void home(const GUIEventAdapter& ea,GUIActionAdapter& us); + + virtual void init(const GUIEventAdapter& ea,GUIActionAdapter& us); + + virtual bool handle(const GUIEventAdapter& ea,GUIActionAdapter& us); + + /** Get the keyboard and mouse usage of this manipulator.*/ + virtual void getUsage(osg::ApplicationUsage& usage) const; + + void setModelScale( double in_ms ) { _modelScale = in_ms; } + double getModelScale() const { return _modelScale; } + + void setVelocity( double in_vel ) { _velocity = in_vel; } + double getVelocity() const { return _velocity; } + + void setHeight( double in_h ) { _height = in_h; } + double getHeight() const { return _height; } + + protected: + + virtual ~DriveManipulator(); + + bool intersect(const osg::Vec3d& start, const osg::Vec3d& end, osg::Vec3d& intersection, osg::Vec3d& normal) const; + + /** Reset the internal GUIEvent stack.*/ + void flushMouseEventStack(); + + /** Add the current mouse GUIEvent to internal stack.*/ + void addMouseEvent(const GUIEventAdapter& ea); + + void computePosition(const osg::Vec3d& eye,const osg::Vec3d& lv,const osg::Vec3d& up); + + /** For the given mouse movement calculate the movement of the camera. + * Return true if camera has moved and a redraw is required. + */ + bool calcMovement(); + + // Internal event stack comprising last two mouse events. + osg::ref_ptr _ga_t1; + osg::ref_ptr _ga_t0; + + osg::observer_ptr _node; + + double _modelScale; + double _velocity; + double _height; + double _buffer; + + enum SpeedControlMode { + USE_MOUSE_Y_FOR_SPEED, + USE_MOUSE_BUTTONS_FOR_SPEED + }; + + SpeedControlMode _speedMode; + + osg::Vec3d _eye; + osg::Quat _rotation; + double _pitch; + double _distance; + + bool _pitchUpKeyPressed; + bool _pitchDownKeyPressed; +}; + +} + +#endif diff --git a/libs/include/android/osgGA/EventQueue b/libs/include/android/osgGA/EventQueue new file mode 100755 index 0000000..4edeaeb --- /dev/null +++ b/libs/include/android/osgGA/EventQueue @@ -0,0 +1,257 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGGA_EVENTQUEUE +#define OSGGA_EVENTQUEUE 1 + +#include + +#include +#include + +#include +#include + +namespace osgGA { + +/** + * EventQueue implementation for collecting and adapting windowing events + */ +class OSGGA_EXPORT EventQueue : public osg::Referenced +{ + public: + + EventQueue(GUIEventAdapter::MouseYOrientation mouseYOrientation=GUIEventAdapter::Y_INCREASING_DOWNWARDS); + + typedef std::list< osg::ref_ptr > Events; + + bool empty() const + { + OpenThreads::ScopedLock lock(_eventQueueMutex); + return _eventQueue.empty(); + } + + /** Set events.*/ + void setEvents(Events& events); + + /** Take the entire event queue leaving the EventQueue' event queue empty.*/ + bool takeEvents(Events& events); + + /** Take the events that were recorded before with specified time queue.*/ + bool takeEvents(Events& events, double cutOffTime); + + /** Take a copy the entire event queue leaving the EventQueue' event queue intact.*/ + bool copyEvents(Events& events) const; + + /** Add events to end of event queue.*/ + void appendEvents(Events& events); + + /** Add an event to the end of the event queue.*/ + void addEvent(GUIEventAdapter* event); + + + /** Specify if mouse coordinates should be transformed into a pre defined input range, or whether they + * should be simply based on as local coordinates to the window that generated the mouse events.*/ + void setUseFixedMouseInputRange(bool useFixedMouseInputRange) { _useFixedMouseInputRange = useFixedMouseInputRange; } + + /** Get whether the mouse coordinates should be transformed into a pre defined input range.*/ + bool getUseFixedMouseInputRange() { return _useFixedMouseInputRange; } + + + /** Set the graphics context associated with this event queue.*/ + void setGraphicsContext(osg::GraphicsContext* context) { getCurrentEventState()->setGraphicsContext(context); } + + osg::GraphicsContext* getGraphicsContext() { return getCurrentEventState()->getGraphicsContext(); } + + const osg::GraphicsContext* getGraphicsContext() const { return getCurrentEventState()->getGraphicsContext(); } + + /** Read the window record dimensions from the graphics context. */ + void syncWindowRectangleWithGraphcisContext(); + + + /** Set the mouse input range.*/ + void setMouseInputRange(float xMin, float yMin, float xMax, float yMax) { getCurrentEventState()->setInputRange(xMin, yMin, xMax, yMax); } + + + /** Method for adapting window resize event, placing this event on the back of the event queue. */ + void windowResize(int x, int y, int width, int height) { windowResize(x,y,width,height,getTime()); } + + /** Method for adapting window resize event, placing this event on the back of the event queue, with specified time. */ + void windowResize(int x, int y, int width, int height, double time); + + + /** Method for adapting mouse scroll wheel events, placing this event on the back of the event queue. */ + void mouseScroll(GUIEventAdapter::ScrollingMotion sm) { mouseScroll(sm,getTime()); } + + /** Method for adapting mouse scroll wheel events, placing this event on the back of the event queue, with specified time. */ + void mouseScroll(GUIEventAdapter::ScrollingMotion sm, double time); + + + /** Method for adapting mouse scroll wheel events, placing this event on the back of the event queue. */ + void mouseScroll2D(float x, float y) { mouseScroll2D(x, y, getTime()); } + + /** Method for adapting mouse scroll wheel events, placing this event on the back of the event queue. */ + void mouseScroll2D(float x, float y, double time); + + + /** Method for adapting pen pressure events, placing this event on the back of the event queue.*/ + void penPressure(float pressure) { penPressure(pressure, getTime()); } + + /** Method for adapting pen pressure events, placing this event on the back of the event queue, with specified time.*/ + void penPressure(float pressure, double time); + + /** Method for adapting pen orientation events, placing this event on the back of the event queue.*/ + void penOrientation(float tiltX, float tiltY, float rotation) { penOrientation(tiltX, tiltY, rotation, getTime()); } + + /** Method for adapting pen orientation events, placing this event on the back of the event queue, with specified time.*/ + void penOrientation(float tiltX, float tiltY, float rotation, double time); + + /** Method for adapting pen proximity events, placing this event on the back of the event queue.*/ + void penProximity(GUIEventAdapter::TabletPointerType pt, bool isEntering) { penProximity(pt, isEntering, getTime()); } + + /** Method for adapting pen proximity events, placing this event on the back of the event queue, with specified time.*/ + void penProximity(GUIEventAdapter::TabletPointerType pt, bool isEntering, double time); + + + /** Method for updating in response to a mouse warp. Note, just moves the mouse position without creating a new event for it.*/ + void mouseWarped(float x, float y); + + + /** Method for adapting mouse motion events, placing this event on the back of the event queue.*/ + void mouseMotion(float x, float y) { mouseMotion(x,y, getTime()); } + + /** Method for adapting mouse motion events, placing this event on the back of the event queue, with specified time.*/ + void mouseMotion(float x, float y, double time); + + + /** Method for adapting mouse button pressed events, placing this event on the back of the event queue. + * Button numbering is 1 for left mouse button, 2 for middle, 3 for right. */ + void mouseButtonPress(float x, float y, unsigned int button) { mouseButtonPress(x, y, button, getTime()); } + + /** Method for adapting mouse button pressed events, placing this event on the back of the event queue, with specified time. + * Button numbering is 1 for left mouse button, 2 for middle, 3 for right. */ + void mouseButtonPress(float x, float y, unsigned int button, double time); + + + /** Method for adapting mouse button pressed events, placing this event on the back of the event queue. + * Button numbering is 1 for left mouse button, 2 for middle, 3 for right. */ + void mouseDoubleButtonPress(float x, float y, unsigned int button) { mouseDoubleButtonPress(x, y, button, getTime()); } + + /** Method for adapting mouse button pressed events, placing this event on the back of the event queue, with specified time. + * Button numbering is 1 for left mouse button, 2 for middle, 3 for right. */ + void mouseDoubleButtonPress(float x, float y, unsigned int button, double time); + + + /** Method for adapting mouse button release events, placing this event on the back of the event queue. + * Button numbering is 1 for left mouse button, 2 for middle, 3 for right. */ + void mouseButtonRelease(float x, float y, unsigned int button) { mouseButtonRelease(x, y, button, getTime()); } + + /** Method for adapting mouse button release events, placing this event on the back of the event queue, with specified time. + * Button numbering is 1 for left mouse button, 2 for middle, 3 for right. */ + void mouseButtonRelease(float x, float y, unsigned int button, double time); + + + /** Method for adapting keyboard press events. Note, special keys such as Ctrl/Function keys should be adapted to GUIEventAdapter::KeySymbol mappings.*/ + void keyPress(int key, int unmodifiedKey = 0) { keyPress(key, getTime(), unmodifiedKey); } + + /** Method for adapting keyboard press events. Note, special keys such as Ctrl/Function keys should be adapted to GUIEventAdapter::KeySymbol mappings, with specified time.*/ + void keyPress(int key, double time, int unmodifiedKey = 0); + + + /** Method for adapting keyboard press events. Note, special keys such as Ctrl/Function keys should be adapted to GUIEventAdapter::KeySymbol mappings.*/ + void keyRelease(int key, int unmodifiedKey = 0) { keyRelease(key, getTime(), unmodifiedKey); } + + /** Method for adapting keyboard press events. Note, special keys such as Ctrl/Function keys should be adapted to GUIEventAdapter::KeySymbol mappings, with specified time.*/ + void keyRelease(int key, double time, int unmodifiedKey = 0); + + GUIEventAdapter* touchBegan(unsigned int id, GUIEventAdapter::TouchPhase phase, float x, float y, double time); + GUIEventAdapter* touchBegan(unsigned int id, GUIEventAdapter::TouchPhase phase, float x, float y) { + return touchBegan(id, phase, x, y, getTime()); + } + + GUIEventAdapter* touchMoved(unsigned int id, GUIEventAdapter::TouchPhase phase, float x, float y, double time); + GUIEventAdapter* touchMoved(unsigned int id, GUIEventAdapter::TouchPhase phase, float x, float y) { + return touchMoved(id, phase, x, y, getTime()); + } + + GUIEventAdapter* touchEnded(unsigned int id, GUIEventAdapter::TouchPhase phase, float x, float y, unsigned int tap_count, double time); + GUIEventAdapter* touchEnded(unsigned int id, GUIEventAdapter::TouchPhase phase, float x, float y, unsigned int tap_count) { + return touchEnded(id, phase, x, y, tap_count, getTime()); + } + + + + /** Method for adapting close window events.*/ + void closeWindow() { closeWindow(getTime()); } + + /** Method for adapting close window event with specified event time.*/ + void closeWindow(double time); + + + /** Method for adapting application quit events.*/ + void quitApplication() { quitApplication(getTime()); } + + /** Method for adapting application quit events with specified event time.*/ + void quitApplication(double time); + + + /** Method for adapting frame events.*/ + void frame(double time); + + + void setStartTick(osg::Timer_t tick) { _startTick = tick; clear(); } + osg::Timer_t getStartTick() const { return _startTick; } + + double getTime() const { return osg::Timer::instance()->delta_s(_startTick, osg::Timer::instance()->tick()); } + + /** clear all events from queue. */ + void clear(); + + /** convenience method for create an event ready to fill in. Clones the getCurrentEventState() to produce a up to date event state. */ + GUIEventAdapter* createEvent(); + + + void setCurrentEventState(GUIEventAdapter* ea) { _accumulateEventState = ea; } + GUIEventAdapter* getCurrentEventState() { return _accumulateEventState.get(); } + const GUIEventAdapter* getCurrentEventState() const { return _accumulateEventState.get(); } + + /** Method for adapting user defined events */ + void userEvent(osg::Referenced* userEventData) { userEvent(userEventData, getTime()); } + + /** Method for adapting user defined events with specified event time */ + void userEvent(osg::Referenced* userEventData, double time); + + void setFirstTouchEmulatesMouse(bool b) { _firstTouchEmulatesMouse = b; } + bool getFirstTouchEmulatesMouse() const { return _firstTouchEmulatesMouse; } + + protected: + + virtual ~EventQueue(); + + /** Prevent unwanted copy operator.*/ + EventQueue& operator = (const EventQueue&) { return *this; } + + osg::ref_ptr _accumulateEventState; + + bool _useFixedMouseInputRange; + + osg::Timer_t _startTick; + mutable OpenThreads::Mutex _eventQueueMutex; + Events _eventQueue; + bool _firstTouchEmulatesMouse; + +}; + +} + +#endif diff --git a/libs/include/android/osgGA/EventVisitor b/libs/include/android/osgGA/EventVisitor new file mode 100755 index 0000000..83cfc7c --- /dev/null +++ b/libs/include/android/osgGA/EventVisitor @@ -0,0 +1,146 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGGA_EVENTVISITOR +#define OSGGA_EVENTVISITOR 1 + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace osgGA { + +/** + * Basic EventVisitor implementation for animating a scene. + * This visitor traverses the scene graph, calling each nodes appCallback if + * it exists. + */ +class OSGGA_EXPORT EventVisitor : public osg::NodeVisitor +{ + public: + + EventVisitor(); + virtual ~EventVisitor(); + + META_NodeVisitor(osgGA, EventVisitor) + + void setActionAdapter(osgGA::GUIActionAdapter* actionAdapter) { _actionAdapter=actionAdapter; } + + osgGA::GUIActionAdapter* getActionAdapter() { return _actionAdapter; } + + const osgGA::GUIActionAdapter* getActionAdapter() const { return _actionAdapter; } + + + typedef std::list< osg::ref_ptr > EventList; + + void addEvent(GUIEventAdapter* event); + void removeEvent(GUIEventAdapter* event); + + void setEventHandled(bool handled) { _handled = handled; } + bool getEventHandled() const { return _handled; } + + + void setEvents(const EventQueue::Events& events) { _events = events; } + EventQueue::Events& getEvents() { return _events; } + const EventQueue::Events& getEvents() const { return _events; } + + public: + + virtual void reset(); + + /** During traversal each type of node calls its callbacks and its children traversed. */ + virtual void apply(osg::Node& node) { handle_callbacks_and_traverse(node); } + + virtual void apply(osg::Geode& node) { handle_geode_callbacks(node); } + virtual void apply(osg::Billboard& node) { handle_geode_callbacks(node); } + + virtual void apply(osg::LightSource& node) { handle_callbacks_and_traverse(node); } + + virtual void apply(osg::Group& node) { handle_callbacks_and_traverse(node); } + virtual void apply(osg::Transform& node) { handle_callbacks_and_traverse(node); } + virtual void apply(osg::Projection& node) { handle_callbacks_and_traverse(node); } + virtual void apply(osg::Switch& node) { handle_callbacks_and_traverse(node); } + virtual void apply(osg::LOD& node) { handle_callbacks_and_traverse(node); } + virtual void apply(osg::OccluderNode& node) { handle_callbacks_and_traverse(node); } + + + protected: + + /** Prevent unwanted copy operator.*/ + EventVisitor& operator = (const EventVisitor&) { return *this; } + + inline void handle_callbacks(osg::StateSet* stateset) + { + if (stateset && stateset->requiresEventTraversal()) + { + stateset->runEventCallbacks(this); + } + } + + inline void handle_callbacks_and_traverse(osg::Node& node) + { + handle_callbacks(node.getStateSet()); + + osg::NodeCallback* callback = node.getEventCallback(); + if (callback) (*callback)(&node,this); + else if (node.getNumChildrenRequiringEventTraversal()>0) traverse(node); + } + + inline void handle_geode_callbacks(osg::Geode& node) + { + handle_callbacks(node.getStateSet()); + + osg::NodeCallback* callback = node.getEventCallback(); + if (callback) (*callback)(&node,this); + /*else if (node.getNumChildrenRequiringEventTraversal()>0)*/ + traverseGeode(node); + } + + inline void traverseGeode(osg::Geode& geode) + { + traverse((osg::Node&)geode); + + // Call the app callbacks on the drawables. + for(unsigned int i=0;igetEventCallback(); + if (callback) callback->event(this,geode.getDrawable(i)); + + handle_callbacks(geode.getDrawable(i)->getStateSet()); + } + } + + osgGA::GUIActionAdapter* _actionAdapter; + + osg::ref_ptr _accumulateEventState; + + bool _handled; + EventQueue::Events _events; + +}; + +} + +#endif + diff --git a/libs/include/android/osgGA/Export b/libs/include/android/osgGA/Export new file mode 100755 index 0000000..0743d67 --- /dev/null +++ b/libs/include/android/osgGA/Export @@ -0,0 +1,74 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +// The following symbol has a underscore suffix for compatibility. +#ifndef OSGGA_EXPORT_ +#define OSGGA_EXPORT_ 1 + +#include + +#if defined(_MSC_VER) && defined(OSG_DISABLE_MSVC_WARNINGS) + #pragma warning( disable : 4244 ) + #pragma warning( disable : 4251 ) + #pragma warning( disable : 4267 ) + #pragma warning( disable : 4275 ) + #pragma warning( disable : 4290 ) + #pragma warning( disable : 4786 ) + #pragma warning( disable : 4305 ) + #pragma warning( disable : 4996 ) +#endif + +#if defined(_MSC_VER) || defined(__CYGWIN__) || defined(__MINGW32__) || defined( __BCPLUSPLUS__) || defined( __MWERKS__) + # if defined( OSG_LIBRARY_STATIC ) + # define OSGGA_EXPORT + # elif defined( OSGGA_LIBRARY ) + # define OSGGA_EXPORT __declspec(dllexport) + # else + # define OSGGA_EXPORT __declspec(dllimport) + #endif +#else + #define OSGGA_EXPORT +#endif + +#endif + + +/** + +\namespace osgGA + +The 'GA' in osgGA stands for 'GUI Abstraction'; the osgGA namespace provides facilities to +help developers write the glue to allow the osg to work with varying window systems. + +As a cross-platform, window system-agnostic class library, the OpenSceneGraph +has no direct ties to any given windowing environment. Viewers, however, must at +some level interact with a window system - where Window system may refer to a windowing +API, e.g. GLUT, Qt, FLTK, MFC, ... + +There is much commonality in the implementation of Viewers for varying windowing +environments. E.g. most Viewers will update a Camera position in response to a mouse +event, and may request that a timer be started as a result of a model being 'spun'. + +The purpose of the osgGA namespace is to centralise the common areas of this +functionality. The viewer writer needs then only write a GUIEventAdapter, a +GUIActionAdapter, and assemble a collection of GUIEventHandlers +as appropriate for the viewer. + +Events from the windowing environment are adpated, and then fed into the GUIEventHandlers. +The GUIEventHandlers analyse and take action, and make requests of the windowing +environemnt via the GUIActionAdapter. The viewer writer should then honour these +requests, translating them into calls to the windowing API. + +*/ + + diff --git a/libs/include/android/osgGA/FirstPersonManipulator b/libs/include/android/osgGA/FirstPersonManipulator new file mode 100755 index 0000000..b032638 --- /dev/null +++ b/libs/include/android/osgGA/FirstPersonManipulator @@ -0,0 +1,112 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2010 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. + * + * FirstPersonManipulator code Copyright (C) 2010 PCJohn (Jan Peciva) + * while some pieces of code were taken from OSG. + * Thanks to company Cadwork (www.cadwork.ch) and + * Brno University of Technology (www.fit.vutbr.cz) for open-sourcing this work. +*/ + +#ifndef OSGGA_FIRST_PERSON_MANIPULATOR +#define OSGGA_FIRST_PERSON_MANIPULATOR 1 + +#include + + +namespace osgGA { + + +/** FirstPersonManipulator is base class for camera control based on position + and orientation of camera, like walk, drive, and flight manipulators. */ +class OSGGA_EXPORT FirstPersonManipulator : public StandardManipulator +{ + typedef StandardManipulator inherited; + + public: + + FirstPersonManipulator( int flags = DEFAULT_SETTINGS ); + FirstPersonManipulator( const FirstPersonManipulator& fpm, + const osg::CopyOp& copyOp = osg::CopyOp::SHALLOW_COPY ); + + META_Object( osgGA, FirstPersonManipulator ); + + virtual void setByMatrix( const osg::Matrixd& matrix ); + virtual void setByInverseMatrix( const osg::Matrixd& matrix ); + virtual osg::Matrixd getMatrix() const; + virtual osg::Matrixd getInverseMatrix() const; + + virtual void setTransformation( const osg::Vec3d& eye, const osg::Quat& rotation ); + virtual void setTransformation( const osg::Vec3d& eye, const osg::Vec3d& center, const osg::Vec3d& up ); + virtual void getTransformation( osg::Vec3d& eye, osg::Quat& rotation ) const; + virtual void getTransformation( osg::Vec3d& eye, osg::Vec3d& center, osg::Vec3d& up ) const; + + virtual void setVelocity( const double& velocity ); + inline double getVelocity() const; + virtual void setAcceleration( const double& acceleration, bool relativeToModelSize = false ); + double getAcceleration( bool *relativeToModelSize = NULL ) const; + virtual void setMaxVelocity( const double& maxVelocity, bool relativeToModelSize = false ); + double getMaxVelocity( bool *relativeToModelSize = NULL ) const; + + virtual void setWheelMovement( const double& wheelMovement, bool relativeToModelSize = false ); + double getWheelMovement( bool *relativeToModelSize = NULL ) const; + + virtual void home( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& us ); + virtual void home( double ); + + virtual void init( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& us ); + + protected: + + virtual bool handleMouseWheel( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& us ); + + virtual bool performMovementLeftMouseButton( const double eventTimeDelta, const double dx, const double dy ); + virtual bool performMouseDeltaMovement( const float dx, const float dy ); + virtual void applyAnimationStep( const double currentProgress, const double prevProgress ); + virtual bool startAnimationByMousePointerIntersection( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& us ); + + void moveForward( const double distance ); + void moveForward( const osg::Quat& rotation, const double distance ); + void moveRight( const double distance ); + void moveUp( const double distance ); + + osg::Vec3d _eye; + osg::Quat _rotation; + double _velocity; + + double _acceleration; + static int _accelerationFlagIndex; + double _maxVelocity; + static int _maxVelocityFlagIndex; + double _wheelMovement; + static int _wheelMovementFlagIndex; + + class FirstPersonAnimationData : public AnimationData { + public: + osg::Quat _startRot; + osg::Quat _targetRot; + void start( const osg::Quat& startRotation, const osg::Quat& targetRotation, const double startTime ); + }; + virtual void allocAnimationData() { _animationData = new FirstPersonAnimationData(); } +}; + + +// +// inline methods +// + +/// Returns velocity. +double FirstPersonManipulator::getVelocity() const { return _velocity; } + + +} + +#endif /* OSGGA_FIRST_PERSON_MANIPULATOR */ diff --git a/libs/include/android/osgGA/FlightManipulator b/libs/include/android/osgGA/FlightManipulator new file mode 100755 index 0000000..c39ff92 --- /dev/null +++ b/libs/include/android/osgGA/FlightManipulator @@ -0,0 +1,83 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGGA_FLIGHT_MANIPULATOR +#define OSGGA_FLIGHT_MANIPULATOR 1 + +#include + + +namespace osgGA { + + +/** FlightManipulator is a CameraManipulator which provides flight simulator-like + * updating of the camera position & orientation. By default, the left mouse + * button accelerates, the right mouse button decelerates, and the middle mouse + * button (or left and right simultaneously) stops dead. + */ +class OSGGA_EXPORT FlightManipulator : public FirstPersonManipulator +{ + typedef FirstPersonManipulator inherited; + + public: + + enum YawControlMode + { + YAW_AUTOMATICALLY_WHEN_BANKED, + NO_AUTOMATIC_YAW + }; + + FlightManipulator( int flags = UPDATE_MODEL_SIZE | COMPUTE_HOME_USING_BBOX ); + FlightManipulator( const FlightManipulator& fpm, + const osg::CopyOp& copyOp = osg::CopyOp::SHALLOW_COPY ); + + META_Object( osgGA, FlightManipulator ); + + virtual void setYawControlMode( YawControlMode ycm ); + inline YawControlMode getYawControlMode() const; + + virtual void home( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& us ); + virtual void init( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& us ); + virtual void getUsage( osg::ApplicationUsage& usage ) const; + + protected: + + virtual bool handleFrame( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& us ); + virtual bool handleMouseMove( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& us ); + virtual bool handleMouseDrag( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& us ); + virtual bool handleMousePush( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& us ); + virtual bool handleMouseRelease( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& us ); + virtual bool handleKeyDown( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& us ); + virtual bool flightHandleEvent( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& us ); + + virtual bool performMovement(); + virtual bool performMovementLeftMouseButton( const double eventTimeDelta, const double dx, const double dy ); + virtual bool performMovementMiddleMouseButton( const double eventTimeDelta, const double dx, const double dy ); + virtual bool performMovementRightMouseButton( const double eventTimeDelta, const double dx, const double dy ); + + YawControlMode _yawMode; + +}; + + +// +// inline methods +// + +/// Returns the Yaw control for the flight model. +inline FlightManipulator::YawControlMode FlightManipulator::getYawControlMode() const { return _yawMode; } + + +} + +#endif /* OSGGA_FLIGHT_MANIPULATOR */ diff --git a/libs/include/android/osgGA/GUIActionAdapter b/libs/include/android/osgGA/GUIActionAdapter new file mode 100755 index 0000000..07ddce4 --- /dev/null +++ b/libs/include/android/osgGA/GUIActionAdapter @@ -0,0 +1,91 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGGA_GUIACTIONADAPTER +#define OSGGA_GUIACTIONADAPTER 1 + +#include +#include + +namespace osgGA{ + +/** +Abstract base class defining the interface by which GUIEventHandlers may request +actions of the GUI system in use. These requests for actions should then be honored +by the GUI toolkit of the user's application. + +To provide more detail, when a GUIEventHandler (e.g. a TrackballManipulator) +handles an incoming event, such as a mouse event, it may wish to make +a request of the GUI. E.g. if a model is 'thrown', the trackball manipulator +may wish to start a timer, and be repeatedly called, to continuously refresh the +camera's position and orientation. However, it has no way of doing this, as it +knows nothing of the window system in which it's operating. Instead, the +GUIEventHandler issues it's request via a GUIActionAdapter, and the viewer +in use should honour the request, using the GUI system in play. + +There is more than one way of using the GUIActionAdapter. E.g. it may be inherited +into a Viewer class, as is done with osgGLUT::Viewer. Alternatively, a simple +subclass of GUIActionAdapter (e.g. osgQt::QtActionAdapter) may be passed to +the GUIEventHandler::handle() function; once the function has returned, the viewer +will then unpack the results and work out what to do to respond to the +requests. + +Also there are several ways to run your app and handle the updating of +the window. osgGLUT::Viewer always has a idle callback registered which does a +redraw all the time. osgGLUT::Viewer can safely ignore both requestRedraw() and +requestContinousUpdate() as these are happening all the time anyway. + +Other apps will probably want to respond to the requestRedraw() and +requestContinousUpdate(bool) and again there is more than one way to handle it. +You can override requestRedraw() and implement to call your own window +redraw straight away. Or you can implement so that a flag is set and +then you then respond the flag being set in your own leisure. + +*/ +class GUIActionAdapter +{ +public: + virtual ~GUIActionAdapter() {} + + /** Provide a mechanism for getting the osg::View associated with this GUIActionAdapter. + * One would use this to case view to osgViewer::View(er) if supported by the subclass.*/ + virtual osg::View* asView() { return 0; } + + /** + requestRedraw() requests a single redraw. + */ + virtual void requestRedraw() = 0; + + /** + requestContinuousUpdate(bool) is for en/disabling a throw or idle + callback to be requested by a GUIEventHandler (typically a CameraManipulator, + though other GUIEventHandler's may also provide functionality). + GUI toolkits can respond to this immediately by registering an idle/timed + callback, or can delay setting the callback and update at their own leisure. + */ + virtual void requestContinuousUpdate(bool needed=true) = 0; + + /** + requestWarpPointer(int,int) is requesting a repositioning of the mouse pointer + to a specified x,y location on the window. This is used by some camera manipulators + to initialise the mouse pointer when mouse position relative to a controls + neutral mouse position is required, i.e when mimicking a aircrafts joystick. + */ + virtual void requestWarpPointer(float x,float y) = 0; + +}; + +} + +#endif + diff --git a/libs/include/android/osgGA/GUIEventAdapter b/libs/include/android/osgGA/GUIEventAdapter new file mode 100755 index 0000000..08620ee --- /dev/null +++ b/libs/include/android/osgGA/GUIEventAdapter @@ -0,0 +1,760 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGGA_EVENT +#define OSGGA_EVENT 1 + +#include +#include +#include +#include + +namespace osgGA{ + +struct PointerData : public osg::Referenced +{ + PointerData(): + object(0), + x(0.0f), + xMin(-1.0f), + xMax(1.0f), + y(0.0f), + yMin(-1.0f), + yMax(1.0f) {} + + PointerData(osg::Object* obj, float in_x, float in_xMin, float in_xMax, float in_y, float in_yMin, float in_yMax): + object(obj), + x(in_x), + xMin(in_xMin), + xMax(in_xMax), + y(in_y), + yMin(in_yMin), + yMax(in_yMax) {} + + PointerData(const PointerData& pd): + osg::Referenced(), + object(pd.object), + x(pd.x), + xMin(pd.xMin), + xMax(pd.xMax), + y(pd.y), + yMin(pd.yMin), + yMax(pd.yMax) {} + + PointerData& operator = (const PointerData& pd) + { + if (&pd==this) return *this; + + object = pd.object; + x = pd.x; + xMin = pd.xMin; + xMax = pd.xMax; + y = pd.y; + yMin = pd.yMin; + yMax = pd.yMax; + + return *this; + } + + osg::observer_ptr object; + float x, xMin, xMax; + float y, yMin, yMax; + + float getXnormalized() const { return (x-xMin)/(xMax-xMin)*2.0f-1.0f; } + float getYnormalized() const { return (y-yMin)/(yMax-yMin)*2.0f-1.0f; } +}; + + +/** Event class for storing Keyboard, mouse and window events. +*/ +class OSGGA_EXPORT GUIEventAdapter : public osg::Object +{ +public: + + enum MouseButtonMask { + LEFT_MOUSE_BUTTON = 1<<0, + MIDDLE_MOUSE_BUTTON = 1<<1, + RIGHT_MOUSE_BUTTON = 1<<2 + }; + + enum EventType { + NONE = 0, + PUSH = 1<<0, + RELEASE = 1<<1, + DOUBLECLICK = 1<<2, + DRAG = 1<<3, + MOVE = 1<<4, + KEYDOWN = 1<<5, + KEYUP = 1<<6, + FRAME = 1<<7, + RESIZE = 1<<8, + SCROLL = 1<<9, + PEN_PRESSURE = 1<<10, + PEN_ORIENTATION = 1<<11, + PEN_PROXIMITY_ENTER = 1<<12, + PEN_PROXIMITY_LEAVE = 1<<13, + CLOSE_WINDOW = 1<<14, + QUIT_APPLICATION = 1<<15, + USER = 1<<16 + }; + + enum KeySymbol + { + KEY_Space = 0x20, + + KEY_0 = '0', + KEY_1 = '1', + KEY_2 = '2', + KEY_3 = '3', + KEY_4 = '4', + KEY_5 = '5', + KEY_6 = '6', + KEY_7 = '7', + KEY_8 = '8', + KEY_9 = '9', + KEY_A = 'a', + KEY_B = 'b', + KEY_C = 'c', + KEY_D = 'd', + KEY_E = 'e', + KEY_F = 'f', + KEY_G = 'g', + KEY_H = 'h', + KEY_I = 'i', + KEY_J = 'j', + KEY_K = 'k', + KEY_L = 'l', + KEY_M = 'm', + KEY_N = 'n', + KEY_O = 'o', + KEY_P = 'p', + KEY_Q = 'q', + KEY_R = 'r', + KEY_S = 's', + KEY_T = 't', + KEY_U = 'u', + KEY_V = 'v', + KEY_W = 'w', + KEY_X = 'x', + KEY_Y = 'y', + KEY_Z = 'z', + + KEY_Exclaim = 0x21, + KEY_Quotedbl = 0x22, + KEY_Hash = 0x23, + KEY_Dollar = 0x24, + KEY_Ampersand = 0x26, + KEY_Quote = 0x27, + KEY_Leftparen = 0x28, + KEY_Rightparen = 0x29, + KEY_Asterisk = 0x2A, + KEY_Plus = 0x2B, + KEY_Comma = 0x2C, + KEY_Minus = 0x2D, + KEY_Period = 0x2E, + KEY_Slash = 0x2F, + KEY_Colon = 0x3A, + KEY_Semicolon = 0x3B, + KEY_Less = 0x3C, + KEY_Equals = 0x3D, + KEY_Greater = 0x3E, + KEY_Question = 0x3F, + KEY_At = 0x40, + KEY_Leftbracket = 0x5B, + KEY_Backslash = 0x5C, + KEY_Rightbracket = 0x5D, + KEY_Caret = 0x5E, + KEY_Underscore = 0x5F, + KEY_Backquote = 0x60, + + KEY_BackSpace = 0xFF08, /* back space, back char */ + KEY_Tab = 0xFF09, + KEY_Linefeed = 0xFF0A, /* Linefeed, LF */ + KEY_Clear = 0xFF0B, + KEY_Return = 0xFF0D, /* Return, enter */ + KEY_Pause = 0xFF13, /* Pause, hold */ + KEY_Scroll_Lock = 0xFF14, + KEY_Sys_Req = 0xFF15, + KEY_Escape = 0xFF1B, + KEY_Delete = 0xFFFF, /* Delete, rubout */ + + + /* Cursor control & motion */ + + KEY_Home = 0xFF50, + KEY_Left = 0xFF51, /* Move left, left arrow */ + KEY_Up = 0xFF52, /* Move up, up arrow */ + KEY_Right = 0xFF53, /* Move right, right arrow */ + KEY_Down = 0xFF54, /* Move down, down arrow */ + KEY_Prior = 0xFF55, /* Prior, previous */ + KEY_Page_Up = 0xFF55, + KEY_Next = 0xFF56, /* Next */ + KEY_Page_Down = 0xFF56, + KEY_End = 0xFF57, /* EOL */ + KEY_Begin = 0xFF58, /* BOL */ + + + /* Misc Functions */ + + KEY_Select = 0xFF60, /* Select, mark */ + KEY_Print = 0xFF61, + KEY_Execute = 0xFF62, /* Execute, run, do */ + KEY_Insert = 0xFF63, /* Insert, insert here */ + KEY_Undo = 0xFF65, /* Undo, oops */ + KEY_Redo = 0xFF66, /* redo, again */ + KEY_Menu = 0xFF67, /* On Windows, this is VK_APPS, the context-menu key */ + KEY_Find = 0xFF68, /* Find, search */ + KEY_Cancel = 0xFF69, /* Cancel, stop, abort, exit */ + KEY_Help = 0xFF6A, /* Help */ + KEY_Break = 0xFF6B, + KEY_Mode_switch = 0xFF7E, /* Character set switch */ + KEY_Script_switch = 0xFF7E, /* Alias for mode_switch */ + KEY_Num_Lock = 0xFF7F, + + /* Keypad Functions, keypad numbers cleverly chosen to map to ascii */ + + KEY_KP_Space = 0xFF80, /* space */ + KEY_KP_Tab = 0xFF89, + KEY_KP_Enter = 0xFF8D, /* enter */ + KEY_KP_F1 = 0xFF91, /* PF1, KP_A, ... */ + KEY_KP_F2 = 0xFF92, + KEY_KP_F3 = 0xFF93, + KEY_KP_F4 = 0xFF94, + KEY_KP_Home = 0xFF95, + KEY_KP_Left = 0xFF96, + KEY_KP_Up = 0xFF97, + KEY_KP_Right = 0xFF98, + KEY_KP_Down = 0xFF99, + KEY_KP_Prior = 0xFF9A, + KEY_KP_Page_Up = 0xFF9A, + KEY_KP_Next = 0xFF9B, + KEY_KP_Page_Down = 0xFF9B, + KEY_KP_End = 0xFF9C, + KEY_KP_Begin = 0xFF9D, + KEY_KP_Insert = 0xFF9E, + KEY_KP_Delete = 0xFF9F, + KEY_KP_Equal = 0xFFBD, /* equals */ + KEY_KP_Multiply = 0xFFAA, + KEY_KP_Add = 0xFFAB, + KEY_KP_Separator = 0xFFAC, /* separator, often comma */ + KEY_KP_Subtract = 0xFFAD, + KEY_KP_Decimal = 0xFFAE, + KEY_KP_Divide = 0xFFAF, + + KEY_KP_0 = 0xFFB0, + KEY_KP_1 = 0xFFB1, + KEY_KP_2 = 0xFFB2, + KEY_KP_3 = 0xFFB3, + KEY_KP_4 = 0xFFB4, + KEY_KP_5 = 0xFFB5, + KEY_KP_6 = 0xFFB6, + KEY_KP_7 = 0xFFB7, + KEY_KP_8 = 0xFFB8, + KEY_KP_9 = 0xFFB9, + + /* + * Auxiliary Functions; note the duplicate definitions for left and right + * function keys; Sun keyboards and a few other manufactures have such + * function key groups on the left and/or right sides of the keyboard. + * We've not found a keyboard with more than 35 function keys total. + */ + + KEY_F1 = 0xFFBE, + KEY_F2 = 0xFFBF, + KEY_F3 = 0xFFC0, + KEY_F4 = 0xFFC1, + KEY_F5 = 0xFFC2, + KEY_F6 = 0xFFC3, + KEY_F7 = 0xFFC4, + KEY_F8 = 0xFFC5, + KEY_F9 = 0xFFC6, + KEY_F10 = 0xFFC7, + KEY_F11 = 0xFFC8, + KEY_F12 = 0xFFC9, + KEY_F13 = 0xFFCA, + KEY_F14 = 0xFFCB, + KEY_F15 = 0xFFCC, + KEY_F16 = 0xFFCD, + KEY_F17 = 0xFFCE, + KEY_F18 = 0xFFCF, + KEY_F19 = 0xFFD0, + KEY_F20 = 0xFFD1, + KEY_F21 = 0xFFD2, + KEY_F22 = 0xFFD3, + KEY_F23 = 0xFFD4, + KEY_F24 = 0xFFD5, + KEY_F25 = 0xFFD6, + KEY_F26 = 0xFFD7, + KEY_F27 = 0xFFD8, + KEY_F28 = 0xFFD9, + KEY_F29 = 0xFFDA, + KEY_F30 = 0xFFDB, + KEY_F31 = 0xFFDC, + KEY_F32 = 0xFFDD, + KEY_F33 = 0xFFDE, + KEY_F34 = 0xFFDF, + KEY_F35 = 0xFFE0, + + /* Modifiers */ + + KEY_Shift_L = 0xFFE1, /* Left shift */ + KEY_Shift_R = 0xFFE2, /* Right shift */ + KEY_Control_L = 0xFFE3, /* Left control */ + KEY_Control_R = 0xFFE4, /* Right control */ + KEY_Caps_Lock = 0xFFE5, /* Caps lock */ + KEY_Shift_Lock = 0xFFE6, /* Shift lock */ + + KEY_Meta_L = 0xFFE7, /* Left meta */ + KEY_Meta_R = 0xFFE8, /* Right meta */ + KEY_Alt_L = 0xFFE9, /* Left alt */ + KEY_Alt_R = 0xFFEA, /* Right alt */ + KEY_Super_L = 0xFFEB, /* Left super */ + KEY_Super_R = 0xFFEC, /* Right super */ + KEY_Hyper_L = 0xFFED, /* Left hyper */ + KEY_Hyper_R = 0xFFEE /* Right hyper */ + }; + + + enum ModKeyMask + { + MODKEY_LEFT_SHIFT = 0x0001, + MODKEY_RIGHT_SHIFT = 0x0002, + MODKEY_LEFT_CTRL = 0x0004, + MODKEY_RIGHT_CTRL = 0x0008, + MODKEY_LEFT_ALT = 0x0010, + MODKEY_RIGHT_ALT = 0x0020, + MODKEY_LEFT_META = 0x0040, + MODKEY_RIGHT_META = 0x0080, + MODKEY_LEFT_SUPER = 0x0100, + MODKEY_RIGHT_SUPER = 0x0200, + MODKEY_LEFT_HYPER = 0x0400, + MODKEY_RIGHT_HYPER = 0x0800, + MODKEY_NUM_LOCK = 0x1000, + MODKEY_CAPS_LOCK = 0x2000, + MODKEY_CTRL = (MODKEY_LEFT_CTRL|MODKEY_RIGHT_CTRL), + MODKEY_SHIFT = (MODKEY_LEFT_SHIFT|MODKEY_RIGHT_SHIFT), + MODKEY_ALT = (MODKEY_LEFT_ALT|MODKEY_RIGHT_ALT), + MODKEY_META = (MODKEY_LEFT_META|MODKEY_RIGHT_META), + MODKEY_SUPER = (MODKEY_LEFT_SUPER|MODKEY_RIGHT_SUPER), + MODKEY_HYPER = (MODKEY_LEFT_HYPER|MODKEY_RIGHT_HYPER) + }; + + enum MouseYOrientation + { + Y_INCREASING_UPWARDS, + Y_INCREASING_DOWNWARDS + }; + + enum ScrollingMotion + { + SCROLL_NONE, + SCROLL_LEFT, + SCROLL_RIGHT, + SCROLL_UP, + SCROLL_DOWN, + SCROLL_2D + }; + + enum TabletPointerType + { + UNKNOWN = 0, + PEN, + PUCK, + ERASER + }; + + enum TouchPhase + { + TOUCH_UNKNOWN, + TOUCH_BEGAN, + TOUCH_MOVED, + TOUCH_STATIONERY, + TOUCH_ENDED + }; + + class TouchData : public osg::Object { + public: + + struct TouchPoint { + unsigned int id; + TouchPhase phase; + float x, y; + + unsigned int tapCount; + TouchPoint() : id(0), phase(TOUCH_UNKNOWN), x(0.0f), y(0.0f), tapCount(0) {} + TouchPoint(unsigned int in_id, TouchPhase in_phase, float in_x, float in_y, unsigned int in_tap_count) + : id(in_id), + phase(in_phase), + x(in_x), + y(in_y), + tapCount(in_tap_count) + { + } + }; + + typedef std::vector TouchSet; + + typedef TouchSet::iterator iterator; + typedef TouchSet::const_iterator const_iterator; + + TouchData() : osg::Object() {} + + TouchData(const TouchData& td, const osg::CopyOp& copyop): + osg::Object(td,copyop), + _touches(td._touches) {} + + + META_Object(osgGA, TouchData); + + + unsigned int getNumTouchPoints() const { return static_cast(_touches.size()); } + + iterator begin() { return _touches.begin(); } + const_iterator begin() const { return _touches.begin(); } + + iterator end() { return _touches.end(); } + const_iterator end() const { return _touches.end(); } + + const TouchPoint get(unsigned int i) const { return _touches[i]; } + + protected: + + virtual ~TouchData() {} + + void addTouchPoint(unsigned int id, TouchPhase phase, float x, float y, unsigned int tap_count) { + _touches.push_back(TouchPoint(id, phase, x, y, tap_count)); + } + + TouchSet _touches; + + friend class GUIEventAdapter; + }; + + public: + + GUIEventAdapter(); + + GUIEventAdapter(const GUIEventAdapter& rhs, const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY); + + META_Object(osgGA, GUIEventAdapter); + + + /** Get the accumulated event state singleton. + * Typically all EventQueue will share this single GUIEventAdapter object for tracking + * the mouse position, keyboard and mouse masks. */ + static osg::ref_ptr& getAccumulatedEventState(); + + + /** Set whether this event has been handled by an event handler or not.*/ + void setHandled(bool handled) const { _handled = handled; } + + /** Get whether this event has been handled by an event handler or not.*/ + bool getHandled() const { return _handled; } + + /** set the event type. */ + void setEventType(EventType Type) { _eventType = Type; } + + /** get the event type. */ + virtual EventType getEventType() const { return _eventType; } + + /** set time in seconds of event. */ + void setTime(double time) { _time = time; } + + /** get time in seconds of event. */ + double getTime() const { return _time; } + + /** deprecated function for getting time of event. */ + double time() const { return _time; } + + + void setGraphicsContext(osg::GraphicsContext* context) { _context = context; } + osg::GraphicsContext* getGraphicsContext() { return _context.get(); } + const osg::GraphicsContext* getGraphicsContext() const { return _context.get(); } + + + /** set window rectangle. */ + void setWindowRectangle(int x, int y, int width, int height, bool updateMouseRange = true); + + /** set window x origin.*/ + void setWindowX(int v) { _windowX = v; } + + /** get window x origin.*/ + int getWindowX() const { return _windowX; } + + /** set window x origin.*/ + void setWindowY(int v) { _windowY = v; } + + /** get window y origin.*/ + int getWindowY() const { return _windowY; } + + /** set window width.*/ + void setWindowWidth(int v) { _windowWidth = v; } + + /** get window width.*/ + int getWindowWidth() const { return _windowWidth; } + + /** set window height.*/ + void setWindowHeight(int v) { _windowHeight = v; } + + /** get window height.*/ + int getWindowHeight() const { return _windowHeight; } + + + /** set key pressed. */ + inline void setKey(int key) { _key = key; } + + /** get key pressed, return -1 if inappropriate for this GUIEventAdapter. */ + virtual int getKey() const { return _key; } + + /** set virtual key pressed. */ + void setUnmodifiedKey(int key) { _unmodifiedKey = key; } + + /** get virtual key pressed. */ + int getUnmodifiedKey() const { return _unmodifiedKey; } + + /** set button pressed/released.*/ + void setButton(int button) { _button = button; } + + /** button pressed/released, return -1 if inappropriate for this GUIEventAdapter.*/ + int getButton() const { return _button; } + + + /** set mouse input range. */ + void setInputRange(float Xmin, float Ymin, float Xmax, float Ymax); + + /** set mouse minimum x. */ + void setXmin(float v) { _Xmin = v; } + + /** get mouse minimum x. */ + float getXmin() const { return _Xmin; } + + /** set mouse maximum x. */ + void setXmax(float v) { _Xmax = v; } + + /** get mouse maximum x. */ + float getXmax() const { return _Xmax; } + + /** set mouse minimum x. */ + void setYmin(float v) { _Ymin = v; } + + /** get mouse minimum y. */ + float getYmin() const { return _Ymin; } + + /** set mouse maximum y. */ + void setYmax(float v) { _Ymax = v; } + + /** get mouse maximum y. */ + float getYmax() const { return _Ymax; } + + /** set current mouse x position.*/ + void setX(float x) { _mx = x; } + + /** get current mouse x position.*/ + float getX() const { return _mx; } + + /** set current mouse y position.*/ + void setY(float y) { _my = y; } + + /** get current mouse y position.*/ + float getY() const { return _my; } + +#if 1 + inline float getXnormalized() const + { + return _pointerDataList.size()>=1 ? + _pointerDataList[_pointerDataList.size()-1]->getXnormalized(): + 2.0f*(getX()-getXmin())/(getXmax()-getXmin())-1.0f; + } + + inline float getYnormalized() const + { + if (_pointerDataList.size()>=1) return _pointerDataList[_pointerDataList.size()-1]->getYnormalized(); + if (_mouseYOrientation==Y_INCREASING_UPWARDS) return 2.0f*(getY()-getYmin())/(getYmax()-getYmin())-1.0f; + else return -(2.0f*(getY()-getYmin())/(getYmax()-getYmin())-1.0f); + } +#else + /** + * return the current mouse x value normalized to the range of -1 to 1. + * -1 would be the left hand side of the window. + * 0.0 would be the middle of the window. + * +1 would be the right hand side of the window. + */ + inline float getXnormalized() const { return 2.0f*(getX()-getXmin())/(getXmax()-getXmin())-1.0f; } + + /** + * return the current mouse y value normalized to the range of -1 to 1. + * -1 would be the bottom of the window. + * 0.0 would be the middle of the window. + * +1 would be the top of the window. + */ + inline float getYnormalized() const + { + if (_mouseYOrientation==Y_INCREASING_UPWARDS) return 2.0f*(getY()-getYmin())/(getYmax()-getYmin())-1.0f; + else return -(2.0f*(getY()-getYmin())/(getYmax()-getYmin())-1.0f); + } +#endif + + /// set mouse-Y orientation (mouse-Y increases upwards or downwards). + void setMouseYOrientation(MouseYOrientation myo) { _mouseYOrientation = myo; } + + /// get mouse-Y orientation (mouse-Y increases upwards or downwards). + MouseYOrientation getMouseYOrientation() const { return _mouseYOrientation; } + + /// set current mouse button state. + void setButtonMask(int mask) { _buttonMask = mask; } + + /// get current mouse button state. + int getButtonMask() const { return _buttonMask; } + + /// set modifier key mask. + void setModKeyMask(int mask) { _modKeyMask = mask; } + + /// get modifier key mask. + int getModKeyMask() const { return _modKeyMask; } + + /// set scrolling motion (for EventType::SCROLL). + void setScrollingMotion(ScrollingMotion motion) { _scrolling.motion = motion; } + + /// get scrolling motion (for EventType::SCROLL). + ScrollingMotion getScrollingMotion() const { return _scrolling.motion; } + + /// set the scrolling delta to x,y and the scrolling motion to SCROLL_2D. + void setScrollingMotionDelta(float x, float y) { + _scrolling.motion = SCROLL_2D; + _scrolling.deltaX = x; + _scrolling.deltaY = y; + } + + /// set the scrolling x-delta. + void setScrollingDeltaX(float v) { _scrolling.deltaX = v; } + + /// get the scrolling x-delta. + float getScrollingDeltaX() const { return _scrolling.deltaX; } + + /// set the scrolling y-delta. + void setScrollingDeltaY(float v) { _scrolling.deltaY = v; } + + /// get the scrolling y-delta. + float getScrollingDeltaY() const { return _scrolling.deltaY; } + + + /// set the tablet pen pressure (range 0..1). + void setPenPressure(float pressure) { _tabletPen.pressure = pressure; } + + /// get the tablet pen pressure (range 0..1). + float getPenPressure() const { return _tabletPen.pressure; } + + /// set the tablet pen tiltX in degrees. + void setPenTiltX(float tiltX) { _tabletPen.tiltX = tiltX; } + + /// get the tablet pen tiltX in degrees. + float getPenTiltX() const { return _tabletPen.tiltX; } + + /// set the tablet pen tiltY in degrees. + void setPenTiltY(float tiltY) { _tabletPen.tiltY = tiltY; } + + /// get the tablet pen tiltY in degrees. + float getPenTiltY() const { return _tabletPen.tiltY; } + + /// set the tablet pen rotation around the Z-axis in degrees. + void setPenRotation(float rotation) { _tabletPen.rotation = rotation; } + + /// get the tablet pen rotation around the Z-axis in degrees. + float getPenRotation() const { return _tabletPen.rotation; } + + /// set the tablet pointer type. + void setTabletPointerType(TabletPointerType pt) { _tabletPen.tabletPointerType = pt; } + + /// get the tablet pointer type. + TabletPointerType getTabletPointerType() const { return _tabletPen.tabletPointerType; } + + /// set the orientation from a tablet input device as a matrix. + const osg::Matrix getPenOrientation() const; + + void addTouchPoint(unsigned int id, TouchPhase phase, float x, float y, unsigned int tapCount = 0); + + TouchData* getTouchData() const { return _touchData.get(); } + bool isMultiTouchEvent() const { return (_touchData.valid()); } + + + typedef std::vector< osg::ref_ptr > PointerDataList; + void setPointerDataList(const PointerDataList& pdl) { _pointerDataList = pdl; } + PointerDataList& getPointerDataList() { return _pointerDataList; } + const PointerDataList& getPointerDataList() const { return _pointerDataList; } + + unsigned int getNumPointerData() const { return static_cast(_pointerDataList.size()); } + PointerData* getPointerData(unsigned int i) { return _pointerDataList[i].get(); } + const PointerData* getPointerData(unsigned int i) const { return _pointerDataList[i].get(); } + + PointerData* getPointerData(osg::Object* obj) { for(unsigned int i=0;i<_pointerDataList.size(); ++i) { if (_pointerDataList[i]->object==obj) return _pointerDataList[i].get(); } return 0; } + const PointerData* getPointerData(osg::Object* obj) const { for(unsigned int i=0;i<_pointerDataList.size(); ++i) { if (_pointerDataList[i]->object==obj) return _pointerDataList[i].get(); } return 0; } + void addPointerData(PointerData* pd) { _pointerDataList.push_back(pd); } + + void copyPointerDataFrom(const osgGA::GUIEventAdapter& sourceEvent); + + protected: + + /** Force users to create on heap, so that multiple referencing is safe.*/ + virtual ~GUIEventAdapter(); + + mutable bool _handled; + EventType _eventType; + double _time; + + osg::observer_ptr _context; + int _windowX; + int _windowY; + int _windowWidth; + int _windowHeight; + int _key; + int _unmodifiedKey; + int _button; + float _Xmin,_Xmax; + float _Ymin,_Ymax; + float _mx; + float _my; + int _buttonMask; + int _modKeyMask; + MouseYOrientation _mouseYOrientation; + + struct Scrolling { + ScrollingMotion motion; + float deltaX; + float deltaY; + + Scrolling() : motion(SCROLL_NONE), deltaX(0), deltaY(0) {} + Scrolling(const Scrolling& rhs) : motion(rhs.motion), deltaX(rhs.deltaX), deltaY(rhs.deltaY) {} + }; + Scrolling _scrolling; + + struct TabletPen { + float pressure; + float tiltX; + float tiltY; + float rotation; + TabletPointerType tabletPointerType; + + TabletPen() : pressure(0), tiltX(0), tiltY(0), rotation(0), tabletPointerType(UNKNOWN) {} + TabletPen(const TabletPen& rhs) : pressure(rhs.pressure), tiltX(rhs.tiltX), tiltY(rhs.tiltY), rotation(rhs.rotation), tabletPointerType(rhs.tabletPointerType) {} + }; + TabletPen _tabletPen; + + osg::ref_ptr _touchData; + + + PointerDataList _pointerDataList; +}; + +} + +#endif diff --git a/libs/include/android/osgGA/GUIEventHandler b/libs/include/android/osgGA/GUIEventHandler new file mode 100755 index 0000000..38d589a --- /dev/null +++ b/libs/include/android/osgGA/GUIEventHandler @@ -0,0 +1,138 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGGA_GUIEVENTHANDLER +#define OSGGA_GUIEVENTHANDLER 1 + +#include + +#include +#include +#include + +#include +#include +#include + + +// #define COMPILE_COMPOSITE_EVENTHANDLER + +namespace osgGA{ + +/** + +GUIEventHandler provides a basic interface for any class which wants to handle +a GUI Events. + +The GUIEvent is supplied by a GUIEventAdapter. Feedback resulting from the +handle method is supplied by a GUIActionAdapter, which allows the GUIEventHandler +to ask the GUI to take some action in response to an incoming event. + +For example, consider a Trackball Viewer class which takes mouse events and +manipulates a scene camera in response. The Trackball Viewer is a GUIEventHandler, +and receives the events via the handle method. If the user 'throws' the model, +the Trackball Viewer class can detect this via the incoming events, and +request that the GUI set up a timer callback to continually redraw the view. +This request is made via the GUIActionAdapter class. + +*/ + +class OSGGA_EXPORT GUIEventHandler : public osg::NodeCallback, public osg::Drawable::EventCallback +{ +public: + + GUIEventHandler() : _ignoreHandledEventsMask(GUIEventAdapter::NONE) {} + GUIEventHandler(const GUIEventHandler& eh,const osg::CopyOp& copyop): + osg::NodeCallback(eh, copyop), + osg::Drawable::EventCallback(eh, copyop), + _ignoreHandledEventsMask(eh._ignoreHandledEventsMask) {} + + META_Object(osgGA,GUIEventHandler); + + /** Event traversal node callback method.*/ + virtual void operator()(osg::Node* node, osg::NodeVisitor* nv); + + /** Event traversal drawable callback method.*/ + virtual void event(osg::NodeVisitor* nv, osg::Drawable* drawable); + + /** Handle events, return true if handled, false otherwise. */ + virtual bool handle(const GUIEventAdapter& ea,GUIActionAdapter& aa, osg::Object*, osg::NodeVisitor*) { return handle(ea,aa); } + + /** Convenience method that only passes on to the handle(,,,) method events that either haven't been + * handled yet, or have been handled but haven't be set to be ignored by the IgnoreHandledEventsMask. + * Note, this method is an inline method, and not appropriate for users to override, override the handle(,,,) + * method instead.*/ + inline bool handleWithCheckAgainstIgnoreHandledEventsMask(const GUIEventAdapter& ea,GUIActionAdapter& aa, osg::Object* object, osg::NodeVisitor* nv) + { + if (!ea.getHandled() || + (ea.getEventType() & _ignoreHandledEventsMask)==0) + { + bool handled = handle(ea,aa,object,nv); + if (handled) ea.setHandled(true); + return handled; + } + else + { + return false; + } + } + + /** Deprecated, Handle events, return true if handled, false otherwise. */ + virtual bool handle(const GUIEventAdapter&,GUIActionAdapter&) { return false; } + + /** Convenience method that only passes on to the handle(,) method events that either haven't been + * handled yet, or have been handled but haven't be set to be ignored by the IgnoreHandledEventsMask. + * Note, this method is an inline method, and not appropriate for users to override, override the handle(,) + * method instead.*/ + inline bool handleWithCheckAgainstIgnoreHandledEventsMask(const GUIEventAdapter& ea,GUIActionAdapter& aa) + { + if (!ea.getHandled() || + (ea.getEventType() & _ignoreHandledEventsMask)==0) + { + bool handled = handle(ea,aa); + if (handled) ea.setHandled(true); + return handled; + } + else + { + return false; + } + } + + /** Get the keyboard and mouse usage of this manipulator.*/ + virtual void getUsage(osg::ApplicationUsage&) const {} + + /** Set a mask of osgGA::GUIEeventAdapter::Event to be ignored if marked as handled */ + void setIgnoreHandledEventsMask(unsigned int mask) { _ignoreHandledEventsMask = mask; } + + /** Get the event mask of the osgGA::GUIEeventAdapter::Event to be ignored if marked as handled */ + unsigned int getIgnoreHandledEventsMask() const { return _ignoreHandledEventsMask; }; + +protected: + unsigned int _ignoreHandledEventsMask; + +}; + +#ifdef USE_DEPRECATED_API + // keep for backwards compatibility + class GUIEventHandlerVisitor + { + public: + + void visit(GUIEventHandler&) {} + }; +#endif + +} + +#endif diff --git a/libs/include/android/osgGA/KeySwitchMatrixManipulator b/libs/include/android/osgGA/KeySwitchMatrixManipulator new file mode 100755 index 0000000..78367a7 --- /dev/null +++ b/libs/include/android/osgGA/KeySwitchMatrixManipulator @@ -0,0 +1,136 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGUTIL_KEYSWITCMATRIXMANIPULATOR +#define OSGUTIL_KEYSWITCMATRIXMANIPULATOR 1 + +#include +#include +#include + +namespace osgGA{ + +class GUIActionAdapter; + +/** +KeySwitchMatrixManipulator is a decorator which allows the type of camera manipulator +being used to be switched by pressing a key. E.g. '1' for a TrackballManipulator, +'2' for a DriveManipulator, '3' for a FlightManipulator. The manipulators available, +and the associated switch keys, can be configured. +*/ +class OSGGA_EXPORT KeySwitchMatrixManipulator : public CameraManipulator +{ + public: + + typedef std::pair > NamedManipulator; + typedef std::map KeyManipMap; + + virtual const char* className() const { return "KeySwitchMatrixManipulator"; } + + /** + Add a camera manipulator with an associated name, and a key to + trigger the switch, + */ + void addMatrixManipulator(int key, std::string name, CameraManipulator *cm); + + /** + Add a camera manipulator with an autogenerated keybinding which is '1' + previous number of camera's registerd. + */ + void addNumberedMatrixManipulator(CameraManipulator *cm); + + unsigned int getNumMatrixManipulators() const { return _manips.size(); } + + void selectMatrixManipulator(unsigned int num); + + /** Get the complete list of manipulators attached to this keyswitch manipulator.*/ + KeyManipMap& getKeyManipMap() { return _manips; } + + /** Get the const complete list of manipulators attached to this keyswitch manipulator.*/ + const KeyManipMap& getKeyManipMap() const { return _manips; } + + + /** Get the current active manipulators.*/ + CameraManipulator* getCurrentMatrixManipulator() { return _current.get(); } + + /** Get the const current active manipulators.*/ + const CameraManipulator* getCurrentMatrixManipulator() const { return _current.get(); } + + + /** Get manipulator assigned to a specified index.*/ + CameraManipulator* getMatrixManipulatorWithIndex(unsigned int key); + + /** Get const manipulator assigned to a specified index.*/ + const CameraManipulator* getMatrixManipulatorWithIndex(unsigned int key) const; + + /** Get manipulator assigned to a specified key.*/ + CameraManipulator* getMatrixManipulatorWithKey(unsigned int key); + + /** Get const manipulator assigned to a specified key.*/ + const CameraManipulator* getMatrixManipulatorWithKey(unsigned int key) const; + + + // Overrides from CameraManipulator... + + /** set the coordinate frame which callback tells the manipulator which way is up, east and north.*/ + virtual void setCoordinateFrameCallback(CoordinateFrameCallback* cb); + + /** Set the position of the matrix manipulator using a 4x4 Matrix.*/ + virtual void setByMatrix(const osg::Matrixd& matrix) { _current->setByMatrix(matrix); } + + /** set the position of the matrix manipulator using a 4x4 Matrix.*/ + virtual void setByInverseMatrix(const osg::Matrixd& matrix) { _current->setByInverseMatrix(matrix); } + + /** get the position of the manipulator as 4x4 Matrix.*/ + virtual osg::Matrixd getMatrix() const { return _current->getMatrix(); } + + /** get the position of the manipulator as a inverse matrix of the manipulator, typically used as a model view matrix.*/ + virtual osg::Matrixd getInverseMatrix() const { return _current->getInverseMatrix(); } + + /** Get the FusionDistanceMode. Used by SceneView for setting up stereo convergence.*/ + virtual osgUtil::SceneView::FusionDistanceMode getFusionDistanceMode() const { return _current->getFusionDistanceMode(); } + + /** Get the FusionDistanceValue. Used by SceneView for setting up stereo convergence.*/ + virtual float getFusionDistanceValue() const { return _current->getFusionDistanceValue(); } + + + virtual void setNode(osg::Node* n); + + virtual const osg::Node* getNode() const { return _current->getNode(); } + + virtual osg::Node* getNode() { return _current->getNode(); } + + virtual void setHomePosition(const osg::Vec3d& eye, const osg::Vec3d& center, const osg::Vec3d& up, bool autoComputeHomePosition=false); + + virtual void setAutoComputeHomePosition(bool flag); + + virtual void computeHomePosition(); + + virtual void home(const GUIEventAdapter& ee,GUIActionAdapter& aa); + + virtual void init(const GUIEventAdapter& ee,GUIActionAdapter& aa) { if (_current.valid()) _current->init(ee,aa); } + + virtual bool handle(const GUIEventAdapter& ea,GUIActionAdapter& us); + + /** Get the keyboard and mouse usage of this manipulator.*/ + virtual void getUsage(osg::ApplicationUsage& usage) const; + + private: + + KeyManipMap _manips; + + osg::ref_ptr _current; +}; + +} + +#endif diff --git a/libs/include/android/osgGA/MultiTouchTrackballManipulator b/libs/include/android/osgGA/MultiTouchTrackballManipulator new file mode 100755 index 0000000..5b8ba08 --- /dev/null +++ b/libs/include/android/osgGA/MultiTouchTrackballManipulator @@ -0,0 +1,47 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2010 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGGA_MULTITOUCH_TRACKBALL_MANIPULATOR +#define OSGGA_MULTITOUCH_TRACKBALL_MANIPULATOR 1 + +#include + + +namespace osgGA { + + +class OSGGA_EXPORT MultiTouchTrackballManipulator : public TrackballManipulator +{ + typedef TrackballManipulator inherited; + + public: + + MultiTouchTrackballManipulator( int flags = DEFAULT_SETTINGS ); + MultiTouchTrackballManipulator( const MultiTouchTrackballManipulator& tm, + const osg::CopyOp& copyOp = osg::CopyOp::SHALLOW_COPY ); + + META_Object( osgGA, MultiTouchTrackballManipulator ); + + bool handle( const GUIEventAdapter& ea, GUIActionAdapter& us ); + + protected: + + void handleMultiTouchDrag(GUIEventAdapter::TouchData* now, GUIEventAdapter::TouchData* last, const double eventTimeDelta); + + osg::ref_ptr _lastTouchData; +}; + + +} + +#endif /* OSGGA_MULTITOUCH_TRACKBALL_MANIPULATOR */ diff --git a/libs/include/android/osgGA/NodeTrackerManipulator b/libs/include/android/osgGA/NodeTrackerManipulator new file mode 100755 index 0000000..01b2e0b --- /dev/null +++ b/libs/include/android/osgGA/NodeTrackerManipulator @@ -0,0 +1,107 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGGA_NODE_TRACKER_MANIPULATOR +#define OSGGA_NODE_TRACKER_MANIPULATOR 1 + +#include +#include + + +namespace osgGA { + + +class OSGGA_EXPORT NodeTrackerManipulator : public OrbitManipulator +{ + typedef OrbitManipulator inherited; + + public: + + NodeTrackerManipulator( int flags = DEFAULT_SETTINGS ); + + NodeTrackerManipulator( const NodeTrackerManipulator& om, + const osg::CopyOp& copyOp = osg::CopyOp::SHALLOW_COPY ); + + META_Object( osgGA, NodeTrackerManipulator ); + + void setTrackNodePath(const osg::NodePath& nodePath); + void setTrackNodePath(const osg::ObserverNodePath& nodePath) { _trackNodePath = nodePath; } + osg::ObserverNodePath& getTrackNodePath() { return _trackNodePath; } + + void setTrackNode(osg::Node* node); + osg::Node* getTrackNode() { osg::NodePath nodePath; return _trackNodePath.getNodePath(nodePath) && !nodePath.empty() ? nodePath.back() : 0; } + const osg::Node* getTrackNode() const { osg::NodePath nodePath; return _trackNodePath.getNodePath(nodePath) && !nodePath.empty() ? nodePath.back() : 0; } + + enum TrackerMode + { + /** Track the center of the node's bounding sphere, but not rotations of the node. + * For databases which have a CoordinateSystemNode, the orientation is kept relative the coordinate frame if the center of the node. + */ + NODE_CENTER, + /** Track the center of the node's bounding sphere, and the azimuth rotation (about the z axis of the current coordinate frame). + * For databases which have a CoordinateSystemNode, the orientation is kept relative the coordinate frame if the center of the node. + */ + NODE_CENTER_AND_AZIM, + /** Tack the center of the node's bounding sphere, and the all rotations of the node. + */ + NODE_CENTER_AND_ROTATION + }; + + void setTrackerMode(TrackerMode mode); + TrackerMode getTrackerMode() const { return _trackerMode; } + + + enum RotationMode + { + /** Use a trackball style manipulation of the view direction w.r.t the tracked orientation. + */ + TRACKBALL, + /** Allow the elevation and azimuth angles to be adjust w.r.t the tracked orientation. + */ + ELEVATION_AZIM + }; + + void setRotationMode(RotationMode mode); + RotationMode getRotationMode() const; + + + virtual void setByMatrix(const osg::Matrixd& matrix); + virtual osg::Matrixd getMatrix() const; + virtual osg::Matrixd getInverseMatrix() const; + + virtual void setNode(osg::Node*); + + virtual void computeHomePosition(); + + protected: + + virtual bool performMovementLeftMouseButton(const double eventTimeDelta, const double dx, const double dy); + virtual bool performMovementMiddleMouseButton(const double eventTimeDelta, const double dx, const double dy); + virtual bool performMovementRightMouseButton(const double eventTimeDelta, const double dx, const double dy); + + void computeNodeWorldToLocal(osg::Matrixd& worldToLocal) const; + void computeNodeLocalToWorld(osg::Matrixd& localToWorld) const; + + void computeNodeCenterAndRotation(osg::Vec3d& center, osg::Quat& rotation) const; + + void computePosition(const osg::Vec3d& eye,const osg::Vec3d& lv,const osg::Vec3d& up); + + + osg::ObserverNodePath _trackNodePath; + TrackerMode _trackerMode; + +}; + +} + +#endif /* OSGGA_NODE_TRACKER_MANIPULATOR */ diff --git a/libs/include/android/osgGA/OrbitManipulator b/libs/include/android/osgGA/OrbitManipulator new file mode 100755 index 0000000..3ed2bc4 --- /dev/null +++ b/libs/include/android/osgGA/OrbitManipulator @@ -0,0 +1,127 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2010 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. + * + * OrbitManipulator code Copyright (C) 2010 PCJohn (Jan Peciva) + * while some pieces of code were taken from OSG. + * Thanks to company Cadwork (www.cadwork.ch) and + * Brno University of Technology (www.fit.vutbr.cz) for open-sourcing this work. +*/ + +#ifndef OSGGA_ORBIT_MANIPULATOR +#define OSGGA_ORBIT_MANIPULATOR 1 + +#include + + +namespace osgGA { + + +/** OrbitManipulator is base class for camera control based on focal center, + distance from the center, and orientation of distance vector to the eye. + This is the base class for trackball style manipulators.*/ +class OSGGA_EXPORT OrbitManipulator : public StandardManipulator +{ + typedef StandardManipulator inherited; + + public: + + OrbitManipulator( int flags = DEFAULT_SETTINGS ); + OrbitManipulator( const OrbitManipulator& om, + const osg::CopyOp& copyOp = osg::CopyOp::SHALLOW_COPY ); + + META_Object( osgGA, OrbitManipulator ); + + virtual void setByMatrix( const osg::Matrixd& matrix ); + virtual void setByInverseMatrix( const osg::Matrixd& matrix ); + virtual osg::Matrixd getMatrix() const; + virtual osg::Matrixd getInverseMatrix() const; + + virtual void setTransformation( const osg::Vec3d& eye, const osg::Quat& rotation ); + virtual void setTransformation( const osg::Vec3d& eye, const osg::Vec3d& center, const osg::Vec3d& up ); + virtual void getTransformation( osg::Vec3d& eye, osg::Quat& rotation ) const; + virtual void getTransformation( osg::Vec3d& eye, osg::Vec3d& center, osg::Vec3d& up ) const; + + void setHeading( double azimuth ); + double getHeading() const; + void setElevation( double elevation ); + double getElevation() const; + + virtual void setCenter( const osg::Vec3d& center ); + const osg::Vec3d& getCenter() const; + virtual void setRotation( const osg::Quat& rotation ); + const osg::Quat& getRotation() const; + virtual void setDistance( double distance ); + double getDistance() const; + + virtual void setTrackballSize( const double& size ); + inline double getTrackballSize() const; + virtual void setWheelZoomFactor( double wheelZoomFactor ); + inline double getWheelZoomFactor() const; + + virtual void setMinimumDistance( const double& minimumDistance, bool relativeToModelSize = false ); + double getMinimumDistance( bool *relativeToModelSize = NULL ) const; + + virtual osgUtil::SceneView::FusionDistanceMode getFusionDistanceMode() const; + virtual float getFusionDistanceValue() const; + + protected: + + virtual bool handleMouseWheel( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& us ); + + virtual bool performMovementLeftMouseButton( const double eventTimeDelta, const double dx, const double dy ); + virtual bool performMovementMiddleMouseButton( const double eventTimeDelta, const double dx, const double dy ); + virtual bool performMovementRightMouseButton( const double eventTimeDelta, const double dx, const double dy ); + virtual bool performMouseDeltaMovement( const float dx, const float dy ); + virtual void applyAnimationStep( const double currentProgress, const double prevProgress ); + + virtual void rotateTrackball( const float px0, const float py0, + const float px1, const float py1, const float scale ); + virtual void rotateWithFixedVertical( const float dx, const float dy ); + virtual void rotateWithFixedVertical( const float dx, const float dy, const osg::Vec3f& up ); + virtual void panModel( const float dx, const float dy, const float dz = 0.f ); + virtual void zoomModel( const float dy, bool pushForwardIfNeeded = true ); + void trackball( osg::Vec3d& axis, float& angle, float p1x, float p1y, float p2x, float p2y ); + float tb_project_to_sphere( float r, float x, float y ); + virtual bool startAnimationByMousePointerIntersection( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& us ); + + osg::Vec3d _center; + osg::Quat _rotation; + double _distance; + + double _trackballSize; + double _wheelZoomFactor; + + double _minimumDistance; + static int _minimumDistanceFlagIndex; + + class OrbitAnimationData : public AnimationData { + public: + osg::Vec3d _movement; + void start( const osg::Vec3d& movement, const double startTime ); + }; + virtual void allocAnimationData() { _animationData = new OrbitAnimationData(); } +}; + + +// +// inline functions +// + +/** Get the size of the trackball relative to the model size. */ +inline double OrbitManipulator::getTrackballSize() const { return _trackballSize; } +/** Get the mouse wheel zoom factor.*/ +inline double OrbitManipulator::getWheelZoomFactor() const { return _wheelZoomFactor; } + + +} + +#endif /* OSGGA_ORBIT_MANIPULATOR */ diff --git a/libs/include/android/osgGA/SphericalManipulator b/libs/include/android/osgGA/SphericalManipulator new file mode 100755 index 0000000..e784b5c --- /dev/null +++ b/libs/include/android/osgGA/SphericalManipulator @@ -0,0 +1,178 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef __SphericalManipulator_h__ +#define __SphericalManipulator_h__ + +#include +#include +#include + +namespace osgGA +{ + +class OSGGA_EXPORT SphericalManipulator : public CameraManipulator +{ + public: + SphericalManipulator(); + + virtual const char* className() const { return "Spherical Manipulator"; } + + /** set the position of the matrix manipulator using a 4x4 Matrix.*/ + virtual void setByMatrix(const osg::Matrixd& matrix); + + /** set the position of the matrix manipulator using a 4x4 Matrix.*/ + virtual void setByInverseMatrix(const osg::Matrixd& matrix) { setByMatrix(osg::Matrixd::inverse(matrix)); } + + /** get the position of the manipulator as 4x4 Matrix.*/ + virtual osg::Matrixd getMatrix() const; + + /** get the position of the manipulator as a inverse matrix of the manipulator, typically used as a model view matrix.*/ + virtual osg::Matrixd getInverseMatrix() const; + + /** Get the FusionDistanceMode. Used by SceneView for setting up stereo convergence.*/ + virtual osgUtil::SceneView::FusionDistanceMode getFusionDistanceMode() const { return osgUtil::SceneView::USE_FUSION_DISTANCE_VALUE; } + + /** Get the FusionDistanceValue. Used by SceneView for setting up stereo convergence.*/ + virtual float getFusionDistanceValue() const { return _distance; } + + /** Attach a node to the manipulator. + Automatically detaches previously attached node. + setNode(NULL) detaches previously nodes. + Is ignored by manipulators which do not require a reference model.*/ + virtual void setNode(osg::Node*); + + /** Return node if attached.*/ + virtual const osg::Node* getNode() const; + + /** Return node if attached.*/ + virtual osg::Node* getNode(); + + /** Move the camera to the default position. + May be ignored by manipulators if home functionality is not appropriate.*/ + virtual void home(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter& us); + virtual void home(double); + + /** Start/restart the manipulator.*/ + virtual void init(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter& us); + + void zoomOn(const osg::BoundingSphere& bound); + + /** handle events, return true if handled, false otherwise.*/ + virtual bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter& us); + + /** Compute the home position.*/ + virtual void computeHomePosition(); + + void computeViewPosition(const osg::BoundingSphere& bound,double& scale,double& distance,osg::Vec3d& center); + + void setCenter(const osg::Vec3d& center) {_center=center;} + const osg::Vec3d& getCenter() const {return _center;} + + bool setDistance(double distance); + double getDistance() const { return _distance; } + + double getHomeDistance() const { return _homeDistance; } + + void setHeading(double azimuth) { _heading = azimuth; } + double getHeading() const {return _heading;} + + void setElevation(double elevation) { _elevation = elevation; } + double getElevtion() const {return _elevation;} + + + /** get the minimum distance (as ratio) the eye point can be zoomed in */ + double getMinimumZoomScale() const { return _minimumZoomScale; } + + /** set the minimum distance (as ratio) the eye point can be zoomed in towards the + center before the center is pushed forward.*/ + void setMinimumZoomScale(double minimumZoomScale) {_minimumZoomScale=minimumZoomScale;} + + + /** set the mouse scroll wheel zoom delta. + * Range -1.0 to +1.0, -ve value inverts wheel direction and zero switches off scroll wheel. */ + void setScroolWheelZoomDelta(double zoomDelta) { _zoomDelta = zoomDelta; } + + /** get the mouse scroll wheel zoom delta. */ + double getScroolWheelZoomDelta() const { return _zoomDelta; } + + + /** Get the keyboard and mouse usage of this manipulator.*/ + virtual void getUsage(osg::ApplicationUsage& usage) const; + + enum RotationMode + { + ELEVATION_HEADING=0, + HEADING, + ELEVATION, + MAP + }; + + RotationMode getRotationMode() const {return _rotationMode;} + void setRotationMode(RotationMode mode); + + /** Returns true if the camera can be thrown, false otherwise. This defaults to true. */ + bool getAllowThrow() const { return _allowThrow; } + /** Set the 'allow throw' flag. Releasing the mouse button while moving the camera results in a throw. */ + void setAllowThrow(bool allowThrow) { _allowThrow = allowThrow; } + + protected: + + virtual ~SphericalManipulator(); + + /** Reset the internal GUIEvent stack.*/ + void flushMouseEventStack(); + /** Add the current mouse GUIEvent to internal stack.*/ + void addMouseEvent(const osgGA::GUIEventAdapter& ea); + + /** For the give mouse movement calculate the movement of the camera. + Return true is camera has moved and a redraw is required.*/ + bool calcMovement(); + + /** Check the speed at which the mouse is moving. + If speed is below a threshold then return false, otherwise return true.*/ + bool isMouseMoving(); + + // Internal event stack comprising last two mouse events. + osg::ref_ptr _ga_t1; + osg::ref_ptr _ga_t0; + + osg::observer_ptr _node; + + double _modelScale; + double _minimumZoomScale; + + bool _thrown; + bool _allowThrow; + + /** The approximate amount of time it is currently taking to draw a frame. + * This is used to compute the delta in translation/rotation during a thrown display update. + * It allows us to match an delta in position/rotation independent of the rendering frame rate. + */ + double _delta_frame_time; + + /** The time the last frame started. + * Used when _rate_sensitive is true so that we can match display update rate to rotation/translation rate. + */ + double _last_frame_time; + + RotationMode _rotationMode; + osg::Vec3d _center; + double _distance; + double _heading; // angle from x axis in xy plane + double _elevation; // angle from xy plane, positive upwards towards the z axis + double _homeDistance; + double _zoomDelta; +}; +} +#endif diff --git a/libs/include/android/osgGA/StandardManipulator b/libs/include/android/osgGA/StandardManipulator new file mode 100755 index 0000000..cc11732 --- /dev/null +++ b/libs/include/android/osgGA/StandardManipulator @@ -0,0 +1,203 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2010 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. + * + * StandardManipulator code Copyright (C) 2010 PCJohn (Jan Peciva) + * while some pieces of code were taken from OSG. + * Thanks to company Cadwork (www.cadwork.ch) and + * Brno University of Technology (www.fit.vutbr.cz) for open-sourcing this work. +*/ + +#ifndef OSGGA_CAMERA_MANIPULATOR +#define OSGGA_CAMERA_MANIPULATOR 1 + +#include + + +namespace osgGA { + + +/** StandardManipulator class provides basic functionality + for user controlled manipulation.*/ +class OSGGA_EXPORT StandardManipulator : public CameraManipulator +{ + typedef CameraManipulator inherited; + + public: + + // flags + enum UserInteractionFlags + { + UPDATE_MODEL_SIZE = 0x01, + COMPUTE_HOME_USING_BBOX = 0x02, + PROCESS_MOUSE_WHEEL = 0x04, + SET_CENTER_ON_WHEEL_FORWARD_MOVEMENT = 0x08, + DEFAULT_SETTINGS = UPDATE_MODEL_SIZE /*| COMPUTE_HOME_USING_BBOX*/ | PROCESS_MOUSE_WHEEL + }; + + StandardManipulator( int flags = DEFAULT_SETTINGS ); + StandardManipulator( const StandardManipulator& m, + const osg::CopyOp& copyOp = osg::CopyOp::SHALLOW_COPY ); + + // We are not using META_Object as this is abstract class. + // Use META_Object(osgGA,YourManipulator); in your descendant non-abstract classes. + virtual const char* className() const { return "StandardManipulator"; } + + /** Sets manipulator by eye position and eye orientation.*/ + virtual void setTransformation( const osg::Vec3d& eye, const osg::Quat& rotation ) = 0; + + /** Sets manipulator by eye position, center of rotation, and up vector.*/ + virtual void setTransformation( const osg::Vec3d& eye, const osg::Vec3d& center, const osg::Vec3d& up ) = 0; + + /** Gets manipulator's eye position and eye orientation.*/ + virtual void getTransformation( osg::Vec3d& eye, osg::Quat& rotation ) const = 0; + + /** Gets manipulator's focal center, eye position, and up vector.*/ + virtual void getTransformation( osg::Vec3d& eye, osg::Vec3d& center, osg::Vec3d& up ) const = 0; + + virtual void setNode( osg::Node* ); + virtual const osg::Node* getNode() const; + virtual osg::Node* getNode(); + + virtual void setVerticalAxisFixed( bool value ); + inline bool getVerticalAxisFixed() const; + inline bool getAllowThrow() const; + virtual void setAllowThrow( bool allowThrow ); + + virtual void setAnimationTime( const double t ); + double getAnimationTime() const; + bool isAnimating() const; + virtual void finishAnimation(); + + virtual void home( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& us ); + virtual void home( double ); + + virtual void init( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& us ); + virtual bool handle( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& us ); + virtual void getUsage( osg::ApplicationUsage& usage ) const; + + protected: + + virtual bool handleFrame( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& us ); + virtual bool handleResize( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& us ); + virtual bool handleMouseMove( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& us ); + virtual bool handleMouseDrag( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& us ); + virtual bool handleMousePush( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& us ); + virtual bool handleMouseRelease( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& us ); + virtual bool handleKeyDown( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& us ); + virtual bool handleKeyUp( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& us ); + virtual bool handleMouseWheel( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& us ); + virtual bool handleMouseDeltaMovement( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& us ); + + virtual bool performMovement(); + virtual bool performMovementLeftMouseButton( const double eventTimeDelta, const double dx, const double dy ); + virtual bool performMovementMiddleMouseButton( const double eventTimeDelta, const double dx, const double dy ); + virtual bool performMovementRightMouseButton( const double eventTimeDelta, const double dx, const double dy ); + virtual bool performMouseDeltaMovement( const float dx, const float dy ); + virtual bool performAnimationMovement( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& us ); + virtual void applyAnimationStep( const double currentProgress, const double prevProgress ); + + void addMouseEvent( const osgGA::GUIEventAdapter& ea ); + void flushMouseEventStack(); + virtual bool isMouseMoving() const; + float getThrowScale( const double eventTimeDelta ) const; + virtual void centerMousePointer( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& us ); + + static void rotateYawPitch( osg::Quat& rotation, const double yaw, const double pitch, + const osg::Vec3d& localUp = osg::Vec3d( 0.,0.,0.) ); + static void fixVerticalAxis( osg::Quat& rotation, const osg::Vec3d& localUp, bool disallowFlipOver ); + void fixVerticalAxis( osg::Vec3d& eye, osg::Quat& rotation, bool disallowFlipOver ); + static void fixVerticalAxis( const osg::Vec3d& forward, const osg::Vec3d& up, osg::Vec3d& newUp, + const osg::Vec3d& localUp, bool disallowFlipOver ); + virtual bool setCenterByMousePointerIntersection( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& us ); + virtual bool startAnimationByMousePointerIntersection( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& us ); + + // mouse state + bool _thrown; + bool _allowThrow; + float _mouseCenterX, _mouseCenterY; + + // internal event stack comprising last two mouse events. + osg::ref_ptr< const osgGA::GUIEventAdapter > _ga_t1; + osg::ref_ptr< const osgGA::GUIEventAdapter > _ga_t0; + + /** The approximate amount of time it is currently taking to draw a frame. + * This is used to compute the delta in translation/rotation during a thrown display update. + * It allows us to match an delta in position/rotation independent of the rendering frame rate. + */ + double _delta_frame_time; + + /** The time the last frame started. + * Used when _rate_sensitive is true so that we can match display update rate to rotation/translation rate. + */ + double _last_frame_time; + + // scene data + osg::ref_ptr< osg::Node > _node; + double _modelSize; + bool _verticalAxisFixed; + + // animation stuff + class OSGGA_EXPORT AnimationData : public osg::Referenced { + public: + double _animationTime; + bool _isAnimating; + double _startTime; + double _phase; + AnimationData(); + void start( const double startTime ); + }; + osg::ref_ptr< AnimationData > _animationData; + virtual void allocAnimationData() { _animationData = new AnimationData(); } + + // flags + int _flags; + + // flags indicating that a value is relative to model size + int _relativeFlags; + inline bool getRelativeFlag( int index ) const; + inline void setRelativeFlag( int index, bool value ); + static int numRelativeFlagsAllocated; + static int allocateRelativeFlag(); +}; + + +// +// inline methods +// + +inline bool StandardManipulator::getRelativeFlag( int index ) const +{ + return ( _relativeFlags & (0x01 << index) ) != 0; +} + +inline void StandardManipulator::setRelativeFlag( int index, bool value ) +{ + if( value ) _relativeFlags |= (0x01 << index); + else _relativeFlags &= (~0x01 << index); +} + +/// Returns whether manipulator preserves camera's "UP" vector. +inline bool StandardManipulator::getVerticalAxisFixed() const +{ + return _verticalAxisFixed; +} + +/// Returns true if the camera can be thrown, false otherwise. It defaults to true. +inline bool StandardManipulator::getAllowThrow() const +{ + return _allowThrow; +} + + +} + +#endif /* OSGGA_CAMERA_MANIPULATOR */ diff --git a/libs/include/android/osgGA/StateSetManipulator b/libs/include/android/osgGA/StateSetManipulator new file mode 100755 index 0000000..ee4aef4 --- /dev/null +++ b/libs/include/android/osgGA/StateSetManipulator @@ -0,0 +1,110 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGGA_STATESET_MANIPULATOR +#define OSGGA_STATESET_MANIPULATOR 1 + +#include +#include +#include +#include + +#include +#include + + +namespace osgGA { + +/** +Experimental class, not been looked at for a while, but which will +be returned to at some point :-\ +*/ +class OSGGA_EXPORT StateSetManipulator : public GUIEventHandler +{ +public: + + StateSetManipulator(osg::StateSet* stateset=0); + + virtual const char* className() const { return "StateSetManipulator"; } + + /** attach a StateSet to the manipulator to be used for specifying view.*/ + virtual void setStateSet(osg::StateSet*); + + /** get the attached a StateSet.*/ + virtual osg::StateSet * getStateSet(); + + /** get the attached a StateSet.*/ + virtual const osg::StateSet * getStateSet() const; + + + /** Handle events, return true if handled, false otherwise.*/ + virtual bool handle(const GUIEventAdapter& ea,GUIActionAdapter& us); + + /** Get the keyboard and mouse usage of this manipulator.*/ + virtual void getUsage(osg::ApplicationUsage& usage) const; + + void setMaximumNumOfTextureUnits(unsigned int i) { _maxNumOfTextureUnits = i; } + unsigned int getMaximumNumOfTextureUnits() const { return _maxNumOfTextureUnits; } + + void setBackfaceEnabled(bool newbackface); + bool getBackfaceEnabled() const {return _backface;}; + + void setLightingEnabled(bool newlighting); + bool getLightingEnabled() const {return _lighting;}; + + void setTextureEnabled(bool newtexture); + bool getTextureEnabled() const {return _texture;}; + + void setPolygonMode(osg::PolygonMode::Mode newpolygonmode); + osg::PolygonMode::Mode getPolygonMode() const; + + void cyclePolygonMode(); + + + void setKeyEventToggleBackfaceCulling(int key) { _keyEventToggleBackfaceCulling = key; } + int getKeyEventToggleBackfaceCulling() const { return _keyEventToggleBackfaceCulling; } + + void setKeyEventToggleLighting(int key) { _keyEventToggleLighting = key; } + int getKeyEventToggleLighting() const { return _keyEventToggleLighting; } + + void setKeyEventToggleTexturing(int key) { _keyEventToggleTexturing = key; } + int getKeyEventToggleTexturing() const { return _keyEventToggleTexturing; } + + void setKeyEventCyclePolygonMode(int key) { _keyEventCyclePolygonMode = key; } + int getKeyEventCyclePolygonMode() const { return _keyEventCyclePolygonMode; } + +protected: + + virtual ~StateSetManipulator(); + + void clone(); + + osg::ref_ptr _stateset; + + bool _initialized; + bool _backface; + bool _lighting; + bool _texture; + unsigned int _maxNumOfTextureUnits; + + int _keyEventToggleBackfaceCulling; + int _keyEventToggleLighting; + int _keyEventToggleTexturing; + int _keyEventCyclePolygonMode; + + osg::PolygonMode* getOrCreatePolygonMode(); +}; + +} + +#endif diff --git a/libs/include/android/osgGA/TerrainManipulator b/libs/include/android/osgGA/TerrainManipulator new file mode 100755 index 0000000..9ed2fed --- /dev/null +++ b/libs/include/android/osgGA/TerrainManipulator @@ -0,0 +1,64 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2010 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGGA_TERRAIN_MANIPULATOR +#define OSGGA_TERRAIN_MANIPULATOR 1 + +#include + + +namespace osgGA { + + +class OSGGA_EXPORT TerrainManipulator : public OrbitManipulator +{ + typedef OrbitManipulator inherited; + +public: + + TerrainManipulator( int flags = DEFAULT_SETTINGS ); + TerrainManipulator( const TerrainManipulator& tm, + const osg::CopyOp& copyOp = osg::CopyOp::SHALLOW_COPY ); + + META_Object( osgGA, TerrainManipulator ); + + enum RotationMode + { + ELEVATION_AZIM_ROLL, + ELEVATION_AZIM + }; + + virtual void setRotationMode(RotationMode mode); + RotationMode getRotationMode() const; + + virtual void setByMatrix( const osg::Matrixd& matrix ); + + virtual void setTransformation( const osg::Vec3d& eye, const osg::Vec3d& center, const osg::Vec3d& up ); + + virtual void setNode( osg::Node* node ); + +protected: + + virtual bool performMovementMiddleMouseButton( const double eventTimeDelta, const double dx, const double dy ); + virtual bool performMovementRightMouseButton( const double eventTimeDelta, const double dx, const double dy ); + + bool intersect( const osg::Vec3d& start, const osg::Vec3d& end, osg::Vec3d& intersection ) const; + void clampOrientation(); + + osg::Vec3d _previousUp; +}; + + +} + +#endif /* OSGGA_TERRAIN_MANIPULATOR */ diff --git a/libs/include/android/osgGA/TrackballManipulator b/libs/include/android/osgGA/TrackballManipulator new file mode 100755 index 0000000..92aba55 --- /dev/null +++ b/libs/include/android/osgGA/TrackballManipulator @@ -0,0 +1,40 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2010 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGGA_TRACKBALL_MANIPULATOR +#define OSGGA_TRACKBALL_MANIPULATOR 1 + +#include + + +namespace osgGA { + + +class OSGGA_EXPORT TrackballManipulator : public OrbitManipulator +{ + typedef OrbitManipulator inherited; + + public: + + TrackballManipulator( int flags = DEFAULT_SETTINGS ); + TrackballManipulator( const TrackballManipulator& tm, + const osg::CopyOp& copyOp = osg::CopyOp::SHALLOW_COPY ); + + META_Object( osgGA, TrackballManipulator ); + +}; + + +} + +#endif /* OSGGA_TRACKBALL_MANIPULATOR */ diff --git a/libs/include/android/osgGA/UFOManipulator b/libs/include/android/osgGA/UFOManipulator new file mode 100755 index 0000000..985ad8d --- /dev/null +++ b/libs/include/android/osgGA/UFOManipulator @@ -0,0 +1,188 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGGA_UFO_MANIPULATOR_DEF +#define OSGGA_UFO_MANIPULATOR_DEF 1 + +#include + +#include +#include +#include + +/** + \class osgGA::UFOManipulator + \brief A UFO manipulator driven with keybindings. + + The UFOManipulator is better suited for applications that employ + architectural walk-throughs, or situations where the eyepoint motion + model must move slowly, deliberately and well controlled. + + The UFO Manipulator allows the following movements with the listed + Key combinations: + \param UpArrow Acceleration forward. + \param DownArrow Acceleration backward (or deceleration forward). + \param LeftArrow Rotate view and direction of travel to the left. + \param RightArrow Rotate view and direction of travel to the right. + \param SpaceBar Brake. Gradually decelerates linear and rotational movement. + \param Shift/UpArrow Accelerate up. + \param Shift/DownArrow Accelerate down. + \param Shift/LeftArrow Accelerate (linearly) left. + \param Shift/RightArrow Accelerate (linearly) right. + \param Shift/SpaceBar Instant brake. Immediately stop all linear and rotational movement. + +When the Shift key is released, up, down, linear left and/or linear right movement is decelerated. + + \param Ctrl/UpArrow Rotate view (but not direction of travel) up. + \param Ctrl/DownArrow Rotate view (but not direction of travel) down. + \param Ctrl/LeftArrow Rotate view (but not direction of travel) left. + \param Ctrl/RightArrow Rotate view (but not direction of travel) right. + \param Ctrl/Return Straightens out the view offset. + +*/ + +namespace osgGA { + +class OSGGA_EXPORT UFOManipulator : public osgGA::CameraManipulator +{ + + public: + /** Default constructor */ + UFOManipulator(); + + /** return className + \return returns constant "UFO" + */ + virtual const char* className() const; + + /** Set the current position with a matrix + \param matrix A viewpoint matrix. + */ + virtual void setByMatrix( const osg::Matrixd &matrix ) ; + + /** Set the current position with the inverse matrix + \param invmat The inverse of a viewpoint matrix + */ + virtual void setByInverseMatrix( const osg::Matrixd &invmat); + + /** Get the current viewmatrix */ + virtual osg::Matrixd getMatrix() const; + + /** Get the current inverse view matrix */ + virtual osg::Matrixd getInverseMatrix() const ; + + /** Set the subgraph this manipulator is driving the eye through. + \param node root of subgraph + */ + virtual void setNode(osg::Node* node); + + /** Get the root node of the subgraph this manipulator is driving the eye through (const)*/ + virtual const osg::Node* getNode() const; + + /** Get the root node of the subgraph this manipulator is driving the eye through */ + virtual osg::Node* getNode(); + + /** Computes the home position based on the extents and scale of the + scene graph rooted at node */ + virtual void computeHomePosition(); + + /** Sets the viewpoint matrix to the home position */ + virtual void home(const osgGA::GUIEventAdapter&, osgGA::GUIActionAdapter&) ; + void home(double); + + virtual void init(const GUIEventAdapter& ,GUIActionAdapter&); + + /** Handles incoming osgGA events */ + bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter &aa); + + /** Reports Usage parameters to the application */ + void getUsage(osg::ApplicationUsage& usage) const; + + /** Report the current position as LookAt vectors */ + void getCurrentPositionAsLookAt( osg::Vec3d& eye, osg::Vec3d& center, osg::Vec3d& up ); + + + void setMinHeight( double in_min_height ) { _minHeightAboveGround = in_min_height; } + double getMinHeight() const { return _minHeightAboveGround; } + + void setMinDistance( double in_min_dist ) { _minDistanceInFront = in_min_dist; } + double getMinDistance() const { return _minDistanceInFront; } + + void setForwardSpeed( double in_fs ) { _forwardSpeed = in_fs; } + double getForwardSpeed() const { return _forwardSpeed; } + + void setSideSpeed( double in_ss ) { _sideSpeed = in_ss; } + double getSideSpeed() const { return _sideSpeed; } + + void setRotationSpeed( double in_rot_speed ) { _directionRotationRate = in_rot_speed; } + double getRotationSpeed() const { return _directionRotationRate; } + + + protected: + + virtual ~UFOManipulator(); + + bool intersect(const osg::Vec3d& start, const osg::Vec3d& end, osg::Vec3d& intersection) const; + + osg::observer_ptr _node; + float _viewAngle; + osg::Matrixd _matrix; + osg::Matrixd _inverseMatrix; + osg::Matrixd _offset; + + double _minHeightAboveGround; + double _minDistanceInFront; + + double _speedEpsilon; + double _forwardSpeed; + double _sideSpeed; + double _upSpeed; + double _speedAccelerationFactor; + double _speedDecelerationFactor; + + bool _decelerateUpSideRate; + + double _directionRotationEpsilon; + double _directionRotationRate; + double _directionRotationAcceleration; + double _directionRotationDeceleration; + + double _viewOffsetDelta; + double _pitchOffsetRate; + double _pitchOffset; + double _yawOffsetRate; + double _yawOffset; + + double _t0; + double _dt; + osg::Vec3d _direction; + osg::Vec3d _position; + + + bool _shift; + bool _ctrl; + bool _decelerateOffsetRate; + + bool _straightenOffset; + + void _stop(); + void _keyDown( const osgGA::GUIEventAdapter &ea, osgGA::GUIActionAdapter &); + void _keyUp( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter &); + void _frame(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter &); + + void _adjustPosition(); +}; + +} + +#endif diff --git a/libs/include/android/osgGA/Version b/libs/include/android/osgGA/Version new file mode 100755 index 0000000..ddd30e8 --- /dev/null +++ b/libs/include/android/osgGA/Version @@ -0,0 +1,48 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGGA_VERSION +#define OSGGA_VERSION 1 + +#include + + +extern "C" { + +/** + * osgGAGetVersion() returns the library version number. + * Numbering convention : OpenSceneGraph-1.0 will return 1.0 from osgGAGetVersion. + * + * This C function can be also used to check for the existence of the OpenSceneGraph + * library using autoconf and its m4 macro AC_CHECK_LIB. + * + * Here is the code to add to your configure.in: + \verbatim + # + # Check for the OpenSceneGraph (OSG) GA library + # + AC_CHECK_LIB(osg, osgGAGetVersion, , + [AC_MSG_ERROR(OpenSceneGraph GA library not found. See http://www.openscenegraph.org)],) + \endverbatim +*/ +extern OSGGA_EXPORT const char* osgGAGetVersion(); + +/** + * getLibraryName_osgGA() returns the library name in human friendly form. +*/ +extern OSGGA_EXPORT const char* osgGAGetLibraryName(); + +} + +#endif + diff --git a/libs/include/android/osgManipulator/AntiSquish b/libs/include/android/osgManipulator/AntiSquish new file mode 100755 index 0000000..c81805f --- /dev/null +++ b/libs/include/android/osgManipulator/AntiSquish @@ -0,0 +1,84 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +//osgDragger - Copyright (C) 2007 Fugro-Jason B.V. + +#ifndef _OSG_ANTISQUISH_ +#define _OSG_ANTISQUISH_ 1 + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace osgManipulator { + +/** + * Class that performs the Anti Squish by making the scaling uniform along all axes. + */ +class OSGMANIPULATOR_EXPORT AntiSquish: public osg::MatrixTransform +{ + public : + AntiSquish(); + AntiSquish(const osg::Vec3d& pivot); + AntiSquish(const osg::Vec3d& pivot, const osg::Vec3d& position); + AntiSquish(const AntiSquish& pat, const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY); + + virtual osg::Object* cloneType() const { return new AntiSquish(); } + + virtual osg::Object* clone(const osg::CopyOp& copyop) const { return new AntiSquish (*this,copyop); } + + virtual bool isSameKindAs(const osg::Object* obj) const { return dynamic_cast(obj)!=NULL; } + + void setPivot(const osg::Vec3d& pvt) + { + _pivot = pvt; + _usePivot = true; + _dirty = true; + } + + const osg::Vec3d& getPivot() const { return _pivot; } + + void setPosition(const osg::Vec3d& pos) + { + _position = pos; + _usePosition = true; + _dirty = true; + } + + const osg::Vec3d& getPosition() const { return _position; } + + virtual ~AntiSquish(); + + osg::Matrix computeUnSquishedMatrix(const osg::Matrix&, bool& flag); + + protected: + + osg::NodeCallback* _asqCallback; + + osg::Vec3d _pivot; + bool _usePivot; + + osg::Vec3d _position; + bool _usePosition; + + bool _dirty; + osg::Matrix _cachedLocalToWorld; +}; + +} +#endif diff --git a/libs/include/android/osgManipulator/Command b/libs/include/android/osgManipulator/Command new file mode 100755 index 0000000..1227177 --- /dev/null +++ b/libs/include/android/osgManipulator/Command @@ -0,0 +1,338 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +//osgManipulator - Copyright (C) 2007 Fugro-Jason B.V. + +#ifndef OSGMANIPULATOR_COMMAND +#define OSGMANIPULATOR_COMMAND 1 + +#include + +#include +#include +#include + +#include + +namespace osgManipulator { + + +/** Base class for motion commands that are generated by draggers. */ +class OSGMANIPULATOR_EXPORT MotionCommand : public osg::Referenced +{ + public: + + /** + * Motion command are based on click-drag-release actions. So each + * command needs to indicate which stage of the motion the command + * represents. + */ + enum Stage + { + NONE, + /** Click or pick start. */ + START, + /** Drag or pick move. */ + MOVE, + /** Release or pick finish. */ + FINISH + }; + + MotionCommand(); + + /** create a MotionCommand that is the inverse of this command, and if applied will undo this commands changes. */ + virtual MotionCommand* createCommandInverse() = 0; + + /** + * Gets the matrix for transforming the object being dragged. This matrix is in the + * command's coordinate systems. + */ + virtual osg::Matrix getMotionMatrix() const = 0; + + virtual void accept(const Constraint& constraint) { constraint.constrain(*this); } + virtual void accept(DraggerCallback& callback) { callback.receive(*this); } + + /** + * Sets the matrix for transforming the command's local coordinate + * system to the world/object coordinate system. + */ + void setLocalToWorldAndWorldToLocal(const osg::Matrix& localToWorld, const osg::Matrix& worldToLocal) + { + _localToWorld = localToWorld; + _worldToLocal = worldToLocal; + } + + /** + * Gets the matrix for transforming the command's local coordinate + * system to the world/object coordinate system. + */ + inline const osg::Matrix& getLocalToWorld() const { return _localToWorld; } + + /** + * Gets the matrix for transforming the command's world/object + * coordinate system to the command's local coordinate system. + */ + inline const osg::Matrix& getWorldToLocal() const { return _worldToLocal; } + + void setStage(const Stage s) { _stage = s; } + Stage getStage() const { return _stage; } + + protected: + + virtual ~MotionCommand(); + + private: + osg::Matrix _localToWorld; + osg::Matrix _worldToLocal; + + Stage _stage; +}; + + +/** + * Command for translating in a line. + */ +class OSGMANIPULATOR_EXPORT TranslateInLineCommand : public MotionCommand +{ + public: + + TranslateInLineCommand(); + + TranslateInLineCommand(const osg::LineSegment::vec_type& s, const osg::LineSegment::vec_type& e); + + virtual void accept(const Constraint& constraint) {constraint.constrain(*this); } + virtual void accept(DraggerCallback& callback) { callback.receive(*this); } + + virtual MotionCommand* createCommandInverse(); + + inline void setLine(const osg::LineSegment::vec_type& s, const osg::LineSegment::vec_type& e) { _line->start() = s; _line->end() = e; } + inline const osg::LineSegment::vec_type& getLineStart() const { return _line->start(); } + inline const osg::LineSegment::vec_type& getLineEnd() const { return _line->end(); } + + inline void setTranslation(const osg::Vec3& t) { _translation = t; } + inline const osg::Vec3d& getTranslation() const { return _translation; } + + virtual osg::Matrix getMotionMatrix() const + { + return osg::Matrix::translate(_translation); + } + + protected: + + virtual ~TranslateInLineCommand(); + + private: + osg::ref_ptr _line; + osg::Vec3d _translation; +}; + +/** + * Command for translating in a plane. + */ +class OSGMANIPULATOR_EXPORT TranslateInPlaneCommand : public MotionCommand +{ + public: + + TranslateInPlaneCommand(); + + TranslateInPlaneCommand(const osg::Plane& plane); + + virtual void accept(const Constraint& constraint) {constraint.constrain(*this); } + virtual void accept(DraggerCallback& callback) { callback.receive(*this); } + + virtual MotionCommand* createCommandInverse(); + + inline void setPlane(const osg::Plane& plane) { _plane = plane; } + inline const osg::Plane& getPlane() const { return _plane; } + + inline void setTranslation(const osg::Vec3d& t) { _translation = t; } + inline const osg::Vec3d& getTranslation() const { return _translation; } + + /** ReferencePoint is used only for snapping. */ + inline void setReferencePoint(const osg::Vec3d& rp) { _referencePoint = rp; } + inline const osg::Vec3d& getReferencePoint() const { return _referencePoint; } + + virtual osg::Matrix getMotionMatrix() const + { + return osg::Matrix::translate(_translation); + } + + protected: + + virtual ~TranslateInPlaneCommand(); + + private: + osg::Plane _plane; + osg::Vec3d _translation; + osg::Vec3d _referencePoint; +}; + +/** + * Command for 1D scaling. + */ +class OSGMANIPULATOR_EXPORT Scale1DCommand : public MotionCommand +{ + public: + + Scale1DCommand(); + + virtual void accept(const Constraint& constraint) {constraint.constrain(*this); } + virtual void accept(DraggerCallback& callback) { callback.receive(*this); } + + virtual MotionCommand* createCommandInverse(); + + inline void setScale(double s) { _scale = s; } + inline double getScale() const { return _scale; } + + inline void setScaleCenter(double center) { _scaleCenter = center; } + inline double getScaleCenter() const { return _scaleCenter; } + + /** ReferencePoint is used only for snapping. */ + inline void setReferencePoint(double rp) { _referencePoint = rp; } + inline double getReferencePoint() const { return _referencePoint; } + + inline void setMinScale(double min) { _minScale = min; } + inline double getMinScale() const { return _minScale; } + + virtual osg::Matrix getMotionMatrix() const + { + return (osg::Matrix::translate(-_scaleCenter,0.0,0.0) + * osg::Matrix::scale(_scale,1.0,1.0) + * osg::Matrix::translate(_scaleCenter,0.0,0.0)); + } + + protected: + + virtual ~Scale1DCommand(); + + private: + double _scale; + double _scaleCenter; + double _referencePoint; + double _minScale; +}; + +/** + * Command for 2D scaling. + */ +class OSGMANIPULATOR_EXPORT Scale2DCommand : public MotionCommand +{ + public: + + Scale2DCommand(); + + virtual void accept(const Constraint& constraint) {constraint.constrain(*this); } + virtual void accept(DraggerCallback& callback) { callback.receive(*this); } + + virtual MotionCommand* createCommandInverse(); + + inline void setScale(const osg::Vec2d& s) { _scale = s; } + inline const osg::Vec2d& getScale() const { return _scale; } + + inline void setScaleCenter(const osg::Vec2d& center) { _scaleCenter = center; } + inline const osg::Vec2d& getScaleCenter() const { return _scaleCenter; } + + /** ReferencePoint is used only for snapping. */ + inline void setReferencePoint(const osg::Vec2d& rp) { _referencePoint = rp; } + inline const osg::Vec2d& getReferencePoint() const { return _referencePoint; } + + inline void setMinScale(const osg::Vec2d& min) { _minScale = min; } + inline const osg::Vec2d& getMinScale() const { return _minScale; } + + virtual osg::Matrix getMotionMatrix() const + { + return (osg::Matrix::translate(-_scaleCenter[0],0.0,-_scaleCenter[1]) + * osg::Matrix::scale(_scale[0],1.0,_scale[1]) + * osg::Matrix::translate(_scaleCenter[0],0.0,_scaleCenter[1])); + } + + protected: + + virtual ~Scale2DCommand(); + + private: + osg::Vec2d _scale; + osg::Vec2d _scaleCenter; + osg::Vec2d _referencePoint; + osg::Vec2d _minScale; +}; + +/** + * Command for uniform 3D scaling. + */ +class OSGMANIPULATOR_EXPORT ScaleUniformCommand : public MotionCommand +{ + public: + + ScaleUniformCommand(); + + virtual void accept(const Constraint& constraint) {constraint.constrain(*this); } + virtual void accept(DraggerCallback& callback) { callback.receive(*this); } + + virtual MotionCommand* createCommandInverse(); + + inline void setScale(double s) { _scale = s; } + inline double getScale() const { return _scale; } + + inline void setScaleCenter(const osg::Vec3d& center) { _scaleCenter = center; } + inline const osg::Vec3d& getScaleCenter() const { return _scaleCenter; } + + virtual osg::Matrix getMotionMatrix() const + { + return (osg::Matrix::translate(-_scaleCenter) + * osg::Matrix::scale(_scale,_scale,_scale) + * osg::Matrix::translate(_scaleCenter)); + } + + protected: + + virtual ~ScaleUniformCommand(); + + private: + double _scale; + osg::Vec3d _scaleCenter; +}; + +/** + * Command for rotation in 3D. + */ +class OSGMANIPULATOR_EXPORT Rotate3DCommand : public MotionCommand +{ + public: + + Rotate3DCommand(); + + virtual void accept(const Constraint& constraint) {constraint.constrain(*this); } + virtual void accept(DraggerCallback& callback) { callback.receive(*this); } + + virtual MotionCommand* createCommandInverse(); + + inline void setRotation(const osg::Quat& rotation) { _rotation = rotation; } + inline const osg::Quat& getRotation() const { return _rotation; } + + virtual osg::Matrix getMotionMatrix() const + { + return osg::Matrix::rotate(_rotation); + } + + protected: + + virtual ~Rotate3DCommand(); + + private: + osg::Quat _rotation; +}; + + +} + +#endif diff --git a/libs/include/android/osgManipulator/CommandManager b/libs/include/android/osgManipulator/CommandManager new file mode 100755 index 0000000..59cee7e --- /dev/null +++ b/libs/include/android/osgManipulator/CommandManager @@ -0,0 +1,83 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +//osgManipulator - Copyright (C) 2007 Fugro-Jason B.V. + +#ifndef OSGMANIPULATOR_COMMANDMANAGER +#define OSGMANIPULATOR_COMMANDMANAGER 1 + +#include +#include +#include + +namespace osgManipulator { + +/** + * Deprecated. + * CommandManager class is now no longer required as Dragger now matains all references to Constraints and Selections (now just generic MatrixTransforms). + * To replace CommandManager usage simple replace cmdMgr->connect(*dragger, *selection) with dragger->addTransformUpdating(selection) and + * cmdMgr->connect(*dragger, *selection) with dragger->addConstaint(constraint). + */ +class CommandManager : public osg::Referenced +{ + public: + CommandManager() {} + + bool connect(Dragger& dragger, Selection& selection) + { + dragger.addTransformUpdating(&selection); + + return true; + } + + bool connect(Dragger& dragger, Constraint& constraint) + { + dragger.addConstraint(&constraint); + + return true; + } + + bool disconnect(Dragger& dragger) + { + dragger.getConstraints().clear(); + dragger.getDraggerCallbacks().clear(); + + return true; + } + + typedef std::list< osg::ref_ptr > Selections; + + Selections getConnectedSelections(Dragger& dragger) + { + Selections selections; + + for(Dragger::DraggerCallbacks::iterator itr = dragger.getDraggerCallbacks().begin(); + itr != dragger.getDraggerCallbacks().end(); + ++itr) + { + DraggerCallback* dc = itr->get(); + DraggerTransformCallback* dtc = dynamic_cast(dc); + if (dtc && dtc->getTransform()) selections.push_back(dtc->getTransform()); + } + + return selections; + } + + protected: + + virtual ~CommandManager() {} + +}; + +} + +#endif diff --git a/libs/include/android/osgManipulator/Constraint b/libs/include/android/osgManipulator/Constraint new file mode 100755 index 0000000..2e18cf8 --- /dev/null +++ b/libs/include/android/osgManipulator/Constraint @@ -0,0 +1,127 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +//osgManipulator - Copyright (C) 2007 Fugro-Jason B.V. + +#ifndef OSGMANIPULATOR_CONSTRAINT +#define OSGMANIPULATOR_CONSTRAINT 1 + +#include + +#include +#include +#include + +namespace osgManipulator { + +class MotionCommand; +class TranslateInLineCommand; +class TranslateInPlaneCommand; +class Scale1DCommand; +class Scale2DCommand; +class ScaleUniformCommand; +class Rotate3DCommand; + + +class DraggerCallback : virtual public osg::Object +{ + public: + DraggerCallback(): + osg::Object(true) {} + + DraggerCallback(const DraggerCallback&, const osg::CopyOp& /*copyop*/ = osg::CopyOp::SHALLOW_COPY): + osg::Object(true) {} + + META_Object(osgManipulator, DraggerCallback); + + /** + * Receive motion commands. Returns true on success. + */ + virtual bool receive(const MotionCommand&) { return false; } + virtual bool receive(const TranslateInLineCommand& command) { return receive((MotionCommand&)command); } + virtual bool receive(const TranslateInPlaneCommand& command) { return receive((MotionCommand&)command); } + virtual bool receive(const Scale1DCommand& command) { return receive((MotionCommand&)command); } + virtual bool receive(const Scale2DCommand& command) { return receive((MotionCommand&)command); } + virtual bool receive(const ScaleUniformCommand& command) { return receive((MotionCommand&)command); } + virtual bool receive(const Rotate3DCommand& command) { return receive((MotionCommand&)command); } +}; + + +class OSGMANIPULATOR_EXPORT Constraint : public osg::Referenced +{ + public: + + virtual bool constrain(MotionCommand&) const { return false; } + virtual bool constrain(TranslateInLineCommand& command) const { return constrain((MotionCommand&)command); } + virtual bool constrain(TranslateInPlaneCommand& command) const { return constrain((MotionCommand&)command); } + virtual bool constrain(Scale1DCommand& command) const { return constrain((MotionCommand&)command); } + virtual bool constrain(Scale2DCommand& command) const { return constrain((MotionCommand&)command); } + virtual bool constrain(ScaleUniformCommand& command) const { return constrain((MotionCommand&)command); } + virtual bool constrain(Rotate3DCommand& command) const { return constrain((MotionCommand&)command); } + +protected: + + Constraint() {} + Constraint(osg::Node& refNode) : _refNode(&refNode) {} + virtual ~Constraint() {} + + osg::Node& getReferenceNode() { return *_refNode; } + const osg::Node& getReferenceNode() const { return *_refNode; } + + const osg::Matrix& getLocalToWorld() const { return _localToWorld; } + const osg::Matrix& getWorldToLocal() const { return _worldToLocal; } + + void computeLocalToWorldAndWorldToLocal() const; + + private: + + osg::observer_ptr _refNode; + mutable osg::Matrix _localToWorld; + mutable osg::Matrix _worldToLocal; +}; + +/** + * Constraint to snap motion commands to a sugar cube grid. + */ +class OSGMANIPULATOR_EXPORT GridConstraint : public Constraint +{ + public: + + GridConstraint(osg::Node& refNode, const osg::Vec3d& origin, const osg::Vec3d& spacing); + + void setOrigin(const osg::Vec3d& origin) { _origin = origin; } + const osg::Vec3d& getOrigin() const { return _origin; } + + void setSpacing(const osg::Vec3d& spacing) { _spacing = spacing; } + const osg::Vec3d& getSpacing() const { return _spacing; } + + virtual bool constrain(TranslateInLineCommand& command) const; + virtual bool constrain(TranslateInPlaneCommand& command) const; + virtual bool constrain(Scale1DCommand& command) const; + virtual bool constrain(Scale2DCommand& command) const; + virtual bool constrain(ScaleUniformCommand& command) const; + + protected: + + virtual ~GridConstraint() {} + + private: + + osg::Vec3d _origin; + osg::Vec3d _spacing; + mutable osg::Matrix _startMatrix; + mutable osg::Matrix _matrix; +}; + +} + +#endif diff --git a/libs/include/android/osgManipulator/Dragger b/libs/include/android/osgManipulator/Dragger new file mode 100755 index 0000000..acd70bb --- /dev/null +++ b/libs/include/android/osgManipulator/Dragger @@ -0,0 +1,357 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +//osgManipulator - Copyright (C) 2007 Fugro-Jason B.V. + +#ifndef OSGMANIPULATOR_DRAGGER +#define OSGMANIPULATOR_DRAGGER 1 + +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace osgManipulator +{ + +class CompositeDragger; +class MotionCommand; +class TranslateInLineCommand; +class TranslateInPlaneCommand; +class Scale1DCommand; +class Scale2DCommand; +class ScaleUniformCommand; +class Rotate3DCommand; + +/** Computes the nodepath from the given node all the way upto the root. */ +extern OSGMANIPULATOR_EXPORT void computeNodePathToRoot(osg::Node& node, osg::NodePath& np); + + +class OSGMANIPULATOR_EXPORT DraggerTransformCallback : public DraggerCallback +{ + public: + + enum HandleCommandMask + { + HANDLE_TRANSLATE_IN_LINE = 1<<0, + HANDLE_TRANSLATE_IN_PLANE = 1<<1, + HANDLE_SCALED_1D = 1<<2, + HANDLE_SCALED_2D = 1<<3, + HANDLE_SCALED_UNIFORM = 1<<4, + HANDLE_ROTATE_3D = 1<<5, + HANDLE_ALL = 0x8ffffff + }; + + DraggerTransformCallback(osg::MatrixTransform* transform, int handleCommandMask = HANDLE_ALL); + + virtual bool receive(const MotionCommand&); + virtual bool receive(const TranslateInLineCommand& command); + virtual bool receive(const TranslateInPlaneCommand& command); + virtual bool receive(const Scale1DCommand& command); + virtual bool receive(const Scale2DCommand& command); + virtual bool receive(const ScaleUniformCommand& command); + virtual bool receive(const Rotate3DCommand& command); + + osg::MatrixTransform* getTransform() { return _transform.get(); } + const osg::MatrixTransform* getTransform() const { return _transform.get(); } + + protected: + + unsigned int _handleCommandMask; + + osg::observer_ptr _transform; + osg::Matrix _startMotionMatrix; + + osg::Matrix _localToWorld; + osg::Matrix _worldToLocal; +}; + + +class OSGMANIPULATOR_EXPORT PointerInfo +{ + public: + + PointerInfo(); + + PointerInfo(const PointerInfo& rhs): + _hitList(rhs._hitList), + _nearPoint(rhs._nearPoint), + _farPoint(rhs._farPoint), + _eyeDir(rhs._eyeDir) + { + _hitIter = _hitList.begin(); + } + + void reset() + { + _hitList.clear(); + _hitIter = _hitList.begin(); + setCamera(0); + } + + + bool completed() const { return _hitIter==_hitList.end(); } + + void next() + { + if (!completed()) ++_hitIter; + } + + typedef std::pair NodePathIntersectionPair; + typedef std::list< NodePathIntersectionPair> IntersectionList; + + + osg::Vec3d getLocalIntersectPoint() const { return _hitIter->second; } + + + + void setNearFarPoints (osg::Vec3d nearPoint, osg::Vec3d farPoint) { + _nearPoint = nearPoint; + _farPoint=farPoint; + _eyeDir = farPoint - nearPoint; + } + + const osg::Vec3d& getEyeDir() const {return _eyeDir;} + + void getNearFarPoints( osg::Vec3d& nearPoint, osg::Vec3d& farPoint) const { + nearPoint = _nearPoint; + farPoint = _farPoint; + } + + bool contains(const osg::Node* node) const; + + void setCamera(osg::Camera* camera) + { + + if (camera) + { + _MVPW = camera->getViewMatrix() * camera->getProjectionMatrix(); + if (camera->getViewport()) _MVPW.postMult(camera->getViewport()->computeWindowMatrix()); + _inverseMVPW.invert(_MVPW); + osg::Vec3d eye, center, up; + camera->getViewMatrix().getLookAt(eye, center, up); + _eyeDir = eye - center; + + } + else + { + _MVPW.makeIdentity(); + _inverseMVPW.makeIdentity(); + _eyeDir = osg::Vec3d(0,0,1); + } + + } + + void addIntersection(const osg::NodePath& nodePath, const osg::Vec3d& intersectionPoint) + { + bool needToResetHitIter = _hitList.empty(); + _hitList.push_back(NodePathIntersectionPair(nodePath, intersectionPoint)); + if (needToResetHitIter) _hitIter = _hitList.begin(); + } + + void setMousePosition(float pixel_x, float pixel_y) + { + projectWindowXYIntoObject(osg::Vec2d(pixel_x, pixel_y), _nearPoint, _farPoint); + } + + protected: + bool projectWindowXYIntoObject(const osg::Vec2d& windowCoord, osg::Vec3d& nearPoint, osg::Vec3d& farPoint) const; + + public: + IntersectionList _hitList; + IntersectionList::const_iterator _hitIter; + + protected: + + osg::Vec3d _nearPoint,_farPoint; + osg::Vec3d _eyeDir; + + osg::Matrix _MVPW; + osg::Matrix _inverseMVPW; + +}; + +/** + * Base class for draggers. Concrete draggers implement the pick event handler + * and generate motion commands (translate, rotate, ...) and sends these + * command to all the DraggerCallbacks & Transforms that are connected to the Dragger that generates the + * commands. + */ +class OSGMANIPULATOR_EXPORT Dragger : public osg::MatrixTransform +{ + public: + + + META_Node(osgManipulator,Dragger) + + /** + * Set/Get parent dragger. For simple draggers parent points to itself. + * For composite draggers parent points to the parent dragger that uses + * this dragger. + */ + virtual void setParentDragger(Dragger* parent) { _parentDragger = parent; } + Dragger* getParentDragger() { return _parentDragger; } + const Dragger* getParentDragger() const { return _parentDragger; } + + /** Returns 0 if this Dragger is not a CompositeDragger. */ + virtual const CompositeDragger* getComposite() const { return 0; } + + /** Returns 0 if this Dragger is not a CompositeDragger. */ + virtual CompositeDragger* getComposite() { return 0; } + + + void setHandleEvents(bool flag); + bool getHandleEvents() const { return _handleEvents; } + + void setActivationModKeyMask(unsigned int mask) { _activationModKeyMask = mask; } + unsigned int getActivationModKeyMask() const { return _activationModKeyMask; } + + void setActivationMouseButtonMask(unsigned int mask) { _activationMouseButtonMask = mask; } + unsigned int getActivationMouseButtonMask() const { return _activationMouseButtonMask; } + + void setActivationKeyEvent(int key) { _activationKeyEvent = key; } + int getActivationKeyEvent() const { return _activationKeyEvent; } + + + virtual void traverse(osg::NodeVisitor& nv); + + virtual bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa); + virtual bool handle(const PointerInfo&, const osgGA::GUIEventAdapter&, osgGA::GUIActionAdapter&) { return false; } + + + typedef std::vector< osg::ref_ptr > Constraints; + + void addConstraint(Constraint* constraint); + void removeConstraint(Constraint* constraint); + + Constraints& getConstraints() { return _constraints; } + const Constraints& getConstraints() const { return _constraints; } + + + typedef std::vector< osg::ref_ptr > DraggerCallbacks; + + void addDraggerCallback(DraggerCallback* dc); + void removeDraggerCallback(DraggerCallback* dc); + + DraggerCallbacks& getDraggerCallbacks() { return _draggerCallbacks; } + const DraggerCallbacks& getDraggerCallbacks() const { return _draggerCallbacks; } + + void addTransformUpdating(MatrixTransform* transform, int handleCommandMask = DraggerTransformCallback::HANDLE_ALL); + void removeTransformUpdating(MatrixTransform* transform); + + /** Setup default geometry for dragger. */ + virtual void setupDefaultGeometry() {} + + virtual bool receive(const MotionCommand& command); + virtual void dispatch(MotionCommand& command); + + void setDraggerActive(bool active) { _draggerActive = active; } + bool getDraggerActive() const { return _draggerActive; } + + /** + * Set/Get the traversal mask used by this dragger when looking for intersections during event handling. + * This is usefull to "hide" some geometry during event handling. + */ + virtual void setIntersectionMask(osg::Node::NodeMask intersectionMask) { _intersectionMask = intersectionMask; } + osg::Node::NodeMask getIntersectionMask() const { return _intersectionMask; } + + protected: + + Dragger(); + Dragger(const Dragger& rhs, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY); + + virtual ~Dragger(); + + + bool _handleEvents; + bool _draggerActive; + + unsigned int _activationModKeyMask; + unsigned int _activationMouseButtonMask; + int _activationKeyEvent; + bool _activationPermittedByModKeyMask; + bool _activationPermittedByMouseButtonMask; + bool _activationPermittedByKeyEvent; + + osgManipulator::PointerInfo _pointer; + + Dragger* _parentDragger; + + osg::ref_ptr _selfUpdater; + Constraints _constraints; + DraggerCallbacks _draggerCallbacks; + osg::Node::NodeMask _intersectionMask; + +}; + + +/** + * CompositeDragger allows to create complex draggers that are composed of a + * hierarchy of Draggers. + */ +class OSGMANIPULATOR_EXPORT CompositeDragger : public Dragger +{ + public: + + META_Node(osgManipulator,CompositeDragger) + + typedef std::vector< osg::ref_ptr > DraggerList; + + virtual const CompositeDragger* getComposite() const { return this; } + virtual CompositeDragger* getComposite() { return this; } + + virtual void setParentDragger(Dragger* parent); + + virtual bool handle(const PointerInfo& pi, const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa); + + // Composite-specific methods below + virtual bool addDragger(Dragger* dragger); + virtual bool removeDragger(Dragger* dragger); + unsigned int getNumDraggers() const { return _draggerList.size(); } + Dragger* getDragger(unsigned int i) { return _draggerList[i].get(); } + const Dragger* getDragger(unsigned int i) const { return _draggerList[i].get(); } + bool containsDragger(const Dragger* dragger) const; + DraggerList::iterator findDragger(const Dragger* dragger); + + virtual void setIntersectionMask(osg::Node::NodeMask intersectionMask); + + protected: + + CompositeDragger() {} + CompositeDragger(const CompositeDragger& rhs, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY); + + virtual ~CompositeDragger() {} + + DraggerList _draggerList; +}; + +/** + * Culls the drawable all the time. Used by draggers to have invisible geometry + * around lines and points so that they can be picked. For example, a dragger + * could have a line with an invisible cylinder around it to enable picking on + * that line. + */ +void OSGMANIPULATOR_EXPORT setDrawableToAlwaysCull(osg::Drawable& drawable); + +/** + * Convenience function for setting the material color on a node. + */ +void OSGMANIPULATOR_EXPORT setMaterialColor(const osg::Vec4& color, osg::Node& node); + +} + +#endif diff --git a/libs/include/android/osgManipulator/Export b/libs/include/android/osgManipulator/Export new file mode 100755 index 0000000..8228286 --- /dev/null +++ b/libs/include/android/osgManipulator/Export @@ -0,0 +1,44 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +//osgManipulator - Copyright (C) 2007 Fugro-Jason B.V. + +#ifndef OSGMANIPULATOR_EXPORT_ +#define OSGMANIPULATOR_EXPORT_ 1 + +#if defined(_MSC_VER) || defined(__CYGWIN__) || defined(__MINGW32__) || defined( __BCPLUSPLUS__) || defined( __MWERKS__) + # if defined( OSG_LIBRARY_STATIC ) + # define OSGMANIPULATOR_EXPORT + # elif defined( OSGMANIPULATOR_LIBRARY ) + # define OSGMANIPULATOR_EXPORT __declspec(dllexport) + # else + # define OSGMANIPULATOR_EXPORT __declspec(dllimport) + # endif +#else + # define OSGMANIPULATOR_EXPORT +#endif + +#define META_OSGMANIPULATOR_Object(library,name) \ +virtual osg::Object* cloneType() const { return new name (); } \ +virtual bool isSameKindAs(const osg::Object* obj) const { return dynamic_cast(obj)!=NULL; } \ +virtual const char* libraryName() const { return #library; }\ +virtual const char* className() const { return #name; } + + +/** + +\namespace osgManipulator + +The osgManipulator library is a NodeKit that extends the core scene graph to support 3D interactive manipulators. +*/ + +#endif diff --git a/libs/include/android/osgManipulator/Projector b/libs/include/android/osgManipulator/Projector new file mode 100755 index 0000000..634a973 --- /dev/null +++ b/libs/include/android/osgManipulator/Projector @@ -0,0 +1,310 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +//osgManipulator - Copyright (C) 2007 Fugro-Jason B.V. + +#ifndef OSGMANIPULATOR_PROJECTOR +#define OSGMANIPULATOR_PROJECTOR 1 + +#include + +#include +#include + +#include + +namespace osgManipulator { + +/** + * Base class for Projectors. Projectors maps 2D cursor motions to 3D motions. + */ +class OSGMANIPULATOR_EXPORT Projector : public osg::Referenced +{ + public: + + Projector(); + + /** + * Calculates the object/world coordinates (projectedPoint) of a window + * coordinate (pointToProject) when projected onto some shape or + * geometry (implemented in derived classes). SceneView in used for i + * projecting window coordinates into object coordinates and vice versa. + * Returns true on successful projection. + */ + virtual bool project(const PointerInfo& pi, osg::Vec3d& projectedPoint) const = 0; + + /** + * Sets the matrix for transforming the projector's local coordinate + * system to the world/object coordinate system. + */ + void setLocalToWorld(const osg::Matrix& localToWorld) + { + _localToWorld = localToWorld; + _worldToLocalDirty = true; + } + + /** + * Gets the matrix for transforming the projector's local coordinate + * system to the world/object coordinate system. + */ + inline const osg::Matrix& getLocalToWorld() const { return _localToWorld; } + + /** + * Gets the matrix for transforming the world/object coordinate + * system to the command's local coordinate system. + */ + inline const osg::Matrix& getWorldToLocal() const + { + if (_worldToLocalDirty) + { + _worldToLocal.invert(_localToWorld); + _worldToLocalDirty = false; + } + return _worldToLocal; + } + + protected: + + virtual ~Projector(); + + osg::Matrix _localToWorld; + mutable osg::Matrix _worldToLocal; + + mutable bool _worldToLocalDirty; +}; + + +/** + * LineProjector projects points onto the closest point on the given line. + */ +class OSGMANIPULATOR_EXPORT LineProjector : public Projector +{ + public: + + LineProjector(); + + LineProjector(const osg::LineSegment::vec_type& s, const osg::LineSegment::vec_type& e); + + inline void setLine(const osg::LineSegment::vec_type& s, const osg::LineSegment::vec_type& e) { _line->start() = s; _line->end() = e; } + + inline const osg::LineSegment::vec_type& getLineStart() const { return _line->start(); } + inline osg::LineSegment::vec_type& getLineStart() { return _line->start(); } + + inline const osg::LineSegment::vec_type& getLineEnd() const { return _line->end(); } + inline osg::LineSegment::vec_type& getLineEnd() { return _line->end(); } + + /** + * Calculates the object coordinates (projectedPoint) of a window + * coordinate (pointToProject) when projected onto the given line. + * Returns true on successful projection. + */ + virtual bool project(const PointerInfo& pi, osg::Vec3d& projectedPoint) const; + + protected: + + virtual ~LineProjector(); + + osg::ref_ptr _line; +}; + +/** + * PlaneProjector projects points onto the given line. + */ +class OSGMANIPULATOR_EXPORT PlaneProjector : public Projector +{ + public: + + PlaneProjector(); + + PlaneProjector(const osg::Plane& plane); + + inline void setPlane(const osg::Plane& plane) { _plane = plane; } + inline const osg::Plane& getPlane() const { return _plane; } + + /** + * Calculates the object coordinates (projectedPoint) of a window + * coordinate (pointToProject) when projected onto the given plane. + * Returns true on successful projection. + */ + virtual bool project(const PointerInfo& pi, osg::Vec3d& projectedPoint) const; + + protected: + + virtual ~PlaneProjector(); + + osg::Plane _plane; +}; + +/** + * SphereProjector projects points onto the given sphere. + */ +class OSGMANIPULATOR_EXPORT SphereProjector : public Projector +{ + public: + + SphereProjector(); + + SphereProjector(osg::Sphere* sphere); + + inline void setSphere(osg::Sphere* sphere) { _sphere = sphere; } + inline const osg::Sphere* getSphere() const { return _sphere.get(); } + + /** + * Calculates the object coordinates (projectedPoint) of a window + * coordinate (pointToProject) when projected onto the given sphere. + * Returns true on successful projection. + */ + virtual bool project(const PointerInfo& pi, osg::Vec3d& projectedPoint) const; + + /** + * Returns true is the point is in front of the cylinder given the eye + * direction. + */ + bool isPointInFront(const PointerInfo& pi, const osg::Matrix& localToWorld) const; + + void setFront(bool front) { _front = front; } + + protected: + + virtual ~SphereProjector(); + + osg::ref_ptr _sphere; + bool _front; +}; + +/** + * SpherePlaneProjector projects points onto a sphere, failing which it project + * onto a plane oriented to the viewing direction. + */ +class OSGMANIPULATOR_EXPORT SpherePlaneProjector : public SphereProjector +{ + public: + + SpherePlaneProjector(); + + SpherePlaneProjector(osg::Sphere* sphere); + + /** + * Calculates the object coordinates (projectedPoint) of a window + * coordinate (pointToProject) when projected onto the given sphere. + * Returns true on successful projection. + */ + virtual bool project(const PointerInfo& pi, osg::Vec3d& projectedPoint) const; + + /** + * Returns true if the previous projection was on the sphere and false + * if the projection was on the plane. + */ + bool isProjectionOnSphere() const { return _onSphere; } + + osg::Quat getRotation(const osg::Vec3d& p1, bool p1OnSphere, + const osg::Vec3d& p2, bool p2OnSphere, + float radialFactor = 0.0f) const; + + protected: + + virtual ~SpherePlaneProjector(); + + mutable osg::Plane _plane; + mutable bool _onSphere; +}; + +/** + * CylinderProjector projects points onto the given cylinder. + */ +class OSGMANIPULATOR_EXPORT CylinderProjector : public Projector +{ + public: + + CylinderProjector(); + + CylinderProjector(osg::Cylinder* cylinder); + + inline void setCylinder(osg::Cylinder* cylinder) + { + _cylinder = cylinder; + _cylinderAxis = osg::Vec3d(0.0,0.0,1.0) * osg::Matrix(cylinder->getRotation()); + _cylinderAxis.normalize(); + } + inline const osg::Cylinder* getCylinder() const { return _cylinder.get(); } + + /** + * Calculates the object coordinates (projectedPoint) of a window + * coordinate (pointToProject) when projected onto the given plane. + * Returns true on successful projection. + */ + virtual bool project(const PointerInfo& pi, osg::Vec3d& projectedPoint) const; + + + /** + * Returns true is the point is in front of the cylinder given the eye + * direction. + */ + bool isPointInFront(const PointerInfo& pi, const osg::Matrix& localToWorld) const; + + void setFront(bool front) { _front = front; } + + protected: + + virtual ~CylinderProjector(); + + osg::ref_ptr _cylinder; + osg::Vec3d _cylinderAxis; + bool _front; +}; + +/** + * CylinderPlaneProjector projects a point onto a plane relative to the + * given cylinder. For most cases, the plane will be parallel to the + * cylinder axis oriented towards the eyepoint. When the eyepoint and + * cylinder axis are close to parallel, then it will project onto a plane + * perpendicular to the cylinder. + */ +class OSGMANIPULATOR_EXPORT CylinderPlaneProjector : public CylinderProjector +{ + public: + + CylinderPlaneProjector(); + + CylinderPlaneProjector(osg::Cylinder* cylinder); + + /** + * Calculates the object coordinates (projectedPoint) of a window + * coordinate (pointToProject) when projected onto the given plane. + * Returns true on successful projection. + * \param[in] pi Incoming intersection information + * \param[out] projectedPoint Point located on the given plane + * \return bool Whether the projection onto the plane was successful. + */ + virtual bool project(const PointerInfo& pi, osg::Vec3d& projectedPoint) const; + + /** + * Generates a rotation about the cylinder axis based upon the incoming + * projected points on the plane computed from project(). + * \param[in] p1 Initial projection point + * \param[in] p2 Second projection point + * \return osg::Quat Rotation about cylinder axis + */ + osg::Quat getRotation(const osg::Vec3d& p1, const osg::Vec3d& p2) const; + + protected: + + virtual ~CylinderPlaneProjector(); + + mutable osg::Plane _plane; + mutable osg::Vec3d _planeLineStart, _planeLineEnd; + mutable bool _parallelPlane; +}; + +} + +#endif diff --git a/libs/include/android/osgManipulator/RotateCylinderDragger b/libs/include/android/osgManipulator/RotateCylinderDragger new file mode 100755 index 0000000..93eb279 --- /dev/null +++ b/libs/include/android/osgManipulator/RotateCylinderDragger @@ -0,0 +1,72 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +//osgManipulator - Copyright (C) 2007 Fugro-Jason B.V. + +#ifndef OSGMANIPULATOR_ROTATECYLINDERDRAGGER +#define OSGMANIPULATOR_ROTATECYLINDERDRAGGER 1 + +#include +#include + +namespace osgManipulator { + +/** + * Dragger for performing 3D rotation on a cylinder. + */ +class OSGMANIPULATOR_EXPORT RotateCylinderDragger : public Dragger +{ + public: + + RotateCylinderDragger(); + + META_OSGMANIPULATOR_Object(osgManipulator,RotateCylinderDragger) + + /** + * Handle pick events on dragger and generate TranslateInLine commands. + */ + virtual bool handle(const PointerInfo& pi, const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& us); + + /** Setup default geometry for dragger. */ + void setupDefaultGeometry(); + + /** Set/Get color for dragger. */ + inline void setColor(const osg::Vec4& color) { _color = color; setMaterialColor(_color,*this); } + inline const osg::Vec4& getColor() const { return _color; } + + /** + * Set/Get pick color for dragger. Pick color is color of the dragger + * when picked. It gives a visual feedback to show that the dragger has + * been picked. + */ + inline void setPickColor(const osg::Vec4& color) { _pickColor = color; } + inline const osg::Vec4& getPickColor() const { return _pickColor; } + + + protected: + + virtual ~RotateCylinderDragger(); + + osg::ref_ptr _projector; + + osg::Vec3d _prevWorldProjPt; + osg::Matrix _startLocalToWorld, _startWorldToLocal; + osg::Quat _prevRotation; + + osg::Vec4 _color; + osg::Vec4 _pickColor; +}; + + +} + +#endif diff --git a/libs/include/android/osgManipulator/RotateSphereDragger b/libs/include/android/osgManipulator/RotateSphereDragger new file mode 100755 index 0000000..8efe313 --- /dev/null +++ b/libs/include/android/osgManipulator/RotateSphereDragger @@ -0,0 +1,72 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +//osgManipulator - Copyright (C) 2007 Fugro-Jason B.V. + +#ifndef OSGMANIPULATOR_ROTATESPHEREDRAGGER +#define OSGMANIPULATOR_ROTATESPHEREDRAGGER 1 + +#include +#include + +namespace osgManipulator { + +/** + * Dragger for performing 3D rotation on a sphere. + */ +class OSGMANIPULATOR_EXPORT RotateSphereDragger : public Dragger +{ + public: + + RotateSphereDragger(); + + META_OSGMANIPULATOR_Object(osgManipulator,RotateSphereDragger) + + /** + * Handle pick events on dragger and generate TranslateInLine commands. + */ + virtual bool handle(const PointerInfo&, const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& us); + + /** Setup default geometry for dragger. */ + void setupDefaultGeometry(); + + /** Set/Get color for dragger. */ + inline void setColor(const osg::Vec4& color) { _color = color; setMaterialColor(_color,*this); } + inline const osg::Vec4& getColor() const { return _color; } + + /** + * Set/Get pick color for dragger. Pick color is color of the dragger + * when picked. It gives a visual feedback to show that the dragger has + * been picked. + */ + inline void setPickColor(const osg::Vec4& color) { _pickColor = color; } + inline const osg::Vec4& getPickColor() const { return _pickColor; } + + protected: + + virtual ~RotateSphereDragger(); + + osg::ref_ptr _projector; + + osg::Vec3d _prevWorldProjPt; + bool _prevPtOnSphere; + osg::Matrix _startLocalToWorld, _startWorldToLocal; + osg::Quat _prevRotation; + + osg::Vec4 _color; + osg::Vec4 _pickColor; +}; + + +} + +#endif diff --git a/libs/include/android/osgManipulator/Scale1DDragger b/libs/include/android/osgManipulator/Scale1DDragger new file mode 100755 index 0000000..828cfa6 --- /dev/null +++ b/libs/include/android/osgManipulator/Scale1DDragger @@ -0,0 +1,99 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +//osgManipulator - Copyright (C) 2007 Fugro-Jason B.V. + +#ifndef OSGMANIPULATOR_SCALE1DDRAGGER +#define OSGMANIPULATOR_SCALE1DDRAGGER 1 + +#include +#include + +namespace osgManipulator { + +/** + * Dragger for performing 1D scaling. + */ +class OSGMANIPULATOR_EXPORT Scale1DDragger : public Dragger +{ + public: + + enum ScaleMode + { + SCALE_WITH_ORIGIN_AS_PIVOT = 0, + SCALE_WITH_OPPOSITE_HANDLE_AS_PIVOT + }; + + Scale1DDragger(ScaleMode scaleMode=SCALE_WITH_ORIGIN_AS_PIVOT); + + META_OSGMANIPULATOR_Object(osgManipulator,Scale1DDragger) + + /** + * Handle pick events on dragger and generate TranslateInLine commands. + */ + virtual bool handle(const PointerInfo& pi, const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& us); + + /** Setup default geometry for dragger. */ + void setupDefaultGeometry(); + + /** Set/Get min scale for dragger. */ + inline void setMinScale(double min) { _minScale = min; } + inline double getMinScale() const { return _minScale; } + + /** Set/Get color for dragger. */ + inline void setColor(const osg::Vec4& color) { _color = color; setMaterialColor(_color,*this); } + inline const osg::Vec4& getColor() const { return _color; } + + /** + * Set/Get pick color for dragger. Pick color is color of the dragger + * when picked. It gives a visual feedback to show that the dragger has + * been picked. + */ + inline void setPickColor(const osg::Vec4& color) { _pickColor = color; } + inline const osg::Vec4& getPickColor() const { return _pickColor; } + + /** Set/Get left and right handle nodes for dragger. */ + inline void setLeftHandleNode (osg::Node& node) { _leftHandleNode = &node; } + inline void setRightHandleNode(osg::Node& node) { _rightHandleNode = &node; } + inline osg::Node* getLeftHandleNode() { return _leftHandleNode.get(); } + inline const osg::Node* getLeftHandleNode() const { return _leftHandleNode.get(); } + inline osg::Node* getRightHandleNode() { return _rightHandleNode.get(); } + inline const osg::Node* getRightHandleNode() const { return _rightHandleNode.get(); } + + /** Set left/right handle position. */ + inline void setLeftHandlePosition(double pos) { _projector->getLineStart() = osg::Vec3d(pos,0.0,0.0); } + inline double getLeftHandlePosition() const { return _projector->getLineStart()[0]; } + inline void setRightHandlePosition(double pos) { _projector->getLineEnd() = osg::Vec3d(pos,0.0,0.0); } + inline double getRightHandlePosition() const { return _projector->getLineEnd()[0]; } + + protected: + + virtual ~Scale1DDragger(); + + osg::ref_ptr< LineProjector > _projector; + osg::Vec3d _startProjectedPoint; + double _scaleCenter; + double _minScale; + + osg::ref_ptr< osg::Node > _leftHandleNode; + osg::ref_ptr< osg::Node > _rightHandleNode; + + osg::Vec4 _color; + osg::Vec4 _pickColor; + + ScaleMode _scaleMode; +}; + + +} + +#endif diff --git a/libs/include/android/osgManipulator/Scale2DDragger b/libs/include/android/osgManipulator/Scale2DDragger new file mode 100755 index 0000000..e97f1ee --- /dev/null +++ b/libs/include/android/osgManipulator/Scale2DDragger @@ -0,0 +1,117 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +//osgManipulator - Copyright (C) 2007 Fugro-Jason B.V. + +#ifndef OSGMANIPULATOR_SCALE2DDRAGGER +#define OSGMANIPULATOR_SCALE2DDRAGGER 1 + +#include +#include + +namespace osgManipulator { + +/** + * Dragger for performing 2D scaling. + */ +class OSGMANIPULATOR_EXPORT Scale2DDragger : public Dragger +{ + public: + + enum ScaleMode + { + SCALE_WITH_ORIGIN_AS_PIVOT = 0, + SCALE_WITH_OPPOSITE_HANDLE_AS_PIVOT + }; + + Scale2DDragger(ScaleMode scaleMode=SCALE_WITH_ORIGIN_AS_PIVOT); + + META_OSGMANIPULATOR_Object(osgManipulator,Scale2DDragger) + + /** + * Handle pick events on dragger and generate TranslateInLine commands. + */ + virtual bool handle(const PointerInfo& pi, const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& us); + + /** Setup default geometry for dragger. */ + void setupDefaultGeometry(); + + /** Set/Get min scale for dragger. */ + inline void setMinScale(const osg::Vec2d& min) { _minScale = min; } + inline const osg::Vec2d& getMinScale() const { return _minScale; } + + /** Set/Get color for dragger. */ + inline void setColor(const osg::Vec4& color) { _color = color; setMaterialColor(_color,*this); } + inline const osg::Vec4& getColor() const { return _color; } + + /** + * Set/Get pick color for dragger. Pick color is color of the dragger + * when picked. It gives a visual feedback to show that the dragger has + * been picked. + */ + inline void setPickColor(const osg::Vec4& color) { _pickColor = color; } + inline const osg::Vec4& getPickColor() const { return _pickColor; } + + /** Set/Get the handle nodes for dragger. */ + inline void setTopLeftHandleNode (osg::Node& node) { _topLeftHandleNode = &node; } + inline osg::Node* getTopLeftHandleNode() { return _topLeftHandleNode.get(); } + inline const osg::Node* getTopLeftHandleNode() const { return _topLeftHandleNode.get(); } + inline void setBottomLeftHandleNode (osg::Node& node) { _bottomLeftHandleNode = &node; } + inline osg::Node* getBottomLeftHandleNode() { return _bottomLeftHandleNode.get(); } + inline const osg::Node* getBottomLeftHandleNode() const { return _bottomLeftHandleNode.get(); } + inline void setTopRightHandleNode(osg::Node& node) { _topRightHandleNode = &node; } + inline osg::Node* getTopRightHandleNode() { return _topRightHandleNode.get(); } + inline const osg::Node* getTopRightHandleNode() const { return _topRightHandleNode.get(); } + inline void setBottomRightHandleNode(osg::Node& node) { _bottomRightHandleNode = &node; } + inline osg::Node* getBottomRightHandleNode() { return _bottomRightHandleNode.get(); } + inline const osg::Node* getBottomRightHandleNode() const { return _bottomRightHandleNode.get(); } + + /** Set/Get the handle nodes postion for dragger. */ + inline void setTopLeftHandlePosition(const osg::Vec2d& pos) { _topLeftHandlePosition = pos; } + const osg::Vec2d& getTopLeftHandlePosition() const { return _topLeftHandlePosition; } + inline void setBottomLeftHandlePosition(const osg::Vec2d& pos) { _bottomLeftHandlePosition = pos; } + const osg::Vec2d& getBottomLeftHandlePosition() const { return _bottomLeftHandlePosition; } + inline void setTopRightHandlePosition(const osg::Vec2d& pos) { _topRightHandlePosition = pos; } + const osg::Vec2d& getTopRightHandlePosition() const { return _topRightHandlePosition; } + inline void setBottomRightHandlePosition(const osg::Vec2d& pos){ _bottomRightHandlePosition = pos; } + const osg::Vec2d& getBottomRightHandlePosition() const { return _bottomRightHandlePosition; } + + protected: + + virtual ~Scale2DDragger(); + + osg::ref_ptr< PlaneProjector > _projector; + osg::Vec3d _startProjectedPoint; + osg::Vec2d _scaleCenter; + osg::Vec2d _referencePoint; + osg::Vec2d _minScale; + + osg::ref_ptr< osg::Node > _topLeftHandleNode; + osg::ref_ptr< osg::Node > _bottomLeftHandleNode; + osg::ref_ptr< osg::Node > _topRightHandleNode; + osg::ref_ptr< osg::Node > _bottomRightHandleNode; + + osg::Vec2d _topLeftHandlePosition; + osg::Vec2d _bottomLeftHandlePosition; + osg::Vec2d _topRightHandlePosition; + osg::Vec2d _bottomRightHandlePosition; + + osg::Vec4 _color; + osg::Vec4 _pickColor; + + ScaleMode _scaleMode; +}; + + +} + +#endif diff --git a/libs/include/android/osgManipulator/ScaleAxisDragger b/libs/include/android/osgManipulator/ScaleAxisDragger new file mode 100755 index 0000000..0c26a33 --- /dev/null +++ b/libs/include/android/osgManipulator/ScaleAxisDragger @@ -0,0 +1,48 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +//osgManipulator - Copyright (C) 2007 Fugro-Jason B.V. + +#ifndef OSGMANIPULATOR_SCALEAXISDRAGGER +#define OSGMANIPULATOR_SCALEAXISDRAGGER 1 + +#include + +namespace osgManipulator { + +/** + * Dragger for performing scaling on all 3 axes. + */ +class OSGMANIPULATOR_EXPORT ScaleAxisDragger : public CompositeDragger +{ + public: + + ScaleAxisDragger(); + + META_OSGMANIPULATOR_Object(osgManipulator,ScaleAxisDragger) + + /** Setup default geometry for dragger. */ + void setupDefaultGeometry(); + + protected: + + virtual ~ScaleAxisDragger(); + + osg::ref_ptr< Scale1DDragger > _xDragger; + osg::ref_ptr< Scale1DDragger > _yDragger; + osg::ref_ptr< Scale1DDragger > _zDragger; +}; + + +} + +#endif diff --git a/libs/include/android/osgManipulator/Selection b/libs/include/android/osgManipulator/Selection new file mode 100755 index 0000000..8a99bc2 --- /dev/null +++ b/libs/include/android/osgManipulator/Selection @@ -0,0 +1,29 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +//osgManipulator - Copyright (C) 2007 Fugro-Jason B.V. + +#ifndef OSGMANIPULATOR_SELECTION +#define OSGMANIPULATOR_SELECTION 1 + +#include +#include + +namespace osgManipulator { + + +typedef osg::MatrixTransform Selection; + + +} + +#endif diff --git a/libs/include/android/osgManipulator/TabBoxDragger b/libs/include/android/osgManipulator/TabBoxDragger new file mode 100755 index 0000000..486ef6c --- /dev/null +++ b/libs/include/android/osgManipulator/TabBoxDragger @@ -0,0 +1,49 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +//osgManipulator - Copyright (C) 2007 Fugro-Jason B.V. + +#ifndef OSGMANIPULATOR_TABBOXDRAGGER +#define OSGMANIPULATOR_TABBOXDRAGGER 1 + +#include + +namespace osgManipulator { + +/** + * TabBoxDragger consists of 6 TabPlaneDraggers to form a box dragger that + * performs translation and scaling. + */ +class OSGMANIPULATOR_EXPORT TabBoxDragger : public CompositeDragger +{ + public: + + TabBoxDragger(); + + META_OSGMANIPULATOR_Object(osgManipulator,TabBoxDragger) + + /** Setup default geometry for dragger. */ + void setupDefaultGeometry(); + + void setPlaneColor(const osg::Vec4& color); + + protected: + + virtual ~TabBoxDragger(); + + std::vector< osg::ref_ptr< TabPlaneDragger > > _planeDraggers; +}; + + +} + +#endif diff --git a/libs/include/android/osgManipulator/TabBoxTrackballDragger b/libs/include/android/osgManipulator/TabBoxTrackballDragger new file mode 100755 index 0000000..c1d6f84 --- /dev/null +++ b/libs/include/android/osgManipulator/TabBoxTrackballDragger @@ -0,0 +1,48 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +//osgManipulator - Copyright (C) 2007 Fugro-Jason B.V. + +#ifndef OSGMANIPULATOR_TABBOXTRACKBALLDRAGGER +#define OSGMANIPULATOR_TABBOXTRACKBALLDRAGGER 1 + +#include +#include + +namespace osgManipulator { + +/** + * Dragger for performing rotation in all axes. + */ +class OSGMANIPULATOR_EXPORT TabBoxTrackballDragger : public CompositeDragger +{ + public: + + TabBoxTrackballDragger(); + + META_OSGMANIPULATOR_Object(osgManipulator,TabBoxTrackballDragger) + + /** Setup default geometry for dragger. */ + void setupDefaultGeometry(); + + protected: + + virtual ~TabBoxTrackballDragger(); + + osg::ref_ptr _trackballDragger; + osg::ref_ptr _tabBoxDragger; +}; + + +} + +#endif diff --git a/libs/include/android/osgManipulator/TabPlaneDragger b/libs/include/android/osgManipulator/TabPlaneDragger new file mode 100755 index 0000000..8064bf6 --- /dev/null +++ b/libs/include/android/osgManipulator/TabPlaneDragger @@ -0,0 +1,58 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +//osgManipulator - Copyright (C) 2007 Fugro-Jason B.V. + +#ifndef OSGMANIPULATOR_TABPLANEDRAGGER +#define OSGMANIPULATOR_TABPLANEDRAGGER 1 + +#include +#include +#include + +namespace osgManipulator { + +/** + * Tab plane dragger consists of a plane with tabs on it's corners and edges + * for scaling. And the plane is used as a 2D translate dragger. + */ +class OSGMANIPULATOR_EXPORT TabPlaneDragger : public CompositeDragger +{ + public: + + TabPlaneDragger(float handleScaleFactor=20.0f); + + META_OSGMANIPULATOR_Object(osgManipulator,TabPlaneDragger) + + virtual bool handle(const PointerInfo& pi, const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& us); + + /** Setup default geometry for dragger. */ + void setupDefaultGeometry(bool twoSidedHandle = true); + + void setPlaneColor(const osg::Vec4& color) { _translateDragger->setColor(color); } + + protected: + + virtual ~TabPlaneDragger(); + + osg::ref_ptr< TranslatePlaneDragger > _translateDragger; + osg::ref_ptr< Scale2DDragger > _cornerScaleDragger; + osg::ref_ptr< Scale1DDragger > _horzEdgeScaleDragger; + osg::ref_ptr< Scale1DDragger > _vertEdgeScaleDragger; + + float _handleScaleFactor; +}; + + +} + +#endif diff --git a/libs/include/android/osgManipulator/TabPlaneTrackballDragger b/libs/include/android/osgManipulator/TabPlaneTrackballDragger new file mode 100755 index 0000000..df56d7f --- /dev/null +++ b/libs/include/android/osgManipulator/TabPlaneTrackballDragger @@ -0,0 +1,50 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +//osgManipulator - Copyright (C) 2007 Fugro-Jason B.V. + +#ifndef OSGMANIPULATOR_TABPLANETRACKBALLDRAGGER +#define OSGMANIPULATOR_TABPLANETRACKBALLDRAGGER 1 + +#include +#include + +namespace osgManipulator { + +/** + * Dragger for performing rotation in all axes. + */ +class OSGMANIPULATOR_EXPORT TabPlaneTrackballDragger : public CompositeDragger +{ + public: + + TabPlaneTrackballDragger(); + + META_OSGMANIPULATOR_Object(osgManipulator,TabPlaneTrackballDragger) + + /** Setup default geometry for dragger. */ + void setupDefaultGeometry(); + + void setPlaneColor(const osg::Vec4& color) { _tabPlaneDragger->setPlaneColor(color); } + + protected: + + virtual ~TabPlaneTrackballDragger(); + + osg::ref_ptr _trackballDragger; + osg::ref_ptr _tabPlaneDragger; +}; + + +} + +#endif diff --git a/libs/include/android/osgManipulator/TrackballDragger b/libs/include/android/osgManipulator/TrackballDragger new file mode 100755 index 0000000..f4a531e --- /dev/null +++ b/libs/include/android/osgManipulator/TrackballDragger @@ -0,0 +1,50 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +//osgManipulator - Copyright (C) 2007 Fugro-Jason B.V. + +#ifndef OSGMANIPULATOR_TRACKBALLDRAGGER +#define OSGMANIPULATOR_TRACKBALLDRAGGER 1 + +#include +#include + +namespace osgManipulator { + +/** + * Dragger for performing rotation in all axes. + */ +class OSGMANIPULATOR_EXPORT TrackballDragger : public CompositeDragger +{ + public: + + TrackballDragger(bool useAutoTransform=false); + + META_OSGMANIPULATOR_Object(osgManipulator,TrackballDragger) + + /** Setup default geometry for dragger. */ + void setupDefaultGeometry(); + + protected: + + virtual ~TrackballDragger(); + + osg::ref_ptr _xDragger; + osg::ref_ptr _yDragger; + osg::ref_ptr _zDragger; + osg::ref_ptr _xyzDragger; +}; + + +} + +#endif diff --git a/libs/include/android/osgManipulator/Translate1DDragger b/libs/include/android/osgManipulator/Translate1DDragger new file mode 100755 index 0000000..eefa70c --- /dev/null +++ b/libs/include/android/osgManipulator/Translate1DDragger @@ -0,0 +1,70 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +//osgManipulator - Copyright (C) 2007 Fugro-Jason B.V. + +#ifndef OSGMANIPULATOR_TRANSLATE1DDRAGGER +#define OSGMANIPULATOR_TRANSLATE1DDRAGGER 1 + +#include +#include + +namespace osgManipulator { + + +/** + * Dragger for performing 1D translation. + */ +class OSGMANIPULATOR_EXPORT Translate1DDragger : public Dragger +{ + public: + + Translate1DDragger(); + + META_OSGMANIPULATOR_Object(osgManipulator,Translate1DDragger) + + Translate1DDragger(const osg::Vec3d& s, const osg::Vec3d& e); + + /** Handle pick events on dragger and generate TranslateInLine commands. */ + virtual bool handle(const PointerInfo& pi, const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& us); + + /** Setup default geometry for dragger. */ + void setupDefaultGeometry(); + + /** Set/Get color for dragger. */ + inline void setColor(const osg::Vec4& color) { _color = color; setMaterialColor(_color,*this); } + inline const osg::Vec4& getColor() const { return _color; } + + /** Set/Get pick color for dragger. Pick color is color of the dragger when picked. + It gives a visual feedback to show that the dragger has been picked. */ + inline void setPickColor(const osg::Vec4& color) { _pickColor = color; } + inline const osg::Vec4& getPickColor() const { return _pickColor; } + + inline void setCheckForNodeInNodePath(bool onOff) { _checkForNodeInNodePath = onOff; } + + protected: + + virtual ~Translate1DDragger(); + + osg::ref_ptr< LineProjector > _projector; + osg::Vec3d _startProjectedPoint; + + osg::Vec4 _color; + osg::Vec4 _pickColor; + + bool _checkForNodeInNodePath; +}; + + +} + +#endif diff --git a/libs/include/android/osgManipulator/Translate2DDragger b/libs/include/android/osgManipulator/Translate2DDragger new file mode 100755 index 0000000..9cb5cb6 --- /dev/null +++ b/libs/include/android/osgManipulator/Translate2DDragger @@ -0,0 +1,68 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +//osgManipulator - Copyright (C) 2007 Fugro-Jason B.V. + +#ifndef OSGMANIPULATOR_TRANSLATE2DDRAGGER +#define OSGMANIPULATOR_TRANSLATE2DDRAGGER 1 + +#include +#include + +#include + +namespace osgManipulator { + +/** + * Dragger for performing 2D translation. + */ +class OSGMANIPULATOR_EXPORT Translate2DDragger : public Dragger +{ + public: + + Translate2DDragger(); + + Translate2DDragger(const osg::Plane& plane); + + META_OSGMANIPULATOR_Object(osgManipulator,Translate2DDragger) + + /** Handle pick events on dragger and generate TranslateInLine commands. */ + virtual bool handle(const PointerInfo& pi, const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& us); + + /** Setup default geometry for dragger. */ + void setupDefaultGeometry(); + + /** Set/Get color for dragger. */ + inline void setColor(const osg::Vec4& color) { _color = color; setMaterialColor(_color,*this); } + inline const osg::Vec4& getColor() const { return _color; } + + /** Set/Get pick color for dragger. Pick color is color of the dragger when picked. + It gives a visual feedback to show that the dragger has been picked. */ + inline void setPickColor(const osg::Vec4& color) { _pickColor = color; } + inline const osg::Vec4& getPickColor() const { return _pickColor; } + + protected: + + virtual ~Translate2DDragger(); + + osg::ref_ptr< PlaneProjector > _projector; + osg::Vec3d _startProjectedPoint; + + osg::Vec4 _color; + osg::Vec4 _pickColor; + osg::ref_ptr _polygonOffset; +}; + + +} + +#endif diff --git a/libs/include/android/osgManipulator/TranslateAxisDragger b/libs/include/android/osgManipulator/TranslateAxisDragger new file mode 100755 index 0000000..863c6e8 --- /dev/null +++ b/libs/include/android/osgManipulator/TranslateAxisDragger @@ -0,0 +1,48 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +//osgManipulator - Copyright (C) 2007 Fugro-Jason B.V. + +#ifndef OSGMANIPULATOR_TRANSLATEAXISDRAGGER +#define OSGMANIPULATOR_TRANSLATEAXISDRAGGER 1 + +#include + +namespace osgManipulator { + +/** + * Dragger for performing translation in all three axes. + */ +class OSGMANIPULATOR_EXPORT TranslateAxisDragger : public CompositeDragger +{ + public: + + TranslateAxisDragger(); + + META_OSGMANIPULATOR_Object(osgManipulator,TranslateAxisDragger) + + /** Setup default geometry for dragger. */ + void setupDefaultGeometry(); + + protected: + + virtual ~TranslateAxisDragger(); + + osg::ref_ptr< Translate1DDragger > _xDragger; + osg::ref_ptr< Translate1DDragger > _yDragger; + osg::ref_ptr< Translate1DDragger > _zDragger; +}; + + +} + +#endif diff --git a/libs/include/android/osgManipulator/TranslatePlaneDragger b/libs/include/android/osgManipulator/TranslatePlaneDragger new file mode 100755 index 0000000..f95633d --- /dev/null +++ b/libs/include/android/osgManipulator/TranslatePlaneDragger @@ -0,0 +1,56 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +//osgManipulator - Copyright (C) 2007 Fugro-Jason B.V. + +#ifndef OSGMANIPULATOR_TRANSLATEPLANEDRAGGER +#define OSGMANIPULATOR_TRANSLATEPLANEDRAGGER 1 + +#include +#include + +namespace osgManipulator { + +/** + * Translate plane dragger consists of a wireframe box representing a plane that can be dragged to translate along the plane. + */ +class OSGMANIPULATOR_EXPORT TranslatePlaneDragger : public CompositeDragger +{ + public: + + TranslatePlaneDragger(); + + META_OSGMANIPULATOR_Object(osgManipulator,TranslatePlaneDragger) + + virtual bool handle(const PointerInfo& pi, const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& us); + + /** Setup default geometry for dragger. */ + void setupDefaultGeometry(); + + inline void setColor(const osg::Vec4& color) { if (_translate2DDragger.valid()) _translate2DDragger->setColor(color); } + + Translate1DDragger* getTranslate1DDragger() { return _translate1DDragger.get(); } + Translate2DDragger* getTranslate2DDragger() { return _translate2DDragger.get(); } + + protected: + + virtual ~TranslatePlaneDragger(); + + osg::ref_ptr< Translate2DDragger > _translate2DDragger; + osg::ref_ptr< Translate1DDragger > _translate1DDragger; + bool _usingTranslate1DDragger; +}; + + +} + +#endif diff --git a/libs/include/android/osgManipulator/Version b/libs/include/android/osgManipulator/Version new file mode 100755 index 0000000..3794c53 --- /dev/null +++ b/libs/include/android/osgManipulator/Version @@ -0,0 +1,48 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGMANIPULATOR_VERSION +#define OSGMANIPULATOR_VERSION 1 + +#include + + +extern "C" { + +/** + * osgManipulatorGetVersion() returns the library version number. + * Numbering convention : OpenSceneGraph-1.0 will return 1.0 from osgManipulatorGetVersion. + * + * This C function can be also used to check for the existence of the OpenSceneGraph + * library using autoconf and its m4 macro AC_CHECK_LIB. + * + * Here is the code to add to your configure.in: + \verbatim + # + # Check for the OpenSceneGraph (OSG) Manipulator library + # + AC_CHECK_LIB(osg, osgManipulatorGetVersion, , + [AC_MSG_ERROR(OpenSceneGraph Manipulator library not found. See http://www.openscenegraph.org)],) + \endverbatim +*/ +extern OSGMANIPULATOR_EXPORT const char* osgManipulatorGetVersion(); + +/** + * osgManipulatorGetLibraryName() returns the library name in human friendly form. + */ +extern OSGMANIPULATOR_EXPORT const char* osgManipulatorGetLibraryName(); + +} + +#endif + diff --git a/libs/include/android/osgParticle/AccelOperator b/libs/include/android/osgParticle/AccelOperator new file mode 100755 index 0000000..46762f9 --- /dev/null +++ b/libs/include/android/osgParticle/AccelOperator @@ -0,0 +1,108 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +//osgParticle - Copyright (C) 2002 Marco Jez + +#ifndef OSGPARTICLE_ACCELOPERATOR +#define OSGPARTICLE_ACCELOPERATOR 1 + +#include +#include +#include + +#include +#include +#include + +namespace osgParticle +{ + + /** An operator class that applies a constant acceleration to the particles. + */ + class AccelOperator: public Operator { + public: + inline AccelOperator(); + inline AccelOperator(const AccelOperator& copy, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY); + + META_Object(osgParticle, AccelOperator); + + /// Get the acceleration vector. + inline const osg::Vec3& getAcceleration() const; + + /// Set the acceleration vector. + inline void setAcceleration(const osg::Vec3& v); + + /** Quickly set the acceleration vector to the gravity on earth (0, 0, -9.81). + The acceleration will be multiplied by the scale parameter. + */ + inline void setToGravity(float scale = 1); + + /// Apply the acceleration to a particle. Do not call this method manually. + inline void operate(Particle* P, double dt); + + /// Perform some initializations. Do not call this method manually. + inline void beginOperate(Program *prg); + + protected: + virtual ~AccelOperator() {} + AccelOperator &operator=(const AccelOperator &) { return *this; } + + private: + osg::Vec3 _accel; + osg::Vec3 _xf_accel; + }; + + // INLINE FUNCTIONS + + inline AccelOperator::AccelOperator() + : Operator(), _accel(0, 0, 0) + { + } + + inline AccelOperator::AccelOperator(const AccelOperator& copy, const osg::CopyOp& copyop) + : Operator(copy, copyop), _accel(copy._accel) + { + } + + inline const osg::Vec3& AccelOperator::getAcceleration() const + { + return _accel; + } + + inline void AccelOperator::setAcceleration(const osg::Vec3& v) + { + _accel = v; + } + + inline void AccelOperator::setToGravity(float scale) + { + _accel.set(0, 0, -9.80665f * scale); + } + + inline void AccelOperator::operate(Particle* P, double dt) + { + P->addVelocity(_xf_accel * dt); + } + + inline void AccelOperator::beginOperate(Program *prg) + { + if (prg->getReferenceFrame() == ModularProgram::RELATIVE_RF) { + _xf_accel = prg->rotateLocalToWorld(_accel); + } else { + _xf_accel = _accel; + } + } + +} + + +#endif diff --git a/libs/include/android/osgParticle/AngularAccelOperator b/libs/include/android/osgParticle/AngularAccelOperator new file mode 100755 index 0000000..b1eb1dc --- /dev/null +++ b/libs/include/android/osgParticle/AngularAccelOperator @@ -0,0 +1,99 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +//osgParticle - Copyright (C) 2002 Marco Jez + +#ifndef OSGPARTICLE_ANGULARACCELOPERATOR +#define OSGPARTICLE_ANGULARACCELOPERATOR 1 + +#include +#include +#include + +#include +#include +#include + +namespace osgParticle +{ + + /** An operator class that applies a constant angular acceleration to + * the particles. + */ + class AngularAccelOperator: public Operator { + public: + inline AngularAccelOperator(); + inline AngularAccelOperator(const AngularAccelOperator& copy, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY); + + META_Object(osgParticle, AngularAccelOperator); + + /// Get the angular acceleration vector. + inline const osg::Vec3& getAngularAcceleration() const; + + /// Set the angular acceleration vector. + inline void setAngularAcceleration(const osg::Vec3& v); + + /// Apply the angular acceleration to a particle. Do not call this method manually. + inline void operate(Particle* P, double dt); + + /// Perform some initializations. Do not call this method manually. + inline void beginOperate(Program *prg); + + protected: + virtual ~AngularAccelOperator() {} + AngularAccelOperator& operator=(const AngularAccelOperator& ) { return *this; } + + private: + osg::Vec3 _angul_araccel; + osg::Vec3 _xf_angul_araccel; + }; + + // INLINE FUNCTIONS + + inline AngularAccelOperator::AngularAccelOperator() + : Operator(), _angul_araccel(0, 0, 0) + { + } + + inline AngularAccelOperator::AngularAccelOperator(const AngularAccelOperator& copy, const osg::CopyOp& copyop) + : Operator(copy, copyop), _angul_araccel(copy._angul_araccel) + { + } + + inline const osg::Vec3& AngularAccelOperator::getAngularAcceleration() const + { + return _angul_araccel; + } + + inline void AngularAccelOperator::setAngularAcceleration(const osg::Vec3& v) + { + _angul_araccel = v; + } + + inline void AngularAccelOperator::operate(Particle* P, double dt) + { + P->addAngularVelocity(_xf_angul_araccel * dt); + } + + inline void AngularAccelOperator::beginOperate(Program *prg) + { + if (prg->getReferenceFrame() == ModularProgram::RELATIVE_RF) { + _xf_angul_araccel = prg->rotateLocalToWorld(_angul_araccel); + } else { + _xf_angul_araccel = _angul_araccel; + } + } + +} + + +#endif diff --git a/libs/include/android/osgParticle/AngularDampingOperator b/libs/include/android/osgParticle/AngularDampingOperator new file mode 100755 index 0000000..ec59e84 --- /dev/null +++ b/libs/include/android/osgParticle/AngularDampingOperator @@ -0,0 +1,94 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2010 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +// Written by Wang Rui, (C) 2010 + +#ifndef OSGPARTICLE_ANGULARDAMPINGOPERATOR +#define OSGPARTICLE_ANGULARDAMPINGOPERATOR + +#include +#include + +namespace osgParticle +{ + + +/** A angular damping operator applies damping constant to particle's angular velocity. + Refer to David McAllister's Particle System API (http://www.particlesystems.org) +*/ +class AngularDampingOperator : public Operator +{ +public: + AngularDampingOperator() : Operator(), _cutoffLow(0.0f), _cutoffHigh(FLT_MAX) + {} + + AngularDampingOperator( const AngularDampingOperator& copy, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY ) + : Operator(copy, copyop), _damping(copy._damping), + _cutoffLow(copy._cutoffLow), _cutoffHigh(copy._cutoffHigh) + {} + + META_Object( osgParticle, AngularDampingOperator ); + + /// Set the damping factors + void setDamping( float x, float y, float z ) { _damping.set(x, y, z); } + void setDamping( const osg::Vec3& damping ) { _damping = damping; } + + /// Set the damping factors to one value + void setDamping( float x ) { _damping.set(x, x, x); } + + /// Get the damping factors + void getDamping( float& x, float& y, float& z ) const + { x = _damping.x(); y = _damping.y(); z = _damping.z(); } + + const osg::Vec3& getDamping() const { return _damping; } + + /// Set the velocity cutoff factors + void setCutoff( float low, float high ) { _cutoffLow = low; _cutoffHigh = high; } + void setCutoffLow( float low ) { _cutoffLow = low; } + void setCutoffHigh( float low ) { _cutoffHigh = low; } + + /// Get the velocity cutoff factors + void getCutoff( float& low, float& high ) const { low = _cutoffLow; high = _cutoffHigh; } + float getCutoffLow() const { return _cutoffLow; } + float getCutoffHigh() const { return _cutoffHigh; } + + /// Apply the acceleration to a particle. Do not call this method manually. + inline void operate( Particle* P, double dt ); + +protected: + virtual ~AngularDampingOperator() {} + AngularDampingOperator& operator=( const AngularDampingOperator& ) { return *this; } + + osg::Vec3 _damping; + float _cutoffLow; + float _cutoffHigh; +}; + +// INLINE METHODS + +inline void AngularDampingOperator::operate( Particle* P, double dt ) +{ + const osg::Vec3& vel = P->getAngularVelocity(); + float length2 = vel.length2(); + if ( length2>=_cutoffLow && length2<=_cutoffHigh ) + { + osg::Vec3 newvel( vel.x() * (1.0f - (1.0f - _damping.x()) * dt), + vel.y() * (1.0f - (1.0f - _damping.y()) * dt), + vel.z() * (1.0f - (1.0f - _damping.z()) * dt) ); + P->setAngularVelocity( newvel ); + } +} + + +} + +#endif diff --git a/libs/include/android/osgParticle/BounceOperator b/libs/include/android/osgParticle/BounceOperator new file mode 100755 index 0000000..682ac7c --- /dev/null +++ b/libs/include/android/osgParticle/BounceOperator @@ -0,0 +1,78 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2010 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +// Written by Wang Rui, (C) 2010 + +#ifndef OSGPARTICLE_BOUNCEOPERATOR +#define OSGPARTICLE_BOUNCEOPERATOR + +#include +#include + +namespace osgParticle +{ + + +/** A bounce operator can affect the particle's velocity to make it rebound. + Refer to David McAllister's Particle System API (http://www.particlesystems.org) +*/ +class OSGPARTICLE_EXPORT BounceOperator : public DomainOperator +{ +public: + BounceOperator() + : DomainOperator(), _friction(1.0f), _resilience(0.0f), _cutoff(0.0f) + {} + + BounceOperator( const BounceOperator& copy, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY ) + : DomainOperator(copy, copyop), + _friction(copy._friction), _resilience(copy._resilience), _cutoff(copy._cutoff) + {} + + META_Object( osgParticle, BounceOperator ); + + /// Set the friction + void setFriction( float f ) { _friction = f; } + + /// Get the friction + float getFriction() const { return _friction; } + + /// Set the resilience + void setResilience( float r ) { _resilience = r; } + + /// Get the velocity cutoff factor + float getResilience() const { return _resilience; } + + /// Set the velocity cutoff factor + void setCutoff( float v ) { _cutoff = v; } + + /// Get the velocity cutoff factor + float getCutoff() const { return _cutoff; } + +protected: + virtual ~BounceOperator() {} + BounceOperator& operator=( const BounceOperator& ) { return *this; } + + virtual void handleTriangle( const Domain& domain, Particle* P, double dt ); + virtual void handleRectangle( const Domain& domain, Particle* P, double dt ); + virtual void handlePlane( const Domain& domain, Particle* P, double dt ); + virtual void handleSphere( const Domain& domain, Particle* P, double dt ); + virtual void handleDisk( const Domain& domain, Particle* P, double dt ); + + float _friction; + float _resilience; + float _cutoff; +}; + + +} + +#endif diff --git a/libs/include/android/osgParticle/BoxPlacer b/libs/include/android/osgParticle/BoxPlacer new file mode 100755 index 0000000..9765aab --- /dev/null +++ b/libs/include/android/osgParticle/BoxPlacer @@ -0,0 +1,174 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +//Build by Zach Deedler + +#ifndef OSGPARTICLE_BOX_PLACER +#define OSGPARTICLE_BOX_PLACER 1 + +#include +#include +#include + +#include +#include +#include +#include + +namespace osgParticle +{ + + /** A box-shaped particle placer. + This placer sets the initial position of incoming particle by choosing a random position + within the volume of a box; this placer is defined by four parameters: a center point, + which is inherited directly from osgParticle::CenteredPlacer, and three ranges of values + for the valid X, Y, and Z coordinates. + */ + class BoxPlacer: public CenteredPlacer { + public: + inline BoxPlacer(); + inline BoxPlacer(const BoxPlacer& copy, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY); + + /// Get the range of possible values along the X axis. + inline const rangef& getXRange() const; + + /// Set the range of possible values along the X axis. + inline void setXRange(const rangef& r); + + /// Set the range of possible values along the X axis. + inline void setXRange(float r1, float r2); + + /// Get the range of possible values along the Y axis. + inline const rangef& getYRange() const; + + /// Set the range of possible values along the Y axis. + inline void setYRange(const rangef& r); + + /// Set the range of possible values along the Y axis. + inline void setYRange(float r1, float r2); + + /// Get the range of possible values along the Z axis. + inline const rangef& getZRange() const; + + /// Set the range of possible values along the Z axis. + inline void setZRange(const rangef& r); + + /// Set the range of possible values along the Z axis. + inline void setZRange(float r1, float r2); + + META_Object(osgParticle, BoxPlacer); + + /// Place a particle. Do not call it manually. + inline void place(Particle* P) const; + + /// return the volume of the box + inline float volume() const; + + /// return the control position + inline osg::Vec3 getControlPosition() const; + + protected: + virtual ~BoxPlacer() {} + BoxPlacer& operator=(const BoxPlacer&) { return *this; } + + private: + rangef _x_range; + rangef _y_range; + rangef _z_range; + }; + + // INLINE FUNCTIONS + + inline BoxPlacer::BoxPlacer() + : CenteredPlacer(), _x_range(-1, 1), _y_range(-1, 1), _z_range(-1, 1) + { + } + + inline BoxPlacer::BoxPlacer(const BoxPlacer& copy, const osg::CopyOp& copyop) + : CenteredPlacer(copy, copyop), + _x_range(copy._x_range), _y_range(copy._y_range), _z_range(copy._z_range) + { + } + + inline const rangef& BoxPlacer::getXRange() const + { + return _x_range; + } + + inline void BoxPlacer::setXRange(const rangef& r) + { + _x_range = r; + } + + inline void BoxPlacer::setXRange(float r1, float r2) + { + _x_range.minimum = r1; + _x_range.maximum = r2; + } + + inline const rangef& BoxPlacer::getYRange() const + { + return _y_range; + } + + inline void BoxPlacer::setYRange(const rangef& r) + { + _y_range = r; + } + + inline void BoxPlacer::setYRange(float r1, float r2) + { + _y_range.minimum = r1; + _y_range.maximum = r2; + } + + inline const rangef& BoxPlacer::getZRange() const + { + return _z_range; + } + + inline void BoxPlacer::setZRange(const rangef& r) + { + _z_range = r; + } + + inline void BoxPlacer::setZRange(float r1, float r2) + { + _z_range.minimum = r1; + _z_range.maximum = r2; + } + + inline void BoxPlacer::place(Particle* P) const + { + osg::Vec3 pos( + getCenter().x() + _x_range.get_random(), + getCenter().y() + _y_range.get_random(), + getCenter().z() + _z_range.get_random()); + + P->setPosition(pos); + } + + inline float BoxPlacer::volume() const + { + return (_x_range.maximum - _x_range.minimum) * + (_y_range.maximum - _y_range.minimum) * + (_z_range.maximum - _z_range.minimum); + } + + inline osg::Vec3 BoxPlacer::getControlPosition() const + { + return getCenter(); + } + +} + +#endif diff --git a/libs/include/android/osgParticle/CenteredPlacer b/libs/include/android/osgParticle/CenteredPlacer new file mode 100755 index 0000000..8a2c27c --- /dev/null +++ b/libs/include/android/osgParticle/CenteredPlacer @@ -0,0 +1,84 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +//osgParticle - Copyright (C) 2002 Marco Jez + +#ifndef OSGPARTICLE_CENTERED_PLACER +#define OSGPARTICLE_CENTERED_PLACER 1 + +#include + +#include +#include +#include + +namespace osgParticle +{ + + /** An abstract placer base class for placers which need a center point. + */ + class CenteredPlacer: public Placer { + public: + inline CenteredPlacer(); + inline CenteredPlacer(const CenteredPlacer& copy, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY); + + virtual const char* libraryName() const { return "osgParticle"; } + virtual const char* className() const { return "CenteredPlacer"; } + virtual bool isSameKindAs(const osg::Object* obj) const { return dynamic_cast(obj) != 0; } + + /// Get the center point. + inline const osg::Vec3& getCenter() const; + + /// Set the center point. + inline void setCenter(const osg::Vec3& v); + + /// Set the center point. + inline void setCenter(float x, float y, float z); + + protected: + virtual ~CenteredPlacer() {} + + private: + osg::Vec3 center_; + }; + + // INLINE FUNCTIONS + + inline CenteredPlacer::CenteredPlacer() + : Placer(), center_(0, 0, 0) + { + } + + inline CenteredPlacer::CenteredPlacer(const CenteredPlacer& copy, const osg::CopyOp& copyop) + : Placer(copy, copyop), center_(copy.center_) + { + } + + inline const osg::Vec3& CenteredPlacer::getCenter() const + { + return center_; + } + + inline void CenteredPlacer::setCenter(const osg::Vec3& v) + { + center_ = v; + } + + inline void CenteredPlacer::setCenter(float x, float y, float z) + { + center_.set(x, y, z); + } + +} + + +#endif diff --git a/libs/include/android/osgParticle/CompositePlacer b/libs/include/android/osgParticle/CompositePlacer new file mode 100755 index 0000000..9baab81 --- /dev/null +++ b/libs/include/android/osgParticle/CompositePlacer @@ -0,0 +1,104 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2010 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +// Written by Wang Rui, (C) 2010 + +#ifndef OSGPARTICLE_COMPOSITEPLACER +#define OSGPARTICLE_COMPOSITEPLACER + +#include +#include + +namespace osgParticle +{ + + +/** A composite particle placer which allows particles to be generated from a union of placers. */ +class CompositePlacer : public Placer +{ +public: + CompositePlacer() : Placer() {} + + CompositePlacer( const CompositePlacer& copy, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY ) + : Placer(copy, copyop), _placers(copy._placers) {} + + META_Object( osgParticle, CompositePlacer ); + + // Set a child placer at specific index + void setPlacer( unsigned int i, Placer* p ) + { + if (i<_placers.size()) _placers[i] = p; + else addPlacer(p); + } + + /// Add a child placer + void addPlacer( Placer* p ) { _placers.push_back(p); } + + /// Remove a child placer + void removePlacer( unsigned int i ) + { if (i<_placers.size()) _placers.erase(_placers.begin()+i); } + + /// Get a child placer + Placer* getPlacer( unsigned int i ) { return _placers[i].get(); } + const Placer* getPlacer( unsigned int i ) const { return _placers[i].get(); } + + /// Get number of placers + unsigned int getNumPlacers() const { return _placers.size(); } + + /// Place a particle. Do not call it manually. + inline void place( Particle* P ) const; + + /// return the volume of the box + inline float volume() const; + + /// return the control position + inline osg::Vec3 getControlPosition() const; + +protected: + virtual ~CompositePlacer() {} + CompositePlacer& operator=( const CompositePlacer& ) { return *this; } + + typedef std::vector< osg::ref_ptr > PlacerList; + PlacerList _placers; +}; + +// INLINE METHODS + +inline void CompositePlacer::place( Particle* P ) const +{ + rangef sizeRange( 0.0f, volume() ); + float current = 0.0f, selected = sizeRange.get_random(); + for ( PlacerList::const_iterator itr=_placers.begin(); itr!=_placers.end(); ++itr ) + { + current += (*itr)->volume(); + if ( selected<=current ) (*itr)->place( P ); + } +} + +inline float CompositePlacer::volume() const +{ + float total_size = 0.0f; + for ( PlacerList::const_iterator itr=_placers.begin(); itr!=_placers.end(); ++itr ) + total_size += (*itr)->volume(); + return total_size; +} + +inline osg::Vec3 CompositePlacer::getControlPosition() const +{ + if ( !_placers.size() ) return osg::Vec3(); + return _placers.front()->getControlPosition(); +} + + +} + +#endif diff --git a/libs/include/android/osgParticle/ConnectedParticleSystem b/libs/include/android/osgParticle/ConnectedParticleSystem new file mode 100755 index 0000000..89550a6 --- /dev/null +++ b/libs/include/android/osgParticle/ConnectedParticleSystem @@ -0,0 +1,79 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGPARTICLE_CONNECTEDPARTICLESYSTEM +#define OSGPARTICLE_CONNECTEDPARTICLESYSTEM 1 + +#include + +namespace osgParticle +{ + + /** ConnectConnectedParticleSystem is a specialise ConnectedParticleSystem for effects + * like missle trails, where the individual particles are rendered as + * single ribbon. + */ + class OSGPARTICLE_EXPORT ConnectedParticleSystem: public osgParticle::ParticleSystem + { + public: + + ConnectedParticleSystem(); + ConnectedParticleSystem(const ConnectedParticleSystem& copy, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY); + + META_Object(osgParticle, ConnectedParticleSystem); + + /// Create a new particle from the specified template (or the default one if ptemplate is null). + virtual Particle* createParticle(const Particle* ptemplate); + + /// Reuse the i-th particle. + virtual void reuseParticle(int i); + + /// Draw the connected particles as either a line or a quad strip, depending upon viewing distance. . + virtual void drawImplementation(osg::RenderInfo& renderInfo) const; + + ///Get the (const) particle from where the line or quadstrip starts to be drawn + const osgParticle::Particle* getStartParticle() const + { + return (_startParticle != Particle::INVALID_INDEX) ? &_particles[_startParticle] : 0; + } + + ///Get the particle from where the line or quadstrip starts to be drawn + osgParticle::Particle* getStartParticle() + { + return (_startParticle != Particle::INVALID_INDEX) ? &_particles[_startParticle] : 0; + } + + ///Set the maximum numbers of particles to be skipped during the predraw filtering + void setMaxNumberOfParticlesToSkip(unsigned int maxNumberofParticlesToSkip){_maxNumberOfParticlesToSkip = maxNumberofParticlesToSkip;} + + ///Get the maximum numbers of particles to be skipped during the predraw filtering + unsigned int getMaxNumberOfParticlesToSkip(){ return _maxNumberOfParticlesToSkip;} + + protected: + + virtual ~ConnectedParticleSystem(); + + ConnectedParticleSystem& operator=(const ConnectedParticleSystem&) { return *this; } + + int _lastParticleCreated; + unsigned int _maxNumberOfParticlesToSkip; + + int _startParticle; + + }; + + + +} + +#endif diff --git a/libs/include/android/osgParticle/ConstantRateCounter b/libs/include/android/osgParticle/ConstantRateCounter new file mode 100755 index 0000000..6ea6775 --- /dev/null +++ b/libs/include/android/osgParticle/ConstantRateCounter @@ -0,0 +1,77 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGPARTICLE_CONSTANTRATECOUNTER +#define OSGPARTICLE_CONSTANTRATECOUNTER 1 + +#include + +#include +#include + +namespace osgParticle +{ + + class ConstantRateCounter: public Counter { + public: + ConstantRateCounter(): + Counter(), + _minimumNumberOfParticlesToCreate(0), + _numberOfParticlesPerSecondToCreate(0), + _carryOver(0) + { + } + + ConstantRateCounter(const ConstantRateCounter& copy, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY): + Counter(copy, copyop), + _minimumNumberOfParticlesToCreate(copy._minimumNumberOfParticlesToCreate), + _numberOfParticlesPerSecondToCreate(copy._numberOfParticlesPerSecondToCreate), + _carryOver(copy._carryOver) + { + } + + + META_Object(osgParticle, ConstantRateCounter); + + void setMinimumNumberOfParticlesToCreate(int minNumToCreate) { _minimumNumberOfParticlesToCreate = minNumToCreate; } + int getMinimumNumberOfParticlesToCreate() const { return _minimumNumberOfParticlesToCreate; } + + void setNumberOfParticlesPerSecondToCreate(double numPerSecond) { _numberOfParticlesPerSecondToCreate = numPerSecond; } + double getNumberOfParticlesPerSecondToCreate() const { return _numberOfParticlesPerSecondToCreate; } + + /// Return the number of particles to be created in this frame + virtual int numParticlesToCreate(double dt) const + { + double v = (dt*_numberOfParticlesPerSecondToCreate); + int i = (int)(v); + _carryOver += (v-(double)i); + if (_carryOver>1.0) + { + ++i; + _carryOver -= 1.0; + } + return osg::maximum(_minimumNumberOfParticlesToCreate, i); + } + + protected: + virtual ~ConstantRateCounter() {} + + int _minimumNumberOfParticlesToCreate; + double _numberOfParticlesPerSecondToCreate; + mutable double _carryOver; + }; + +} + + +#endif diff --git a/libs/include/android/osgParticle/Counter b/libs/include/android/osgParticle/Counter new file mode 100755 index 0000000..071ebc7 --- /dev/null +++ b/libs/include/android/osgParticle/Counter @@ -0,0 +1,54 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +//osgParticle - Copyright (C) 2002 Marco Jez + +#ifndef OSGPARTICLE_COUNTER +#define OSGPARTICLE_COUNTER 1 + +#include +#include + +namespace osgParticle +{ + + class Counter: public osg::Object { + public: + inline Counter(); + inline Counter(const Counter& copy, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY); + + virtual const char* libraryName() const { return "osgParticle"; } + virtual const char* className() const { return "Counter"; } + virtual bool isSameKindAs(const osg::Object* obj) const { return dynamic_cast(obj) != 0; } + + virtual int numParticlesToCreate(double dt) const = 0; + + protected: + ~Counter() {} + Counter &operator=(const Counter &) { return *this; } + }; + + // INLINE FUNCTIONS + + inline Counter::Counter() + : osg::Object() + { + } + + inline Counter::Counter(const Counter& copy, const osg::CopyOp& copyop) + : osg::Object(copy, copyop) + { + } + +} + +#endif diff --git a/libs/include/android/osgParticle/DampingOperator b/libs/include/android/osgParticle/DampingOperator new file mode 100755 index 0000000..7476314 --- /dev/null +++ b/libs/include/android/osgParticle/DampingOperator @@ -0,0 +1,94 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2010 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +// Written by Wang Rui, (C) 2010 + +#ifndef OSGPARTICLE_DAMPINGOPERATOR +#define OSGPARTICLE_DAMPINGOPERATOR + +#include +#include + +namespace osgParticle +{ + + +/** A damping operator applies damping constant to particle's velocity. + Refer to David McAllister's Particle System API (http://www.particlesystems.org) +*/ +class DampingOperator : public Operator +{ +public: + DampingOperator() : Operator(), _cutoffLow(0.0f), _cutoffHigh(FLT_MAX) + { _damping.set(1.0f, 1.0f, 1.0f); } + + DampingOperator( const DampingOperator& copy, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY ) + : Operator(copy, copyop), _damping(copy._damping), + _cutoffLow(copy._cutoffLow), _cutoffHigh(copy._cutoffHigh) + {} + + META_Object( osgParticle, DampingOperator ); + + /// Set the damping factors + void setDamping( float x, float y, float z ) { _damping.set(x, y, z); } + void setDamping( const osg::Vec3& damping ) { _damping = damping; } + + /// Set the damping factors to one value + void setDamping( float x ) { _damping.set(x, x, x); } + + /// Get the damping factors + void getDamping( float& x, float& y, float& z ) const + { x = _damping.x(); y = _damping.y(); z = _damping.z(); } + + const osg::Vec3& getDamping() const { return _damping; } + + /// Set the velocity cutoff factors + void setCutoff( float low, float high ) { _cutoffLow = low; _cutoffHigh = high; } + void setCutoffLow( float low ) { _cutoffLow = low; } + void setCutoffHigh( float low ) { _cutoffHigh = low; } + + /// Get the velocity cutoff factors + void getCutoff( float& low, float& high ) const { low = _cutoffLow; high = _cutoffHigh; } + float getCutoffLow() const { return _cutoffLow; } + float getCutoffHigh() const { return _cutoffHigh; } + + /// Apply the acceleration to a particle. Do not call this method manually. + inline void operate( Particle* P, double dt ); + +protected: + virtual ~DampingOperator() {} + DampingOperator& operator=( const DampingOperator& ) { return *this; } + + osg::Vec3 _damping; + float _cutoffLow; + float _cutoffHigh; +}; + +// INLINE METHODS + +inline void DampingOperator::operate( Particle* P, double dt ) +{ + const osg::Vec3& vel = P->getVelocity(); + float length2 = vel.length2(); + if ( length2>=_cutoffLow && length2<=_cutoffHigh ) + { + osg::Vec3 newvel( vel.x() * (1.0f - (1.0f - _damping.x()) * dt), + vel.y() * (1.0f - (1.0f - _damping.y()) * dt), + vel.z() * (1.0f - (1.0f - _damping.z()) * dt) ); + P->setVelocity( newvel ); + } +} + + +} + +#endif diff --git a/libs/include/android/osgParticle/DomainOperator b/libs/include/android/osgParticle/DomainOperator new file mode 100755 index 0000000..e35c81e --- /dev/null +++ b/libs/include/android/osgParticle/DomainOperator @@ -0,0 +1,235 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2010 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +// Written by Wang Rui, (C) 2010 + +#ifndef OSGPARTICLE_DOMAINOPERATOR +#define OSGPARTICLE_DOMAINOPERATOR + +#include +#include +#include + +namespace osgParticle +{ + + +/** A domain operator which accepts different domain shapes as the parameter. + It can be derived to implement operators that require particles interacting with domains. + Refer to David McAllister's Particle System API (http://www.particlesystems.org) +*/ +class OSGPARTICLE_EXPORT DomainOperator : public Operator +{ +public: + struct Domain + { + enum Type + { + UNDEFINED_DOMAIN = 0, + POINT_DOMAIN, + LINE_DOMAIN, + TRI_DOMAIN, + RECT_DOMAIN, + PLANE_DOMAIN, + SPHERE_DOMAIN, + BOX_DOMAIN, + DISK_DOMAIN + }; + + Domain( Type t ) : r1(0.0f), r2(0.0f), type(t) {} + osg::Plane plane; + osg::Vec3 v1; + osg::Vec3 v2; + osg::Vec3 v3; + osg::Vec3 s1; + osg::Vec3 s2; + float r1; + float r2; + Type type; + }; + + DomainOperator() + : Operator() + {} + + DomainOperator( const DomainOperator& copy, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY ) + : Operator(copy, copyop), _domains(copy._domains), _backupDomains(copy._backupDomains) + {} + + META_Object( osgParticle, DomainOperator ); + + /// Add a point domain + inline void addPointDomain( const osg::Vec3& p ); + + /// Add a line segment domain + inline void addLineSegmentDomain( const osg::Vec3& v1, const osg::Vec3& v2 ); + + /// Add a triangle domain + inline void addTriangleDomain( const osg::Vec3& v1, const osg::Vec3& v2, const osg::Vec3& v3 ); + + /// Add a rectangle domain + inline void addRectangleDomain( const osg::Vec3& corner, const osg::Vec3& w, const osg::Vec3& h ); + + /// Add a plane domain + inline void addPlaneDomain( const osg::Plane& plane ); + + /// Add a sphere domain + inline void addSphereDomain( const osg::Vec3& c, float r ); + + /// Add a box domain + inline void addBoxDomain( const osg::Vec3& min, const osg::Vec3& max ); + + /// Add a disk domain + inline void addDiskDomain( const osg::Vec3& c, const osg::Vec3& n, float r1, float r2=0.0f ); + + /// Add a domain object directly, used by the .osg wrappers and serializers. + void addDomain( const Domain& domain ) { _domains.push_back(domain); } + + /// Get a domain object directly, used by the .osg wrappers and serializers. + const Domain& getDomain( unsigned int i ) const { return _domains[i]; } + + /// Remove a domain at specific index + void removeDomain( unsigned int i ) + { if (i<_domains.size()) _domains.erase(_domains.begin() + i); } + + /// Remove all existing domains + void removeAllDomains() { _domains.clear(); } + + /// Get number of domains + unsigned int getNumDomains() const { return _domains.size(); } + + /// Apply the acceleration to a particle. Do not call this method manually. + void operate( Particle* P, double dt ); + + /// Perform some initializations. Do not call this method manually. + void beginOperate( Program* prg ); + + /// Perform some post-operations. Do not call this method manually. + void endOperate(); + +protected: + virtual ~DomainOperator() {} + DomainOperator& operator=( const DomainOperator& ) { return *this; } + + virtual void handlePoint( const Domain& /*domain*/, Particle* /*P*/, double /*dt*/ ) { ignore("Point"); } + virtual void handleLineSegment( const Domain& /*domain*/, Particle* /*P*/, double /*dt*/ ) { ignore("LineSegment"); } + virtual void handleTriangle( const Domain& /*domain*/, Particle* /*P*/, double /*dt*/ ) { ignore("Triangle"); } + virtual void handleRectangle( const Domain& /*domain*/, Particle* /*P*/, double /*dt*/ ) { ignore("Rectangle"); } + virtual void handlePlane( const Domain& /*domain*/, Particle* /*P*/, double /*dt*/ ) { ignore("Plane"); } + virtual void handleSphere( const Domain& /*domain*/, Particle* /*P*/, double /*dt*/ ) { ignore("Sphere"); } + virtual void handleBox( const Domain& /*domain*/, Particle* /*P*/, double /*dt*/ ) { ignore("Box"); } + virtual void handleDisk( const Domain& /*domain*/, Particle* /*P*/, double /*dt*/ ) { ignore("Disk"); } + + inline void computeNewBasis( const osg::Vec3&, const osg::Vec3&, osg::Vec3&, osg::Vec3& ); + inline void ignore( const std::string& func ); + + std::vector _domains; + std::vector _backupDomains; +}; + +// INLINE METHODS + +inline void DomainOperator::addPointDomain( const osg::Vec3& p ) +{ + Domain domain( Domain::POINT_DOMAIN ); + domain.v1 = p; + _domains.push_back( domain ); +} + +inline void DomainOperator::addLineSegmentDomain( const osg::Vec3& v1, const osg::Vec3& v2 ) +{ + Domain domain( Domain::LINE_DOMAIN ); + domain.v1 = v1; + domain.v2 = v2; + domain.r1 = (v2 - v1).length(); + _domains.push_back( domain ); +} + +inline void DomainOperator::addTriangleDomain( const osg::Vec3& v1, const osg::Vec3& v2, const osg::Vec3& v3 ) +{ + Domain domain( Domain::TRI_DOMAIN ); + domain.v1 = v1; + domain.v2 = v2; + domain.v3 = v3; + domain.plane.set(v1, v2, v3); + computeNewBasis( v2-v1, v3-v1, domain.s1, domain.s2 ); + _domains.push_back( domain ); +} + +inline void DomainOperator::addRectangleDomain( const osg::Vec3& corner, const osg::Vec3& w, const osg::Vec3& h ) +{ + Domain domain( Domain::RECT_DOMAIN ); + domain.v1 = corner; + domain.v2 = w; + domain.v3 = h; + domain.plane.set(corner, corner+w, corner+h); + computeNewBasis( w, h, domain.s1, domain.s2 ); + _domains.push_back( domain ); +} + +inline void DomainOperator::addPlaneDomain( const osg::Plane& plane ) +{ + Domain domain( Domain::PLANE_DOMAIN ); + domain.plane.set(plane); + _domains.push_back( domain ); +} + +inline void DomainOperator::addSphereDomain( const osg::Vec3& c, float r ) +{ + Domain domain( Domain::SPHERE_DOMAIN ); + domain.v1 = c; + domain.r1 = r; + _domains.push_back( domain ); +} + +inline void DomainOperator::addBoxDomain( const osg::Vec3& min, const osg::Vec3& max ) +{ + Domain domain( Domain::BOX_DOMAIN ); + domain.v1 = min; + domain.v2 = max; + _domains.push_back( domain ); +} + +inline void DomainOperator::addDiskDomain( const osg::Vec3& c, const osg::Vec3& n, float r1, float r2 ) +{ + Domain domain( Domain::DISK_DOMAIN ); + domain.v1 = c; + domain.v2 = n; + domain.r1 = r1; + domain.r2 = r2; + domain.plane.set(n, c); + _domains.push_back( domain ); +} + +inline void DomainOperator::computeNewBasis( const osg::Vec3& u, const osg::Vec3& v, osg::Vec3& s1, osg::Vec3& s2 ) +{ + // Copied from David McAllister's Particle System API (http://www.particlesystems.org), pDomain.h + osg::Vec3 w = u ^ v; + float det = w.z()*u.x()*v.y() - w.z()*u.y()*v.x() - u.z()*w.x()*v.y() - + u.x()*v.z()*w.y() + v.z()*w.x()*u.y() + u.z()*v.x()*w.y(); + det = 1.0f / det; + + s1.set( v.y()*w.z() - v.z()*w.y(), v.z()*w.x() - v.x()*w.z(), v.x()*w.y() - v.y()*w.x() ); + s1 = s1 * det; + s2.set( u.y()*w.z() - u.z()*w.y(), u.z()*w.x() - u.x()*w.z(), u.x()*w.y() - u.y()*w.x() ); + s2 = s2 * (-det); +} + +inline void DomainOperator::ignore( const std::string& func ) +{ + OSG_NOTICE << className() << ": " << func << " domain not yet implemented. " << std::endl; +} + + +} + +#endif diff --git a/libs/include/android/osgParticle/Emitter b/libs/include/android/osgParticle/Emitter new file mode 100755 index 0000000..a433e68 --- /dev/null +++ b/libs/include/android/osgParticle/Emitter @@ -0,0 +1,105 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +//osgParticle - Copyright (C) 2002 Marco Jez + +#ifndef OSGPARTICLE_EMITTER +#define OSGPARTICLE_EMITTER 1 + +#include +#include +#include + +#include +#include +#include +#include + +namespace osgParticle +{ + + /** An abstract base class for particle emitters. + Descendant classes must override the emitParticles() method to generate new particles by + calling the ParticleSystem::createParticle() method on the particle system associated + to the emitter. + */ + class OSGPARTICLE_EXPORT Emitter: public ParticleProcessor { + public: + Emitter(); + Emitter(const Emitter& copy, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY); + + virtual const char* libraryName() const { return "osgParticle"; } + virtual const char* className() const { return "Emitter"; } + virtual bool isSameKindAs(const osg::Object* obj) const { return dynamic_cast(obj) != 0; } + virtual void accept(osg::NodeVisitor& nv) { if (nv.validNodeMask(*this)) { nv.pushOntoNodePath(this); nv.apply(*this); nv.popFromNodePath(); } } + + /// Get the particle template. + inline const Particle& getParticleTemplate() const; + + /// Set the particle template (particle is copied). + inline void setParticleTemplate(const Particle& p); + + /// Return whether the particle system's default template should be used. + inline bool getUseDefaultTemplate() const; + + /** Set whether the default particle template should be used. + When this flag is true, the particle template is ignored, and the + particle system's default template is used instead. + */ + inline void setUseDefaultTemplate(bool v); + + protected: + virtual ~Emitter() {} + Emitter& operator=(const Emitter&) { return *this; } + + inline void process(double dt); + + virtual void emitParticles(double dt) = 0; + + bool _usedeftemp; + Particle _ptemp; + }; + + // INLINE FUNCTIONS + + inline const Particle& Emitter::getParticleTemplate() const + { + return _ptemp; + } + + inline void Emitter::setParticleTemplate(const Particle& p) + { + _ptemp = p; + _usedeftemp = false; + } + + inline bool Emitter::getUseDefaultTemplate() const + { + return _usedeftemp; + } + + inline void Emitter::setUseDefaultTemplate(bool v) + { + _usedeftemp = v; + } + + inline void Emitter::process(double dt) + { + emitParticles(dt); + } + + +} + + +#endif + diff --git a/libs/include/android/osgParticle/ExplosionDebrisEffect b/libs/include/android/osgParticle/ExplosionDebrisEffect new file mode 100755 index 0000000..919d150 --- /dev/null +++ b/libs/include/android/osgParticle/ExplosionDebrisEffect @@ -0,0 +1,56 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGPARTICLE_EXPLOSIONDEBRISEFFECT +#define OSGPARTICLE_EXPLOSIONDEBRISEFFECT + +#include +#include +#include + +namespace osgParticle +{ + + class OSGPARTICLE_EXPORT ExplosionDebrisEffect : public ParticleEffect + { + public: + + explicit ExplosionDebrisEffect(bool automaticSetup=true); + + ExplosionDebrisEffect(const osg::Vec3& position, float scale=1.0f, float intensity=1.0f); + + ExplosionDebrisEffect(const ExplosionDebrisEffect& copy, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY); + + META_Node(osgParticle,ExplosionDebrisEffect); + + virtual void setDefaults(); + + virtual void setUpEmitterAndProgram(); + + virtual Emitter* getEmitter() { return _emitter.get(); } + virtual const Emitter* getEmitter() const { return _emitter.get(); } + + virtual Program* getProgram() { return _program.get(); } + virtual const Program* getProgram() const { return _program.get(); } + + protected: + + virtual ~ExplosionDebrisEffect() {} + + osg::ref_ptr _emitter; + osg::ref_ptr _program; + + }; +} + +#endif diff --git a/libs/include/android/osgParticle/ExplosionEffect b/libs/include/android/osgParticle/ExplosionEffect new file mode 100755 index 0000000..ce9dbcc --- /dev/null +++ b/libs/include/android/osgParticle/ExplosionEffect @@ -0,0 +1,56 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGPARTICLE_EXPLOSIONEFFECT +#define OSGPARTICLE_EXPLOSIONEFFECT + +#include +#include +#include + +namespace osgParticle +{ + + class OSGPARTICLE_EXPORT ExplosionEffect : public ParticleEffect + { + public: + + explicit ExplosionEffect(bool automaticSetup=true); + + ExplosionEffect(const osg::Vec3& position, float scale=1.0f, float intensity=1.0f); + + ExplosionEffect(const ExplosionEffect& copy, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY); + + META_Node(osgParticle,ExplosionEffect); + + virtual void setDefaults(); + + virtual void setUpEmitterAndProgram(); + + virtual Emitter* getEmitter() { return _emitter.get(); } + virtual const Emitter* getEmitter() const { return _emitter.get(); } + + virtual Program* getProgram() { return _program.get(); } + virtual const Program* getProgram() const { return _program.get(); } + + protected: + + virtual ~ExplosionEffect() {} + + osg::ref_ptr _emitter; + osg::ref_ptr _program; + + }; +} + +#endif diff --git a/libs/include/android/osgParticle/ExplosionOperator b/libs/include/android/osgParticle/ExplosionOperator new file mode 100755 index 0000000..f6f29be --- /dev/null +++ b/libs/include/android/osgParticle/ExplosionOperator @@ -0,0 +1,127 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2010 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +// Written by Wang Rui, (C) 2010 + +#ifndef OSGPARTICLE_EXPLOSIONOPERATOR +#define OSGPARTICLE_EXPLOSIONOPERATOR + +#include +#include +#include + +namespace osgParticle +{ + + +/** An explosion operator exerts force on each particle away from the explosion center. + Refer to David McAllister's Particle System API (http://www.particlesystems.org) +*/ +class ExplosionOperator : public Operator +{ +public: + ExplosionOperator() + : Operator(), _radius(1.0f), + _magnitude(1.0f), _epsilon(1e-3), _sigma(1.0f), + _inexp(0.0f), _outexp(0.0f) + {} + + ExplosionOperator( const ExplosionOperator& copy, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY ) + : Operator(copy, copyop), _center(copy._center), _radius(copy._radius), + _magnitude(copy._magnitude), _epsilon(copy._epsilon), _sigma(copy._sigma), + _inexp(copy._inexp), _outexp(copy._outexp) + {} + + META_Object( osgParticle, ExplosionOperator ); + + /// Set the center of shock wave + void setCenter( const osg::Vec3& c ) { _center = c; } + + /// Get the center of shock wave + const osg::Vec3& getCenter() const { return _center; } + + /// Set the radius of wave peak + void setRadius( float r ) { _radius = r; } + + /// Get the radius of wave peak + float getRadius() const { return _radius; } + + /// Set the acceleration scale + void setMagnitude( float mag ) { _magnitude = mag; } + + /// Get the acceleration scale + float getMagnitude() const { return _magnitude; } + + /// Set the acceleration epsilon + void setEpsilon( float eps ) { _epsilon = eps; } + + /// Get the acceleration epsilon + float getEpsilon() const { return _epsilon; } + + /// Set broadness of the strength of the wave + void setSigma( float s ) { _sigma = s; } + + /// Get broadness of the strength of the wave + float getSigma() const { return _sigma; } + + /// Apply the acceleration to a particle. Do not call this method manually. + inline void operate( Particle* P, double dt ); + + /// Perform some initializations. Do not call this method manually. + inline void beginOperate( Program* prg ); + +protected: + virtual ~ExplosionOperator() {} + ExplosionOperator& operator=( const ExplosionOperator& ) { return *this; } + + osg::Vec3 _center; + osg::Vec3 _xf_center; + float _radius; + float _magnitude; + float _epsilon; + float _sigma; + float _inexp; + float _outexp; +}; + +// INLINE METHODS + +inline void ExplosionOperator::operate( Particle* P, double dt ) +{ + osg::Vec3 dir = P->getPosition() - _xf_center; + float length = dir.length(); + float distanceFromWave2 = (_radius - length) * (_radius - length); + float Gd = exp(distanceFromWave2 * _inexp) * _outexp; + float factor = (_magnitude * dt) / (length * (_epsilon+length*length)); + P->addVelocity( dir * (Gd * factor) ); +} + +inline void ExplosionOperator::beginOperate( Program* prg ) +{ + if ( prg->getReferenceFrame()==ModularProgram::RELATIVE_RF ) + { + _xf_center = prg->transformLocalToWorld(_center); + } + else + { + _xf_center = _center; + } + + float oneOverSigma = (_sigma!=0.0f ? (1.0f / _sigma) : 1.0f); + _inexp = -0.5f * oneOverSigma * oneOverSigma; + _outexp = oneOverSigma / sqrt(osg::PI * 2.0f); +} + + +} + +#endif diff --git a/libs/include/android/osgParticle/Export b/libs/include/android/osgParticle/Export new file mode 100755 index 0000000..37989eb --- /dev/null +++ b/libs/include/android/osgParticle/Export @@ -0,0 +1,51 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +//osgParticle - Copyright (C) 2002 Marco Jez + +#ifndef OSGPARTICLE_EXPORT_ +#define OSGPARTICLE_EXPORT_ 1 + +#include + +#if defined(_MSC_VER) && defined(OSG_DISABLE_MSVC_WARNINGS) + #pragma warning( disable : 4244 ) + #pragma warning( disable : 4251 ) + #pragma warning( disable : 4275 ) + #pragma warning( disable : 4786 ) + #pragma warning( disable : 4290 ) + #pragma warning( disable : 4305 ) + #pragma warning( disable : 4996 ) +#endif + + +#if defined(_MSC_VER) || defined(__CYGWIN__) || defined(__MINGW32__) || defined( __BCPLUSPLUS__) || defined( __MWERKS__) + # if defined( OSG_LIBRARY_STATIC ) + # define OSGPARTICLE_EXPORT + # elif defined( OSGPARTICLE_LIBRARY ) + # define OSGPARTICLE_EXPORT __declspec(dllexport) + # else + # define OSGPARTICLE_EXPORT __declspec(dllimport) + # endif +#else + # define OSGPARTICLE_EXPORT +#endif + +/** + +\namespace osgParticle + +The osgParticle library is a NodeKit that extends the core scene graph to support particle effects. +*/ + + +#endif diff --git a/libs/include/android/osgParticle/FireEffect b/libs/include/android/osgParticle/FireEffect new file mode 100755 index 0000000..bca4297 --- /dev/null +++ b/libs/include/android/osgParticle/FireEffect @@ -0,0 +1,57 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGPARTICLE_FIREEFFECT +#define OSGPARTICLE_FIREEFFECT + +#include +#include +#include + +namespace osgParticle +{ + + class OSGPARTICLE_EXPORT FireEffect : public ParticleEffect + { + public: + + explicit FireEffect(bool automaticSetup=true); + + FireEffect(const osg::Vec3& position, float scale=1.0f, float intensity=1.0f); + + FireEffect(const FireEffect& copy, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY); + + META_Node(osgParticle,FireEffect); + + virtual void setDefaults(); + + virtual void setUpEmitterAndProgram(); + + virtual Emitter* getEmitter() { return _emitter.get(); } + virtual const Emitter* getEmitter() const { return _emitter.get(); } + + virtual Program* getProgram() { return _program.get(); } + virtual const Program* getProgram() const { return _program.get(); } + + protected: + + virtual ~FireEffect() {} + + osg::ref_ptr _emitter; + osg::ref_ptr _program; + + + }; +} + +#endif diff --git a/libs/include/android/osgParticle/FluidFrictionOperator b/libs/include/android/osgParticle/FluidFrictionOperator new file mode 100755 index 0000000..8e4bdf1 --- /dev/null +++ b/libs/include/android/osgParticle/FluidFrictionOperator @@ -0,0 +1,148 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +//osgParticle - Copyright (C) 2002 Marco Jez + +#ifndef OSGPARTICLE_FLUIDFRICTIONOPERATOR +#define OSGPARTICLE_FLUIDFRICTIONOPERATOR 1 + +#include +#include + +#include +#include +#include + +namespace osgParticle +{ + + class Particle; + + /** An operator that simulates the friction of a fluid. + By using this operator you can let the particles move in a fluid of a given density + and viscosity. There are two functions to quickly setup the parameters for pure water + and air. You can decide whether to compute the forces using the particle's physical + radius or another value, by calling the setOverrideRadius() method. + */ + class OSGPARTICLE_EXPORT FluidFrictionOperator: public Operator { + public: + + FluidFrictionOperator(); + FluidFrictionOperator(const FluidFrictionOperator& copy, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY); + + META_Object(osgParticle, FluidFrictionOperator); + + /// Set the density of the fluid. + inline void setFluidDensity(float d); + + /// Get the density of the fluid. + inline float getFluidDensity() const; + + /// Set the viscosity of the fluid. + inline void setFluidViscosity(float v); + + /// Get the viscosity of the fluid. + inline float getFluidViscosity() const; + + /// Set the wind vector. + inline void setWind(const osg::Vec3& wind) { _wind = wind; } + + /// Get the wind vector. + inline const osg::Vec3& getWind() const { return _wind; } + + /// Set the overriden radius value (pass 0 if you want to use particle's radius). + inline void setOverrideRadius(float r); + + /// Get the overriden radius value. + inline float getOverrideRadius() const; + + /// Set the fluid parameters as for air (20°C temperature). + inline void setFluidToAir(); + + /// Set the fluid parameters as for pure water (20°C temperature). + inline void setFluidToWater(); + + /// Apply the friction forces to a particle. Do not call this method manually. + void operate(Particle* P, double dt); + + /// Perform some initializations. Do not call this method manually. + inline void beginOperate(Program* prg); + + protected: + virtual ~FluidFrictionOperator() {} + FluidFrictionOperator &operator=(const FluidFrictionOperator &) { return *this; } + + private: + float _coeff_A; + float _coeff_B; + float _density; + float _viscosity; + float _ovr_rad; + osg::Vec3 _wind; + Program* _current_program; + }; + + // INLINE FUNCTIONS + + inline float FluidFrictionOperator::getFluidDensity() const + { + return _density; + } + + inline float FluidFrictionOperator::getFluidViscosity() const + { + return _viscosity; + } + + inline void FluidFrictionOperator::setFluidDensity(float d) + { + _density = d; + _coeff_B = 0.2f * osg::PI * _density; + } + + inline void FluidFrictionOperator::setFluidViscosity(float v) + { + _viscosity = v; + _coeff_A = 6 * osg::PI * _viscosity; + } + + inline void FluidFrictionOperator::setFluidToAir() + { + setFluidViscosity(1.8e-5f); + setFluidDensity(1.2929f); + } + + inline void FluidFrictionOperator::setFluidToWater() + { + setFluidViscosity(1.002e-3f); + setFluidDensity(1.0f); + } + + inline float FluidFrictionOperator::getOverrideRadius() const + { + return _ovr_rad; + } + + inline void FluidFrictionOperator::setOverrideRadius(float r) + { + _ovr_rad = r; + } + + inline void FluidFrictionOperator::beginOperate(Program* prg) + { + _current_program = prg; + } + +} + + +#endif diff --git a/libs/include/android/osgParticle/FluidProgram b/libs/include/android/osgParticle/FluidProgram new file mode 100755 index 0000000..08d223e --- /dev/null +++ b/libs/include/android/osgParticle/FluidProgram @@ -0,0 +1,114 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGPARTICLE_FLUIDPROGRAM +#define OSGPARTICLE_FLUIDPROGRAM 1 + +#include +#include + +#include +#include +#include +#include + +namespace osgParticle +{ + + /** A program class for performing operations on particles using a sequence of operators. + To use a FluidProgram you have to create some Operator objects and + add them to the program. + All operators will be applied to each particle in the same order they've been added to the program. + */ + class OSGPARTICLE_EXPORT FluidProgram: public Program { + public: + FluidProgram(); + FluidProgram(const FluidProgram& copy, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY); + + META_Node(osgParticle,FluidProgram); + + /// Set the viscosity of the fluid. + inline void setFluidViscosity(float v) + { + _viscosity = v; + _viscosityCoefficient = 6 * osg::PI * _viscosity; + } + + /// Get the viscosity of the fluid. + inline float getFluidViscosity() const { return _viscosity; } + + /// Set the density of the fluid. + inline void setFluidDensity(float d) + { + _density = d; + _densityCoefficient = 0.2f * osg::PI * _density; + } + + /// Get the density of the fluid. + inline float getFluidDensity() const { return _density; } + + + /// Set the wind vector. + inline void setWind(const osg::Vec3& wind) { _wind = wind; } + + /// Get the wind vector. + inline const osg::Vec3& getWind() const { return _wind; } + + /// Set the acceleration vector. + inline void setAcceleration(const osg::Vec3& v) { _acceleration = v; } + + /// Get the acceleration vector. + inline const osg::Vec3& getAcceleration() const { return _acceleration; } + + /** Set the acceleration vector to the gravity on earth (0, 0, -9.81). + The acceleration will be multiplied by the scale parameter. + */ + inline void setToGravity(float scale = 1.0f) { _acceleration.set(0, 0, -9.81f*scale); } + + /// Set the fluid parameters as for air (20°C temperature). + inline void setFluidToAir() + { + setToGravity(1.0f); + setFluidDensity(1.2929f); + setFluidViscosity(1.8e-5f); + } + + /// Set the fluid parameters as for pure water (20°C temperature). + inline void setFluidToWater() + { + setToGravity(1.0f); + setFluidDensity(1.0f); + setFluidViscosity(1.002e-3f); + } + + + protected: + + virtual ~FluidProgram() {} + FluidProgram& operator=(const FluidProgram&) { return *this; } + + virtual void execute(double dt); + + osg::Vec3 _acceleration; + float _viscosity; + float _density; + osg::Vec3 _wind; + + float _viscosityCoefficient; + float _densityCoefficient; + }; + + +} + +#endif diff --git a/libs/include/android/osgParticle/ForceOperator b/libs/include/android/osgParticle/ForceOperator new file mode 100755 index 0000000..06db430 --- /dev/null +++ b/libs/include/android/osgParticle/ForceOperator @@ -0,0 +1,98 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +//osgParticle - Copyright (C) 2002 Marco Jez + +#ifndef OSGPARTICLE_FORCEOPERATOR +#define OSGPARTICLE_FORCEOPERATOR 1 + +#include +#include +#include + +#include +#include +#include + +namespace osgParticle +{ + + /** An operator that applies a constant force to the particles. + * Remember that if the mass of particles is expressed in kg and the lengths are + * expressed in meters, then the force should be expressed in Newtons. + */ + class ForceOperator: public Operator { + public: + inline ForceOperator(); + inline ForceOperator(const ForceOperator& copy, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY); + + META_Object(osgParticle, ForceOperator); + + /// Get the force vector. + inline const osg::Vec3& getForce() const; + + /// Set the force vector. + inline void setForce(const osg::Vec3& f); + + /// Apply the force to a particle. Do not call this method manually. + inline void operate(Particle* P, double dt); + + /// Perform some initialization. Do not call this method manually. + inline void beginOperate(Program *prg); + + protected: + virtual ~ForceOperator() {}; + ForceOperator& operator=(const ForceOperator&) { return *this; } + + private: + osg::Vec3 _force; + osg::Vec3 _xf_force; + }; + + // INLINE FUNCTIONS + + inline ForceOperator::ForceOperator() + : Operator(), _force(0, 0, 0) + { + } + + inline ForceOperator::ForceOperator(const ForceOperator& copy, const osg::CopyOp& copyop) + : Operator(copy, copyop), _force(copy._force) + { + } + + inline const osg::Vec3& ForceOperator::getForce() const + { + return _force; + } + + inline void ForceOperator::setForce(const osg::Vec3& v) + { + _force = v; + } + + inline void ForceOperator::operate(Particle* P, double dt) + { + P->addVelocity(_xf_force * (P->getMassInv() * dt)); + } + + inline void ForceOperator::beginOperate(Program *prg) + { + if (prg->getReferenceFrame() == ModularProgram::RELATIVE_RF) { + _xf_force = prg->rotateLocalToWorld(_force); + } else { + _xf_force = _force; + } + } +} + +#endif diff --git a/libs/include/android/osgParticle/Interpolator b/libs/include/android/osgParticle/Interpolator new file mode 100755 index 0000000..36f6da2 --- /dev/null +++ b/libs/include/android/osgParticle/Interpolator @@ -0,0 +1,87 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +//osgParticle - Copyright (C) 2002 Marco Jez + +#ifndef OSGPARTICLE_INTERPOLATOR +#define OSGPARTICLE_INTERPOLATOR + +#include + +#include +#include +#include +#include +#include + +namespace osgParticle +{ + + /// An abstract base class for implementing interpolators. + class Interpolator : public osg::Object { + public: + Interpolator() + : osg::Object() {} + + Interpolator(const Interpolator& copy, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY) + : osg::Object(copy, copyop) {} + + virtual const char* libraryName() const { return "osgParticle"; } + virtual const char* className() const { return "Interpolator"; } + virtual bool isSameKindAs(const osg::Object* obj) const { return dynamic_cast(obj) != 0; } + + /// Interpolate between floats. Must be overriden in descendant classes. + virtual float interpolate(float t, float y1, float y2) const = 0; + + /// Interpolate between 2-dimensional vectors. Default behavior is to interpolate each component separately. + virtual osg::Vec2 interpolate(float t, const osg::Vec2& y1, const osg::Vec2& y2) const + { + return osg::Vec2( + interpolate(t, y1.x(), y2.x()), + interpolate(t, y1.y(), y2.y()) + ); + } + + /// Interpolate between 3-dimensional vectors. Default behavior is to interpolate each component separately. + virtual osg::Vec3 interpolate(float t, const osg::Vec3& y1, const osg::Vec3& y2) const + { + return osg::Vec3( + interpolate(t, y1.x(), y2.x()), + interpolate(t, y1.y(), y2.y()), + interpolate(t, y1.z(), y2.z()) + ); + } + + /// Interpolate between 4-dimensional vectors. Default behavior is to interpolate each component separately. + virtual osg::Vec4 interpolate(float t, const osg::Vec4& y1, const osg::Vec4& y2) const + { + return osg::Vec4( + interpolate(t, y1.x(), y2.x()), + interpolate(t, y1.y(), y2.y()), + interpolate(t, y1.z(), y2.z()), + interpolate(t, y1.w(), y2.w()) + ); + } + + template + ValueType interpolate(float t, const range& r) const + { + return interpolate(t, r.minimum, r.maximum); + } + + protected: + virtual ~Interpolator() {} + }; + +} + +#endif diff --git a/libs/include/android/osgParticle/LinearInterpolator b/libs/include/android/osgParticle/LinearInterpolator new file mode 100755 index 0000000..c44e263 --- /dev/null +++ b/libs/include/android/osgParticle/LinearInterpolator @@ -0,0 +1,51 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +//osgParticle - Copyright (C) 2002 Marco Jez + +#ifndef OSGPARTICLE_LINEARINTERPOLATOR +#define OSGPARTICLE_LINEARINTERPOLATOR + +#include + +#include +#include +#include +#include + +namespace osgParticle +{ + + /// A linear interpolator. + class LinearInterpolator: public Interpolator + { + public: + LinearInterpolator() + : Interpolator() {} + + LinearInterpolator(const LinearInterpolator& copy, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY) + : Interpolator(copy, copyop) {} + + META_Object(osgParticle, LinearInterpolator); + + virtual float interpolate(float t, float y1, float y2) const + { + return y1 + (y2 - y1) * t; + } + + protected: + virtual ~LinearInterpolator() {} + }; + +} + +#endif diff --git a/libs/include/android/osgParticle/ModularEmitter b/libs/include/android/osgParticle/ModularEmitter new file mode 100755 index 0000000..98dab01 --- /dev/null +++ b/libs/include/android/osgParticle/ModularEmitter @@ -0,0 +1,158 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +//osgParticle - Copyright (C) 2002 Marco Jez + +#ifndef OSGPARTICLE_MODULAREMITTER +#define OSGPARTICLE_MODULAREMITTER 1 + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace osgParticle +{ + + /** An emitter class that holds three objects to control the creation of particles. + These objects are a counter, a placer and a shooter. + The counter controls the number of particles to be emitted at each frame; + the placer must initialize the particle's position vector, while the shooter initializes + its velocity vector. + You can use the predefined counter/placer/shooter classes, or you can create your own. + */ + class OSGPARTICLE_EXPORT ModularEmitter: public Emitter { + public: + ModularEmitter(); + ModularEmitter(const ModularEmitter& copy, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY); + + META_Node(osgParticle,ModularEmitter); + + /// Get the counter object. + inline Counter* getCounter(); + + /// Get the const Counter object. + inline const Counter* getCounter() const; + + /// Set the Counter object. + inline void setCounter(Counter* c); + + /// Get the ratio between number of particle to create in compensation for movement of the emitter + inline float getNumParticlesToCreateMovementCompensationRatio() const; + + /// Set the ratio between number of particle to create in compenstation for movement of the emitter + inline void setNumParticlesToCreateMovementCompensationRatio(float r); + + + /// Get the Placer object. + inline Placer* getPlacer(); + + /// Get the const Placer object. + inline const Placer* getPlacer() const; + + /// Set the Placer object. + inline void setPlacer(Placer* p); + + /// Get the Shooter object. + inline Shooter *getShooter(); + + /// Get the const Shooter object. + inline const Shooter *getShooter() const; + + /// Set the Shooter object. + inline void setShooter(Shooter *s); + + protected: + virtual ~ModularEmitter() {} + ModularEmitter &operator=(const ModularEmitter &) { return *this; } + + virtual void emitParticles(double dt); + + private: + + float _numParticleToCreateMovementCompensationRatio; + osg::ref_ptr _counter; + osg::ref_ptr _placer; + osg::ref_ptr _shooter; + }; + + // INLINE FUNCTIONS + + inline Counter* ModularEmitter::getCounter() + { + return _counter.get(); + } + + inline const Counter* ModularEmitter::getCounter() const + { + return _counter.get(); + } + + inline void ModularEmitter::setCounter(Counter* c) + { + _counter = c; + } + + inline float ModularEmitter::getNumParticlesToCreateMovementCompensationRatio() const + { + return _numParticleToCreateMovementCompensationRatio; + } + + inline void ModularEmitter::setNumParticlesToCreateMovementCompensationRatio(float r) + { + _numParticleToCreateMovementCompensationRatio = r; + } + + inline Placer* ModularEmitter::getPlacer() + { + return _placer.get(); + } + + inline const Placer* ModularEmitter::getPlacer() const + { + return _placer.get(); + } + + inline void ModularEmitter::setPlacer(Placer* p) + { + _placer = p; + } + + inline Shooter *ModularEmitter::getShooter() + { + return _shooter.get(); + } + + inline const Shooter *ModularEmitter::getShooter() const + { + return _shooter.get(); + } + + inline void ModularEmitter::setShooter(Shooter *s) + { + _shooter = s; + } + +} + +#endif diff --git a/libs/include/android/osgParticle/ModularProgram b/libs/include/android/osgParticle/ModularProgram new file mode 100755 index 0000000..9f72ea1 --- /dev/null +++ b/libs/include/android/osgParticle/ModularProgram @@ -0,0 +1,99 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +//osgParticle - Copyright (C) 2002 Marco Jez + +#ifndef OSGPARTICLE_MODULARPROGRAM +#define OSGPARTICLE_MODULARPROGRAM 1 + +#include +#include +#include + +#include +#include +#include +#include + +namespace osgParticle +{ + + /** A program class for performing operations on particles using a sequence of operators. + To use a ModularProgram you have to create some Operator objects and + add them to the program. + All operators will be applied to each particle in the same order they've been added to the program. + */ + class OSGPARTICLE_EXPORT ModularProgram: public Program { + public: + ModularProgram(); + ModularProgram(const ModularProgram& copy, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY); + + META_Node(osgParticle,ModularProgram); + + /// Get the number of operators. + inline int numOperators() const; + + /// Add an operator to the list. + inline void addOperator(Operator* o); + + /// Get a pointer to an operator in the list. + inline Operator* getOperator(int i); + + /// Get a const pointer to an operator in the list. + inline const Operator* getOperator(int i) const; + + /// Remove an operator from the list. + inline void removeOperator(int i); + + protected: + virtual ~ModularProgram() {} + ModularProgram& operator=(const ModularProgram&) { return *this; } + + void execute(double dt); + + private: + typedef std::vector > Operator_vector; + + Operator_vector _operators; + }; + + // INLINE FUNCTIONS + + inline int ModularProgram::numOperators() const + { + return static_cast(_operators.size()); + } + + inline void ModularProgram::addOperator(Operator* o) + { + _operators.push_back(o); + } + + inline Operator* ModularProgram::getOperator(int i) + { + return _operators[i].get(); + } + + inline const Operator* ModularProgram::getOperator(int i) const + { + return _operators[i].get(); + } + + inline void ModularProgram::removeOperator(int i) + { + _operators.erase(_operators.begin()+i); + } + + +} + +#endif diff --git a/libs/include/android/osgParticle/MultiSegmentPlacer b/libs/include/android/osgParticle/MultiSegmentPlacer new file mode 100755 index 0000000..1c733ef --- /dev/null +++ b/libs/include/android/osgParticle/MultiSegmentPlacer @@ -0,0 +1,144 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +//osgParticle - Copyright (C) 2002 Marco Jez + +#ifndef OSGPARTICLE_MULTISEGMENT_PLACER +#define OSGPARTICLE_MULTISEGMENT_PLACER 1 + +#include +#include +#include + +#include +#include + +#include +#include +#include +#include + +namespace osgParticle { + + /** A polyline-shaped particle placer. + This placer class sets the position of incoming particles by choosing a random point on the + specified sequence of connected segments. + */ + class OSGPARTICLE_EXPORT MultiSegmentPlacer: public Placer { + public: + MultiSegmentPlacer(); + MultiSegmentPlacer(const MultiSegmentPlacer& copy, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY); + + META_Object(osgParticle, MultiSegmentPlacer); + + /// Get the number of vertices which define the segments. + inline int numVertices() const; + + /// Get a vertex. + inline const osg::Vec3& getVertex(int i) const; + + /// Set a vertex. + inline void setVertex(int i, const osg::Vec3& v); + + /// Set a vertex. + inline void setVertex(int i, float x, float y, float z); + + /// Add a vertex. + inline void addVertex(const osg::Vec3& v); + + /// Add a vertex. + inline void addVertex(float x, float y, float z); + + /// Remove a vertex. + inline void removeVertex(int i); + + /// Place a partice. Called automatically by ModularEmitter, do not call this method manually. + void place(Particle* P) const; + + /// return the length of the multi-segment + inline float volume() const; + + /// return the control position + inline osg::Vec3 getControlPosition() const; + + protected: + virtual ~MultiSegmentPlacer() {} + MultiSegmentPlacer& operator=(const MultiSegmentPlacer&) { return *this; } + + private: + typedef std::pair Vertex_data; + typedef std::vector Vertex_vector; + + Vertex_vector _vx; + float _total_length; + + void recompute_length(); + }; + + // INLINE FUNCTIONS + + + inline int MultiSegmentPlacer::numVertices() const + { + return static_cast(_vx.size()); + } + + inline const osg::Vec3& MultiSegmentPlacer::getVertex(int i) const + { + return _vx[i].first; + } + + inline void MultiSegmentPlacer::setVertex(int i, const osg::Vec3& v) + { + _vx[i].first = v; + recompute_length(); + } + + inline void MultiSegmentPlacer::setVertex(int i, float x, float y, float z) + { + _vx[i].first.set(x, y, z); + recompute_length(); + } + + inline void MultiSegmentPlacer::addVertex(const osg::Vec3& v) + { + float l = 0; + if (_vx.size() > 0) { + l = (v - _vx.back().first).length(); + } + _total_length += l; + _vx.push_back(std::make_pair(v, _total_length)); + } + + inline void MultiSegmentPlacer::addVertex(float x, float y, float z) + { + addVertex(osg::Vec3(x, y, z)); + } + + inline void MultiSegmentPlacer::removeVertex(int i) + { + _vx.erase(_vx.begin()+i); + recompute_length(); + } + + inline float MultiSegmentPlacer::volume() const + { + return _total_length; + } + + inline osg::Vec3 MultiSegmentPlacer::getControlPosition() const + { + return _vx.empty() ? osg::Vec3(0.0f,0.0f,0.0f) : _vx[0].first; + } + +} +#endif diff --git a/libs/include/android/osgParticle/Operator b/libs/include/android/osgParticle/Operator new file mode 100755 index 0000000..bd9e652 --- /dev/null +++ b/libs/include/android/osgParticle/Operator @@ -0,0 +1,115 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +//osgParticle - Copyright (C) 2002 Marco Jez + +#ifndef OSGPARTICLE_OPERATOR +#define OSGPARTICLE_OPERATOR 1 + +#include + +#include +#include +#include + +namespace osgParticle +{ + + // forward declaration to avoid including the whole header file + class Particle; + + /** An abstract base class used by ModularProgram to perform operations on particles before they are updated. + To implement a new operator, derive from this class and override the operate() method. + You should also override the beginOperate() method to query the calling program for the reference frame + used, and initialize the right transformations if needed. + */ + class Operator: public osg::Object { + public: + inline Operator(); + inline Operator(const Operator& copy, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY); + + virtual const char* libraryName() const { return "osgParticle"; } + virtual const char* className() const { return "Operator"; } + virtual bool isSameKindAs(const osg::Object* obj) const { return dynamic_cast(obj) != 0; } + + /// Get whether this operator is enabled. + inline bool isEnabled() const; + + /// Enable or disable this operator. + inline void setEnabled(bool v); + + /** Do something on all emitted particles. + This method is called by ModularProgram objects to perform some operations + on the particles. By default, it will call the operate() method for each particle. + You must override it in descendant classes. + */ + virtual void operateParticles(ParticleSystem* ps, double dt) + { + int n = ps->numParticles(); + for (int i=0; igetParticle(i); + if (P->isAlive() && isEnabled()) operate(P, dt); + } + } + + /** Do something on a particle. + You must override it in descendant classes. Common operations + consist of modifying the particle's velocity vector. The dt parameter is + the time elapsed from last operation. + */ + virtual void operate(Particle* P, double dt) = 0; + + /** Do something before processing particles via the operate() method. + Overriding this method could be necessary to query the calling Program object + for the current reference frame. If the reference frame is RELATIVE_RF, then your + class should prepare itself to do all operations in local coordinates. + */ + virtual void beginOperate(Program *) {} + + /// Do something after all particles have been processed. + virtual void endOperate() {} + + protected: + virtual ~Operator() {} + Operator &operator=(const Operator &) { return *this; } + + private: + bool _enabled; + }; + + // INLINE FUNCTIONS + + inline Operator::Operator() + : osg::Object(), _enabled(true) + { + } + + inline Operator::Operator(const Operator& copy, const osg::CopyOp& copyop) + : osg::Object(copy, copyop), _enabled(copy._enabled) + { + } + + inline bool Operator::isEnabled() const + { + return _enabled; + } + + inline void Operator::setEnabled(bool v) + { + _enabled = v; + } + + +} + +#endif diff --git a/libs/include/android/osgParticle/OrbitOperator b/libs/include/android/osgParticle/OrbitOperator new file mode 100755 index 0000000..be2bbfd --- /dev/null +++ b/libs/include/android/osgParticle/OrbitOperator @@ -0,0 +1,112 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2010 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +// Written by Wang Rui, (C) 2010 + +#ifndef OSGPARTICLE_ORBITOPERATOR +#define OSGPARTICLE_ORBITOPERATOR + +#include +#include +#include + +namespace osgParticle +{ + + +/** An orbit operator forces particles in the orbit around a point. + Refer to David McAllister's Particle System API (http://www.particlesystems.org) +*/ +class OrbitOperator : public Operator +{ +public: + OrbitOperator() + : Operator(), _magnitude(1.0f), _epsilon(1e-3), _maxRadius(FLT_MAX) + {} + + OrbitOperator( const OrbitOperator& copy, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY ) + : Operator(copy, copyop), _center(copy._center), _magnitude(copy._magnitude), + _epsilon(copy._epsilon), _maxRadius(copy._maxRadius) + {} + + META_Object( osgParticle, OrbitOperator ); + + /// Set the center of orbit + void setCenter( const osg::Vec3& c ) { _center = c; } + + /// Get the center of orbit + const osg::Vec3& getCenter() const { return _center; } + + /// Set the acceleration scale + void setMagnitude( float mag ) { _magnitude = mag; } + + /// Get the acceleration scale + float getMagnitude() const { return _magnitude; } + + /// Set the acceleration epsilon + void setEpsilon( float eps ) { _epsilon = eps; } + + /// Get the acceleration epsilon + float getEpsilon() const { return _epsilon; } + + /// Set max radius between the center and the particle + void setMaxRadius( float max ) { _maxRadius = max; } + + /// Get max radius between the center and the particle + float getMaxRadius() const { return _maxRadius; } + + /// Apply the acceleration to a particle. Do not call this method manually. + inline void operate( Particle* P, double dt ); + + /// Perform some initializations. Do not call this method manually. + inline void beginOperate( Program* prg ); + +protected: + virtual ~OrbitOperator() {} + OrbitOperator& operator=( const OrbitOperator& ) { return *this; } + + osg::Vec3 _center; + osg::Vec3 _xf_center; + float _magnitude; + float _epsilon; + float _maxRadius; +}; + +// INLINE METHODS + +inline void OrbitOperator::operate( Particle* P, double dt ) +{ + osg::Vec3 dir = _xf_center - P->getPosition(); + float length = dir.length(); + if ( length<_maxRadius ) + { + P->addVelocity( dir * ((_magnitude * dt) / + (length * (_epsilon+length*length))) ); + } +} + +inline void OrbitOperator::beginOperate( Program* prg ) +{ + if ( prg->getReferenceFrame()==ModularProgram::RELATIVE_RF ) + { + _xf_center = prg->transformLocalToWorld(_center); + } + else + { + _xf_center = _center; + } +} + + +} + +#endif diff --git a/libs/include/android/osgParticle/Particle b/libs/include/android/osgParticle/Particle new file mode 100755 index 0000000..ea34ee8 --- /dev/null +++ b/libs/include/android/osgParticle/Particle @@ -0,0 +1,649 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +//osgParticle - Copyright (C) 2002 Marco Jez + +#ifndef OSGPARTICLE_PARTICLE +#define OSGPARTICLE_PARTICLE 1 + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace osgParticle +{ + + // forward declare so we can reference it + class ParticleSystem; + + /** Implementation of a particle. + Objects of this class are particles, they have some graphical properties + and some physical properties. Particles are created by emitters and then placed + into Particle Systems, where they live and get updated at each frame. + Particles can either live forever (lifeTime < 0), or die after a specified + time (lifeTime >= 0). For each property which is defined as a range of values, a + "current" value will be evaluated at each frame by interpolating the min + and max values so that curr_value = min when t == 0, and + curr_value = max when t == lifeTime. + You may customize the interpolator objects to achieve any kind of transition. + If you want the particle to live forever, set its lifetime to any value <= 0; + in that case, no interpolation is done to compute real-time properties, and only + minimum values are used. + */ + class OSGPARTICLE_EXPORT Particle { + friend class ParticleSystem; + public: + + enum + { + INVALID_INDEX = -1 + }; + + /** + Shape of particles. + NOTE: the LINE shape should be used in conjunction with FIXED alignment mode (see ParticleSystem). + */ + enum Shape { + POINT, // uses GL_POINTS as primitive + QUAD, // uses GL_QUADS as primitive + QUAD_TRIANGLESTRIP, // uses GL_TRI_angleSTRIP as primitive, but each particle needs a glBegin/glEnd pair + HEXAGON, // may save some filling time, but uses more triangles + LINE, // uses GL_LINES to draw line segments that point to the direction of motion + USER // uses a user-defined drawable as primitive + }; + + Particle(); + + /// Get the shape of the particle. + inline Shape getShape() const; + + /// Set the shape of the particle. + inline void setShape(Shape s); + + /// Get whether the particle is still alive. + inline bool isAlive() const; + + /// Get the life time of the particle (in seconds). + inline double getLifeTime() const; + + /// Get the age of the particle (in seconds). + inline double getAge() const; + + /// Get the minimum and maximum values for polygon size. + inline const rangef& getSizeRange() const; + + /// Get the minimum and maximum values for alpha. + inline const rangef& getAlphaRange() const; + + /// Get the minimum and maximum values for color. + inline const rangev4& getColorRange() const; + + /// Get the interpolator for computing the size of polygons. + inline const Interpolator* getSizeInterpolator() const; + + /// Get the interpolator for computing alpha values. + inline const Interpolator* getAlphaInterpolator() const; + + /// Get the interpolator for computing color values. + inline const Interpolator* getColorInterpolator() const; + + /** Get the physical radius of the particle. + For built-in operators to work correctly, lengths must be expressed in meters. + */ + inline float getRadius() const; + + /** Get the mass of the particle. + For built-in operators to work correctly, remember that the mass is expressed in kg. + */ + inline float getMass() const; + + /// Get 1 / getMass(). + inline float getMassInv() const; + + /// Get the position vector. + inline const osg::Vec3& getPosition() const; + + /** Get the velocity vector. + For built-in operators to work correctly, remember that velocity components are expressed + in meters per second. + */ + inline const osg::Vec3& getVelocity() const; + + /// Get the previous position (the position before last update). + inline const osg::Vec3& getPreviousPosition() const; + + /// Get the angle vector. + inline const osg::Vec3& getAngle() const; + + /// Get the rotational velocity vector. + inline const osg::Vec3& getAngularVelocity() const; + + /// Get the previous angle vector. + inline const osg::Vec3& getPreviousAngle() const; + + /// Get the current color + inline const osg::Vec4& getCurrentColor() const { return _current_color; } + + /// Get the current alpha + inline float getCurrentAlpha() const { return _current_alpha; } + + /// Get the s texture coordinate of the bottom left of the particle + inline float getSTexCoord() const { return _s_coord; } + + /// Get the t texture coordinate of the bottom left of the particle + inline float getTTexCoord() const { return _t_coord; } + + /// Get width of texture tile + inline int getTileS() const; + + /// Get height of texture tile + inline int getTileT() const; + + /// Get number of texture tiles + inline int getNumTiles() const { return _end_tile - _start_tile + 1; } + + /** Kill the particle on next update + NOTE: after calling this function, the isAlive() method will still + return true until the particle is updated again. + */ + inline void kill(); + + /// Set the life time of the particle. + inline void setLifeTime(double t); + + /// Set the minimum and maximum values for polygon size. + inline void setSizeRange(const rangef& r); + + /// Set the minimum and maximum values for alpha. + inline void setAlphaRange(const rangef& r); + + /// Set the minimum and maximum values for color. + inline void setColorRange(const rangev4& r); + + /// Set the interpolator for computing size values. + inline void setSizeInterpolator(Interpolator* ri); + + /// Set the interpolator for computing alpha values. + inline void setAlphaInterpolator(Interpolator* ai); + + /// Set the interpolator for computing color values. + inline void setColorInterpolator(Interpolator* ci); + + /** Set the physical radius of the particle. + For built-in operators to work correctly, lengths must be expressed in meters. + */ + inline void setRadius(float r); + + /** Set the mass of the particle. + For built-in operators to work correctly, remember that the mass is expressed in kg. + */ + inline void setMass(float m); + + /// Set the position vector. + inline void setPosition(const osg::Vec3& p); + + /** Set the velocity vector. + For built-in operators to work correctly, remember that velocity components are expressed + in meters per second. + */ + inline void setVelocity(const osg::Vec3& v); + + /// Add a vector to the velocity vector. + inline void addVelocity(const osg::Vec3& dv); + + /// Transform position and velocity vectors by a matrix. + inline void transformPositionVelocity(const osg::Matrix& xform); + + /// Transform position and velocity vectors by a combination of two matrices + void transformPositionVelocity(const osg::Matrix& xform1, const osg::Matrix& xform2, float r); + + /// Set the angle vector. + inline void setAngle(const osg::Vec3& a); + + /** + Set the angular velocity vector. + Components x, y and z are angles of rotation around the respective axis (in radians). + */ + inline void setAngularVelocity(const osg::Vec3& v); + + /// Add a vector to the angular velocity vector. + inline void addAngularVelocity(const osg::Vec3& dv); + + /// Transform angle and angularVelocity vectors by a matrix. + inline void transformAngleVelocity(const osg::Matrix& xform); + + /** Update the particle (don't call this method manually). + This method is called automatically by ParticleSystem::update(); it + updates the graphical properties of the particle for the current time, + checks whether the particle is still alive, and then updates its position + by computing P = P + V * dt (where P is the position and V is the velocity). + */ + bool update(double dt, bool onlyTimeStamp); + + /// Perform some pre-rendering tasks. Called automatically by particle systems. + inline void beginRender(osg::GLBeginEndAdapter* gl) const; + + /// Render the particle. Called automatically by particle systems. + void render(osg::GLBeginEndAdapter* gl, const osg::Vec3& xpos, const osg::Vec3& px, const osg::Vec3& py, float scale = 1.0f) const; + + /// Render the particle with user-defined drawable + void render(osg::RenderInfo& renderInfo, const osg::Vec3& xpos, const osg::Vec3& xrot) const; + + /// Perform some post-rendering tasks. Called automatically by particle systems. + inline void endRender(osg::GLBeginEndAdapter* gl) const; + + /// Get the current (interpolated) polygon size. Valid only after the first call to update(). + inline float getCurrentSize() const; + + /// Specify how the particle texture is tiled. + /// All tiles in the given range are sequentially displayed during the lifetime + /// of the particle. When no range is given, all tiles are displayed during the lifetime. + inline void setTextureTileRange(int sTile, int tTile, int startTile, int endTile); + + /// Same as above, range starts at 0 and ends at end + inline void setTextureTile(int sTile, int tTile, int end = -1); + + inline int getStartTile() const; + + inline int getEndTile() const; + + /// Set the previous particle + inline void setPreviousParticle(int previous) { _previousParticle = previous; } + + /// Get the previous particle + inline int getPreviousParticle() const { return _previousParticle; } + + /// Set the next particle + inline void setNextParticle(int next) { _nextParticle = next; } + + /// Get the const next particle + inline int getNextParticle() const { return _nextParticle; } + + /// Set the depth of the particle + inline void setDepth(double d) { _depth = d; } + + /// Get the depth of the particle + inline double getDepth() const { return _depth; } + + /// Set the user-defined particle drawable + inline void setDrawable(osg::Drawable* d) { _drawable = d; } + + /// Get the user-defined particle drawable + inline osg::Drawable* getDrawable() const { return _drawable.get(); } + + /// Sorting operator + bool operator<(const Particle &P) const { return _depth < P._depth; } + + /// Method for initializing a particles texture coords as part of a connected particle system. + void setUpTexCoordsAsPartOfConnectedParticleSystem(ParticleSystem* ps); + + protected: + + Shape _shape; + + rangef _sr; + rangef _ar; + rangev4 _cr; + + osg::ref_ptr _si; + osg::ref_ptr _ai; + osg::ref_ptr _ci; + + bool _mustdie; + double _lifeTime; + + float _radius; + float _mass; + float _massinv; + osg::Vec3 _prev_pos; + osg::Vec3 _position; + osg::Vec3 _velocity; + + osg::Vec3 _prev_angle; + osg::Vec3 _angle; + osg::Vec3 _angul_arvel; + + double _t0; + + float _alive; + float _current_size; + float _current_alpha; + osg::Vec3 _base_prop; // [0] _alive [1] _current_size [2] _current_alpha + osg::Vec4 _current_color; + + float _s_tile; + float _t_tile; + int _start_tile; + int _end_tile; + int _cur_tile; + float _s_coord; + float _t_coord; + + // previous and next Particles are only used in ConnectedParticleSystems + int _previousParticle; + int _nextParticle; + + // the depth of the particle is used only when sorting is enabled + double _depth; + + // the particle drawable is used only when USER shape is enabled + osg::ref_ptr _drawable; + }; + + // INLINE FUNCTIONS + + inline Particle::Shape Particle::getShape() const + { + return _shape; + } + + inline void Particle::setShape(Shape s) + { + _shape = s; + } + + inline bool Particle::isAlive() const + { + return _alive>0.0f; + } + + inline double Particle::getLifeTime() const + { + return _lifeTime; + } + + inline double Particle::getAge() const + { + return _t0; + } + + inline float Particle::getRadius() const + { + return _radius; + } + + inline void Particle::setRadius(float r) + { + _radius = r; + } + + inline const rangef& Particle::getSizeRange() const + { + return _sr; + } + + inline const rangef& Particle::getAlphaRange() const + { + return _ar; + } + + inline const rangev4& Particle::getColorRange() const + { + return _cr; + } + + inline const Interpolator* Particle::getSizeInterpolator() const + { + return _si.get(); + } + + inline const Interpolator* Particle::getAlphaInterpolator() const + { + return _ai.get(); + } + + inline const Interpolator* Particle::getColorInterpolator() const + { + return _ci.get(); + } + + inline const osg::Vec3& Particle::getPosition() const + { + return _position; + } + + inline const osg::Vec3& Particle::getVelocity() const + { + return _velocity; + } + + inline const osg::Vec3& Particle::getPreviousPosition() const + { + return _prev_pos; + } + + inline const osg::Vec3& Particle::getAngle() const + { + return _angle; + } + + inline const osg::Vec3& Particle::getAngularVelocity() const + { + return _angul_arvel; + } + + inline const osg::Vec3& Particle::getPreviousAngle() const + { + return _prev_angle; + } + + inline int Particle::getTileS() const + { + return (_s_tile>0.0f) ? static_cast(1.0f / _s_tile) : 1; + } + + inline int Particle::getTileT() const + { + return (_t_tile>0.0f) ? static_cast(1.0f / _t_tile) : 1; + } + + inline void Particle::kill() + { + _mustdie = true; + } + + inline void Particle::setLifeTime(double t) + { + _lifeTime = t; + } + + inline void Particle::setSizeRange(const rangef& r) + { + _sr = r; + } + + inline void Particle::setAlphaRange(const rangef& r) + { + _ar = r; + } + + inline void Particle::setColorRange(const rangev4& r) + { + _cr = r; + } + + inline void Particle::setSizeInterpolator(Interpolator* ri) + { + _si = ri; + } + + inline void Particle::setAlphaInterpolator(Interpolator* ai) + { + _ai = ai; + } + + inline void Particle::setColorInterpolator(Interpolator* ci) + { + _ci = ci; + } + + inline void Particle::setPosition(const osg::Vec3& p) + { + _position = p; + } + + inline void Particle::setVelocity(const osg::Vec3& v) + { + _velocity = v; + } + + inline void Particle::addVelocity(const osg::Vec3& dv) + { + _velocity += dv; + } + + inline void Particle::transformPositionVelocity(const osg::Matrix& xform) + { + _position = xform.preMult(_position); + _velocity = osg::Matrix::transform3x3(_velocity, xform); + } + + inline void Particle::transformPositionVelocity(const osg::Matrix& xform1, const osg::Matrix& xform2, float r) + { + osg::Vec3 position1 = xform1.preMult(_position); + osg::Vec3 velocity1 = osg::Matrix::transform3x3(_velocity, xform1); + osg::Vec3 position2 = xform2.preMult(_position); + osg::Vec3 velocity2 = osg::Matrix::transform3x3(_velocity, xform2); + float one_minus_r = 1.0f-r; + _position = position1*r + position2*one_minus_r; + _velocity = velocity1*r + velocity2*one_minus_r; + } + + inline void Particle::setAngle(const osg::Vec3& a) + { + _angle = a; + } + + inline void Particle::setAngularVelocity(const osg::Vec3& v) + { + _angul_arvel = v; + } + + inline void Particle::addAngularVelocity(const osg::Vec3& dv) + { + _angul_arvel += dv; + } + + inline void Particle::transformAngleVelocity(const osg::Matrix& xform) + { + // this should be optimized! + + osg::Vec3 a1 = _angle + _angul_arvel; + + _angle = xform.preMult(_angle); + a1 = xform.preMult(a1); + + _angul_arvel = a1 - _angle; + } + + inline float Particle::getMass() const + { + return _mass; + } + + inline float Particle::getMassInv() const + { + return _massinv; + } + + inline void Particle::setMass(float m) + { + _mass = m; + _massinv = 1 / m; + } + + inline void Particle::beginRender(osg::GLBeginEndAdapter* gl) const + { + switch (_shape) + { + case POINT: + gl->Begin(GL_POINTS); + break; + case QUAD: + gl->Begin(GL_QUADS); + break; + case LINE: + gl->Begin(GL_LINES); + break; + default: ; + } + } + + inline void Particle::endRender(osg::GLBeginEndAdapter* gl) const + { + switch (_shape) + { + case POINT: + case QUAD: + case LINE: + gl->End(); + break; + default: ; + } + } + + inline float Particle::getCurrentSize() const + { + return _current_size; + } + + + inline void Particle::setTextureTile(int sTile, int tTile, int end) + { + setTextureTileRange(sTile, tTile, -1, end); + } + + inline void Particle::setTextureTileRange(int sTile, int tTile, int startTile, int endTile) + { + _s_tile = (sTile>0) ? 1.0f / static_cast(sTile) : 1.0f; + _t_tile = (tTile>0) ? 1.0f / static_cast(tTile) : 1.0f; + + if(startTile == -1) + { + _start_tile = 0; + } + else + { + _start_tile = startTile; + } + + if(endTile == -1) + { + _end_tile = sTile * tTile; + } + else + { + _end_tile = endTile; + } + } + + inline int Particle::getStartTile() const + { + return _start_tile; + } + + inline int Particle::getEndTile() const + { + return _end_tile; + } +} + +#endif + diff --git a/libs/include/android/osgParticle/ParticleEffect b/libs/include/android/osgParticle/ParticleEffect new file mode 100755 index 0000000..f6df657 --- /dev/null +++ b/libs/include/android/osgParticle/ParticleEffect @@ -0,0 +1,118 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGPARTICLE_PARTICLEEFFECT +#define OSGPARTICLE_PARTICLEEFFECT + +#include +#include + +namespace osgParticle +{ + + class OSGPARTICLE_EXPORT ParticleEffect : public osg::Group + { + public: + + explicit ParticleEffect(bool automaticSetup=true): + _automaticSetup(automaticSetup), + _useLocalParticleSystem(true), + _scale(1.0f), + _intensity(1.0f), + _startTime(0.0), + _emitterDuration(1.0), + _wind(0.0f,0.0f,0.0f) + {} + + ParticleEffect(const ParticleEffect& copy, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY); + + + virtual const char* libraryName() const { return "osgParticle"; } + virtual const char* className() const { return "ParticleEffect"; } + virtual bool isSameKindAs(const osg::Object* obj) const { return dynamic_cast(obj) != 0; } + virtual void accept(osg::NodeVisitor& nv) { if (nv.validNodeMask(*this)) { nv.pushOntoNodePath(this); nv.apply(*this); nv.popFromNodePath(); } } + + void setAutomaticSetup(bool flag) { _automaticSetup = flag; } + bool getAutomaticSetup() const { return _automaticSetup; } + + void setUseLocalParticleSystem(bool local); + bool getUseLocalParticleSystem() const { return _useLocalParticleSystem; } + + void setTextureFileName(const std::string& filename); + const std::string& getTextureFileName() const { return _textureFileName; } + + void setDefaultParticleTemplate(const Particle& p); + const Particle& getDefaultParticleTemplate() const { return _defaultParticleTemplate; } + + void setPosition(const osg::Vec3& position); + const osg::Vec3& getPosition() const { return _position; } + + void setScale(float scale); + float getScale() const { return _scale; } + + void setIntensity(float intensity); + float getIntensity() const { return _intensity; } + + void setStartTime(double startTime); + double getStartTime() const { return _startTime; } + + void setEmitterDuration(double duration); + double getEmitterDuration() const { return _emitterDuration; } + + void setParticleDuration(double duration); + double getParticleDuration() const { return _defaultParticleTemplate.getLifeTime(); } + + void setWind(const osg::Vec3& wind); + const osg::Vec3& getWind() const { return _wind; } + + /// Get whether all particles are dead + bool areAllParticlesDead() const { return _particleSystem.valid()?_particleSystem->areAllParticlesDead():true; } + + virtual Emitter* getEmitter() = 0; + virtual const Emitter* getEmitter() const = 0; + + virtual Program* getProgram() = 0; + virtual const Program* getProgram() const = 0; + + void setParticleSystem(ParticleSystem* ps); + inline ParticleSystem* getParticleSystem() { return _particleSystem.get(); } + inline const ParticleSystem* getParticleSystem() const { return _particleSystem.get(); } + + virtual void setDefaults(); + + virtual void setUpEmitterAndProgram() = 0; + + virtual void buildEffect(); + + protected: + + virtual ~ParticleEffect() {} + + bool _automaticSetup; + + osg::ref_ptr _particleSystem; + + bool _useLocalParticleSystem; + std::string _textureFileName; + Particle _defaultParticleTemplate; + osg::Vec3 _position; + float _scale; + float _intensity; + double _startTime; + double _emitterDuration; + osg::Vec3 _wind; + }; + +} + +#endif diff --git a/libs/include/android/osgParticle/ParticleProcessor b/libs/include/android/osgParticle/ParticleProcessor new file mode 100755 index 0000000..58f0cd7 --- /dev/null +++ b/libs/include/android/osgParticle/ParticleProcessor @@ -0,0 +1,340 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +//osgParticle - Copyright (C) 2002 Marco Jez + +#ifndef OSGPARTICLE_PARTICLEPROCESSOR +#define OSGPARTICLE_PARTICLEPROCESSOR 1 + +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace osgParticle +{ + + /** A common base interface for those classes which need to do something on particles. Such classes + * are, for example, Emitter (particle generation) and Program (particle animation). + * This class holds some properties, like a reference frame and a reference to a ParticleSystem; + * descendant classes should process the particles taking into account the reference frame, computing the right + * transformations when needed. + */ + class OSGPARTICLE_EXPORT ParticleProcessor: public osg::Node { + public: + + enum ReferenceFrame { + RELATIVE_RF, + ABSOLUTE_RF + }; + + ParticleProcessor(); + ParticleProcessor(const ParticleProcessor& copy, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY); + + virtual const char* libraryName() const { return "osgParticle"; } + virtual const char* className() const { return "ParticleProcessor"; } + virtual bool isSameKindAs(const osg::Object* obj) const { return dynamic_cast(obj) != 0; } + virtual void accept(osg::NodeVisitor& nv) { if (nv.validNodeMask(*this)) { nv.pushOntoNodePath(this); nv.apply(*this); nv.popFromNodePath(); } } + + /// Get the reference frame. + inline ReferenceFrame getReferenceFrame() const; + + /// Set the reference frame. + inline void setReferenceFrame(ReferenceFrame rf); + + /// Get whether this processor is enabled or not. + bool getEnabled() const { return _enabled; } + inline bool isEnabled() const; + + /// Set whether this processor is enabled or not. + inline void setEnabled(bool v); + + /// Get a pointer to the destination particle system. + inline ParticleSystem* getParticleSystem(); + + /// Get a const pointer to the destination particle system. + inline const ParticleSystem* getParticleSystem() const; + + /// Set the destination particle system. + inline void setParticleSystem(ParticleSystem* ps); + + /// Set the endless flag of this processor. + inline void setEndless(bool type); + + /// Check whether this processor is endless. + bool getEndless() const { return _endless; } + inline bool isEndless() const; + + /// Set the lifetime of this processor. + inline void setLifeTime(double t); + + /// Get the lifetime of this processor. + inline double getLifeTime() const; + + /// Set the start time of this processor. + inline void setStartTime(double t); + + /// Get the start time of this processor. + inline double getStartTime() const; + + /// Set the current time of this processor. + inline void setCurrentTime(double t); + + /// Get the current time of this processor. + inline double getCurrentTime() const; + + /// Set the reset time of this processor. A value of 0 disables reset. + inline void setResetTime(double t); + + /// Get the reset time of this processor. + inline double getResetTime() const; + + /** + Check whether the processor is alive with respect to start time and + life duration. Note that this method may return true even if the + processor has been disabled by calling setEnabled(false). To test + whether the processor is actually processing particles or not, you + should evaluate (isEnabled() && isAlive()). + */ + inline bool isAlive() const; + + void traverse(osg::NodeVisitor& nv); + + /// Get the current local-to-world transformation matrix (valid only during cull traversal). + inline const osg::Matrix& getLocalToWorldMatrix(); + + /// Get the current world-to-local transformation matrix (valid only during cull traversal). + inline const osg::Matrix& getWorldToLocalMatrix(); + + /// Get the previous local-to-world transformation matrix (valid only during cull traversal). + inline const osg::Matrix& getPreviousLocalToWorldMatrix(); + + /// Get the previous world-to-local transformation matrix (valid only during cull traversal). + inline const osg::Matrix& getPreviousWorldToLocalMatrix(); + + + /// Transform a point from local to world coordinates (valid only during cull traversal). + inline osg::Vec3 transformLocalToWorld(const osg::Vec3& P); + + /// Transform a vector from local to world coordinates, discarding translation (valid only during cull traversal). + inline osg::Vec3 rotateLocalToWorld(const osg::Vec3& P); + + /// Transform a point from world to local coordinates (valid only during cull traversal). + inline osg::Vec3 transformWorldToLocal(const osg::Vec3& P); + + /// Transform a vector from world to local coordinates, discarding translation (valid only during cull traversal). + inline osg::Vec3 rotateWorldToLocal(const osg::Vec3& P); + + virtual osg::BoundingSphere computeBound() const; + + protected: + virtual ~ParticleProcessor() {} + ParticleProcessor& operator=(const ParticleProcessor&) { return *this; } + + virtual void process(double dt) = 0; + + private: + ReferenceFrame _rf; + bool _enabled; + double _t0; + osg::ref_ptr _ps; + bool _first_ltw_compute; + bool _need_ltw_matrix; + bool _first_wtl_compute; + bool _need_wtl_matrix; + osg::Matrix _ltw_matrix; + osg::Matrix _wtl_matrix; + osg::Matrix _previous_ltw_matrix; + osg::Matrix _previous_wtl_matrix; + osg::NodeVisitor* _current_nodevisitor; + + bool _endless; + + double _lifeTime; + double _startTime; + double _currentTime; + double _resetTime; + + //added- 1/17/06- bgandere@nps.edu + //a var to keep from doing multiple updates + unsigned int _frameNumber; + }; + + // INLINE FUNCTIONS + + inline ParticleProcessor::ReferenceFrame ParticleProcessor::getReferenceFrame() const + { + return _rf; + } + + inline void ParticleProcessor::setReferenceFrame(ReferenceFrame rf) + { + _rf = rf; + } + + inline bool ParticleProcessor::isEnabled() const + { + return _enabled; + } + + inline void ParticleProcessor::setEnabled(bool v) + { + _enabled = v; + if (_enabled) + { + _currentTime = 0; + } + } + + inline ParticleSystem* ParticleProcessor::getParticleSystem() + { + return _ps.get(); + } + + inline const ParticleSystem* ParticleProcessor::getParticleSystem() const + { + return _ps.get(); + } + + inline void ParticleProcessor::setParticleSystem(ParticleSystem* ps) + { + _ps = ps; + } + + inline void ParticleProcessor::setEndless(bool type) + { + _endless = type; + } + + inline bool ParticleProcessor::isEndless() const + { + return _endless; + } + + inline void ParticleProcessor::setLifeTime(double t) + { + _lifeTime = t; + } + + inline double ParticleProcessor::getLifeTime() const + { + return _lifeTime; + } + + inline void ParticleProcessor::setStartTime(double t) + { + _startTime = t; + } + + inline double ParticleProcessor::getStartTime() const + { + return _startTime; + } + inline void ParticleProcessor::setCurrentTime(double t) + { + _currentTime = t; + } + + inline double ParticleProcessor::getCurrentTime() const + { + return _currentTime; + } + + inline void ParticleProcessor::setResetTime(double t) + { + _resetTime = t; + } + + inline double ParticleProcessor::getResetTime() const + { + return _resetTime; + } + + inline const osg::Matrix& ParticleProcessor::getLocalToWorldMatrix() + { + if (_need_ltw_matrix) { + _previous_ltw_matrix = _ltw_matrix; + _ltw_matrix = osg::computeLocalToWorld(_current_nodevisitor->getNodePath()); + if (_first_ltw_compute) + { + _previous_ltw_matrix = _ltw_matrix; + _first_ltw_compute = false; + } + _need_ltw_matrix = false; + } + return _ltw_matrix; + } + + inline const osg::Matrix& ParticleProcessor::getWorldToLocalMatrix() + { + if (_need_wtl_matrix) { + _previous_wtl_matrix = _wtl_matrix; + _wtl_matrix = osg::computeWorldToLocal(_current_nodevisitor->getNodePath()); + if (_first_wtl_compute) + { + _previous_wtl_matrix = _wtl_matrix; + _first_wtl_compute = false; + } + _need_wtl_matrix = false; + } + return _wtl_matrix; + } + + inline const osg::Matrix& ParticleProcessor::getPreviousLocalToWorldMatrix() + { + if (_need_ltw_matrix) getLocalToWorldMatrix(); + return _previous_ltw_matrix; + } + + inline const osg::Matrix& ParticleProcessor::getPreviousWorldToLocalMatrix() + { + if (_need_wtl_matrix) getWorldToLocalMatrix(); + return _previous_wtl_matrix; + } + + inline osg::Vec3 ParticleProcessor::transformLocalToWorld(const osg::Vec3& P) + { + return getLocalToWorldMatrix().preMult(P); + } + + inline osg::Vec3 ParticleProcessor::transformWorldToLocal(const osg::Vec3& P) + { + return getWorldToLocalMatrix().preMult(P); + } + + inline osg::Vec3 ParticleProcessor::rotateLocalToWorld(const osg::Vec3& P) + { + return getLocalToWorldMatrix().preMult(P) - + getLocalToWorldMatrix().preMult(osg::Vec3(0, 0, 0)); + } + + inline osg::Vec3 ParticleProcessor::rotateWorldToLocal(const osg::Vec3& P) + { + return getWorldToLocalMatrix().preMult(P) - + getWorldToLocalMatrix().preMult(osg::Vec3(0, 0, 0)); + } + + inline bool ParticleProcessor::isAlive() const + { + return _currentTime < (_lifeTime + _startTime); + } + +} + + +#endif diff --git a/libs/include/android/osgParticle/ParticleSystem b/libs/include/android/osgParticle/ParticleSystem new file mode 100755 index 0000000..d32c750 --- /dev/null +++ b/libs/include/android/osgParticle/ParticleSystem @@ -0,0 +1,527 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +//osgParticle - Copyright (C) 2002 Marco Jez + +#ifndef OSGPARTICLE_PARTICLESYSTEM +#define OSGPARTICLE_PARTICLESYSTEM 1 + +#include +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +// 9th Febrary 2009, disabled the use of ReadWriteMutex as it looks like this +// is introducing threading problems due to threading problems in OpenThreads::ReadWriteMutex. +// #define OSGPARTICLE_USE_ReadWriteMutex + +#ifdef OSGPARTICLE_USE_ReadWriteMutex + #include +#else + #include + #include +#endif + + +namespace osgParticle +{ + + /** The heart of this class library; its purpose is to hold a set of particles and manage particle creation, update, rendering and destruction. + * You can add this drawable to any Geode as you usually do with other + * Drawable classes. Each instance of ParticleSystem is a separate set of + * particles; it provides the interface for creating particles and iterating + * through them (see the Emitter and Program classes). + */ + class OSGPARTICLE_EXPORT ParticleSystem: public osg::Drawable { + public: + + enum Alignment { + BILLBOARD, + FIXED + }; + + ParticleSystem(); + ParticleSystem(const ParticleSystem& copy, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY); + + META_Object(osgParticle, ParticleSystem); + + /// Get the alignment type of particles. + inline Alignment getParticleAlignment() const; + + /// Set the alignment type of particles. + inline void setParticleAlignment(Alignment a); + + /// Get the X-axis alignment vector. + inline const osg::Vec3& getAlignVectorX() const; + + /// Set the X-axis alignment vector. + inline void setAlignVectorX(const osg::Vec3& v); + + /// Get the Y-axis alignment vector. + inline const osg::Vec3& getAlignVectorY() const; + + /// Set the Y-axis alignment vector. + inline void setAlignVectorY(const osg::Vec3& v); + + /// Set the alignment vectors. + inline void setAlignVectors(const osg::Vec3& X, const osg::Vec3& Y); + + + + enum ParticleScaleReferenceFrame + { + LOCAL_COORDINATES, + WORLD_COORDINATES + }; + + /** Set whether the particles should be scaled relative to world coordaintes or local coordinates.*/ + void setParticleScaleReferenceFrame(ParticleScaleReferenceFrame rf) { _particleScaleReferenceFrame = rf; } + + /** Get whether the particles should be scaled relative to world coordaintes or local coordinates.*/ + ParticleScaleReferenceFrame getParticleScaleReferenceFrame() const { return _particleScaleReferenceFrame; } + + + + /// Get the default bounding box + inline const osg::BoundingBox& getDefaultBoundingBox() const; + + /** Set the default bounding box. + The default bounding box is used when a real bounding box cannot be computed, for example + because no particles has been updated yet. + */ + inline void setDefaultBoundingBox(const osg::BoundingBox& bbox); + + /// Return true if we use vertex arrays for rendering particles. + bool getUseVertexArray() const { return _useVertexArray; } + + /** Set to use vertex arrays for rendering particles. + Lots of variables will be omitted: particles' shape, alive or not, visibility distance, and so on, + so the rendering result is not as good as we wish (although it's fast than using glBegin/glEnd). + We had better use this for GLSL shaders, in which particle parameters will be kept as uniforms. + This method is called automatically by setDefaultAttributesUsingShaders(). + */ + void setUseVertexArray(bool v) { _useVertexArray = v; } + + /// Return true if shaders are required. + bool getUseShaders() const { return _useShaders; } + + /** Set to use GLSL shaders for rendering particles. + Particles' parameters will be used as shader attribute arrays, and necessary variables, including + the visibility distance, texture, etc, will be used and updated as uniforms. + */ + void setUseShaders(bool v) { _useShaders = v; _dirty_uniforms = true; } + + /// Get the double pass rendering flag. + inline bool getDoublePassRendering() const; + + /** Set the double pass rendering flag. + Double pass rendering avoids overdraw problems between particle systems + and other opaque objects. If you can render all the particle systems after + the opaque objects, then double pass is not necessary and can be turned off (best choice). + If you set the default attributes with setDefaultAttributes, then the particle + system will fall into a transparent bin. + */ + inline void setDoublePassRendering(bool v); + + /// Return true if the particle system is frozen. + bool getFrozen() const { return _frozen; } + inline bool isFrozen() const; + + /** Set or reset the frozen state. + When the particle system is frozen, emitters and programs won't do anything on it. + */ + inline void setFrozen(bool v); + + /// Get the number of allocated particles (alive + dead). + inline int numParticles() const; + + /// Get the number of dead particles. + inline int numDeadParticles() const; + + /// Get whether all particles are dead + inline bool areAllParticlesDead() const { return numDeadParticles()==numParticles(); } + + /// Get a pointer to the i-th particle. + inline Particle* getParticle(int i); + + /// Get a const pointer to the i-th particle. + inline const Particle* getParticle(int i) const; + + /// Create a new particle from the specified template (or the default one if ptemplate is null). + inline virtual Particle* createParticle(const Particle* ptemplate); + + /// Destroy the i-th particle. + inline virtual void destroyParticle(int i); + + /// Reuse the i-th particle. + inline virtual void reuseParticle(int i) { _deadparts.push(&(_particles[i])); } + + /// Get the last frame number. + inline unsigned int getLastFrameNumber() const; + + /// Get the unique delta time for emitters and updaters to use + inline double& getDeltaTime( double currentTime ); + + /// Get a reference to the default particle template. + inline Particle& getDefaultParticleTemplate(); + + /// Get a const reference to the default particle template. + inline const Particle& getDefaultParticleTemplate() const; + + /// Set the default particle template (particle is copied). + inline void setDefaultParticleTemplate(const Particle& p); + + /// Get whether the particle system can freeze when culled + inline bool getFreezeOnCull() const; + + /// Set whether the particle system can freeze when culled (default is true) + inline void setFreezeOnCull(bool v); + + /** A useful method to set the most common StateAttribute's in one call. + If texturefile is empty, then texturing is turned off. + */ + void setDefaultAttributes(const std::string& texturefile = "", bool emissive_particles = true, bool lighting = false, int texture_unit = 0); + + /** A useful method to set the most common StateAttribute and use GLSL shaders to draw particles. + At present, when enabling shaders in the particle system, user-defined shapes will not be usable. + If texturefile is empty, then texturing is turned off. + */ + void setDefaultAttributesUsingShaders(const std::string& texturefile = "", bool emissive_particles = true, int texture_unit = 0); + + /// (EXPERIMENTAL) Get the level of detail. + inline int getLevelOfDetail() const; + + /** (EXPERIMENTAL) Set the level of detail. The total number of particles is divided by the detail value to + get the actual number of particles to be drawn. This value must be greater than zero. + */ + inline void setLevelOfDetail(int v); + + enum SortMode + { + NO_SORT, + SORT_FRONT_TO_BACK, + SORT_BACK_TO_FRONT + }; + + /// Get the sort mode. + inline SortMode getSortMode() const; + + /** Set the sort mode. It will force resorting the particle list by the Z direction of the view coordinates. + This can be used for the purpose of transparent rendering or setVisibilityDistance(). + */ + inline void setSortMode(SortMode mode); + + /// Get the visibility distance. + inline double getVisibilityDistance() const; + + /** Set the visibility distance which allows the particles to be rendered only when depth is inside the distance. + When using shaders, it can work well directly; otherwise the sort mode should also be set to pre-compute depth. + */ + inline void setVisibilityDistance(double distance); + + /// Update the particles. Don't call this directly, use a ParticleSystemUpdater instead. + virtual void update(double dt, osg::NodeVisitor& nv); + + virtual void drawImplementation(osg::RenderInfo& renderInfo) const; + + virtual osg::BoundingBox computeBound() const; + +#ifdef OSGPARTICLE_USE_ReadWriteMutex + typedef OpenThreads::ReadWriteMutex ReadWriterMutex; + typedef OpenThreads::ScopedReadLock ScopedReadLock; + typedef OpenThreads::ScopedWriteLock ScopedWriteLock; +#else + typedef OpenThreads::Mutex ReadWriterMutex; + typedef OpenThreads::ScopedLock ScopedReadLock; + typedef OpenThreads::ScopedLock ScopedWriteLock; +#endif + + ReadWriterMutex* getReadWriteMutex() const { return &_readWriteMutex; } + + protected: + + virtual ~ParticleSystem(); + + ParticleSystem& operator=(const ParticleSystem&) { return *this; } + + inline void update_bounds(const osg::Vec3& p, float r); + void single_pass_render(osg::RenderInfo& renderInfo, const osg::Matrix& modelview) const; + void render_vertex_array(osg::RenderInfo& renderInfo) const; + + typedef std::vector Particle_vector; + typedef std::stack Death_stack; + + Particle_vector _particles; + Death_stack _deadparts; + + osg::BoundingBox _def_bbox; + + Alignment _alignment; + osg::Vec3 _align_X_axis; + osg::Vec3 _align_Y_axis; + ParticleScaleReferenceFrame _particleScaleReferenceFrame; + + bool _useVertexArray; + bool _useShaders; + bool _dirty_uniforms; + + bool _doublepass; + bool _frozen; + + osg::Vec3 _bmin; + osg::Vec3 _bmax; + + bool _reset_bounds_flag; + bool _bounds_computed; + + Particle _def_ptemp; + mutable unsigned int _last_frame; + mutable bool _dirty_dt; + bool _freeze_on_cull; + + double _t0; + double _dt; + + int _detail; + SortMode _sortMode; + double _visibilityDistance; + + mutable int _draw_count; + + mutable ReadWriterMutex _readWriteMutex; + }; + + // INLINE FUNCTIONS + + inline ParticleSystem::Alignment ParticleSystem::getParticleAlignment() const + { + return _alignment; + } + + inline void ParticleSystem::setParticleAlignment(Alignment a) + { + _alignment = a; + } + + inline const osg::Vec3& ParticleSystem::getAlignVectorX() const + { + return _align_X_axis; + } + + inline void ParticleSystem::setAlignVectorX(const osg::Vec3& v) + { + _align_X_axis = v; + } + + inline const osg::Vec3& ParticleSystem::getAlignVectorY() const + { + return _align_Y_axis; + } + + inline void ParticleSystem::setAlignVectorY(const osg::Vec3& v) + { + _align_Y_axis = v; + } + + inline void ParticleSystem::setAlignVectors(const osg::Vec3& X, const osg::Vec3& Y) + { + _align_X_axis = X; + _align_Y_axis = Y; + } + + inline bool ParticleSystem::isFrozen() const + { + return _frozen; + } + + inline void ParticleSystem::setFrozen(bool v) + { + _frozen = v; + } + + inline const osg::BoundingBox& ParticleSystem::getDefaultBoundingBox() const + { + return _def_bbox; + } + + inline void ParticleSystem::setDefaultBoundingBox(const osg::BoundingBox& bbox) + { + _def_bbox = bbox; + } + + inline bool ParticleSystem::getDoublePassRendering() const + { + return _doublepass; + } + + inline void ParticleSystem::setDoublePassRendering(bool v) + { + _doublepass = v; + } + + inline int ParticleSystem::numParticles() const + { + return static_cast(_particles.size()); + } + + inline int ParticleSystem::numDeadParticles() const + { + return static_cast(_deadparts.size()); + } + + inline Particle* ParticleSystem::getParticle(int i) + { + return &_particles[i]; + } + + inline const Particle* ParticleSystem::getParticle(int i) const + { + return &_particles[i]; + } + + inline void ParticleSystem::destroyParticle(int i) + { + _particles[i].kill(); + } + + inline unsigned int ParticleSystem::getLastFrameNumber() const + { + return _last_frame; + } + + inline double& ParticleSystem::getDeltaTime( double currentTime ) + { + if ( _dirty_dt ) + { + _dt = currentTime - _t0; + if ( _dt<0.0 ) _dt = 0.0; + + _t0 = currentTime; + _dirty_dt = false; + } + return _dt; + } + + inline void ParticleSystem::update_bounds(const osg::Vec3& p, float r) + { + if (_reset_bounds_flag) { + _reset_bounds_flag = false; + _bmin = p - osg::Vec3(r,r,r); + _bmax = p + osg::Vec3(r,r,r); + } else { + if (p.x() - r < _bmin.x()) _bmin.x() = p.x() - r; + if (p.y() - r < _bmin.y()) _bmin.y() = p.y() - r; + if (p.z() - r < _bmin.z()) _bmin.z() = p.z() - r; + if (p.x() + r > _bmax.x()) _bmax.x() = p.x() + r; + if (p.y() + r > _bmax.y()) _bmax.y() = p.y() + r; + if (p.z() + r > _bmax.z()) _bmax.z() = p.z() + r; + } + if (!_bounds_computed) + _bounds_computed = true; + } + + inline Particle& ParticleSystem::getDefaultParticleTemplate() + { + return _def_ptemp; + } + + inline const Particle& ParticleSystem::getDefaultParticleTemplate() const + { + return _def_ptemp; + } + + inline void ParticleSystem::setDefaultParticleTemplate(const Particle& p) + { + _def_ptemp = p; + } + + inline bool ParticleSystem::getFreezeOnCull() const + { + return _freeze_on_cull; + } + + inline void ParticleSystem::setFreezeOnCull(bool v) + { + _freeze_on_cull = v; + } + + inline int ParticleSystem::getLevelOfDetail() const + { + return _detail; + } + + inline void ParticleSystem::setLevelOfDetail(int v) + { + if (v < 1) v = 1; + _detail = v; + } + + inline ParticleSystem::SortMode ParticleSystem::getSortMode() const + { + return _sortMode; + } + + inline void ParticleSystem::setSortMode(SortMode mode) + { + _sortMode = mode; + } + + inline double ParticleSystem::getVisibilityDistance() const + { + return _visibilityDistance; + } + + inline void ParticleSystem::setVisibilityDistance(double distance) + { + _visibilityDistance = distance; + if (_useShaders) _dirty_uniforms = true; + } + + // I'm not sure this function should be inlined... + + inline Particle* ParticleSystem::createParticle(const Particle* ptemplate) + { + // is there any dead particle? + if (!_deadparts.empty()) { + + // retrieve a pointer to the last dead particle + Particle* P = _deadparts.top(); + + // create a new (alive) particle in the same place + *P = ptemplate? *ptemplate: _def_ptemp; + + // remove the pointer from the death stack + _deadparts.pop(); + return P; + + } else { + + // add a new particle to the vector + _particles.push_back(ptemplate? *ptemplate: _def_ptemp); + return &_particles.back(); + } + } + + +} + +#endif diff --git a/libs/include/android/osgParticle/ParticleSystemUpdater b/libs/include/android/osgParticle/ParticleSystemUpdater new file mode 100755 index 0000000..d229308 --- /dev/null +++ b/libs/include/android/osgParticle/ParticleSystemUpdater @@ -0,0 +1,134 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +//osgParticle - Copyright (C) 2002 Marco Jez + +#ifndef OSGPARTICLE_PARTICLESYSTEMUPDATER +#define OSGPARTICLE_PARTICLESYSTEMUPDATER 1 + +#include +#include + +#include + +#include +#include +#include +#include +#include + +#include + +namespace osgParticle +{ + + /** A useful node class for updating particle systems automatically. + When a ParticleSystemUpdater is traversed by a cull visitor, it calls the + update() method on the specified particle systems. You should place this updater + AFTER other nodes like emitters and programs. + */ + class OSGPARTICLE_EXPORT ParticleSystemUpdater: public osg::Node { + public: + ParticleSystemUpdater(); + ParticleSystemUpdater(const ParticleSystemUpdater& copy, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY); + + META_Node(osgParticle,ParticleSystemUpdater); + + /// Add a particle system to the list. + virtual bool addParticleSystem(ParticleSystem* ps); + + /// Remove a particle system from the list (by pointer). + virtual bool removeParticleSystem(ParticleSystem* ps); + + /// Remove a particle system(s) from the list (by index). + virtual bool removeParticleSystem(unsigned int i, unsigned int numParticleSystemsToRemove=1); + + /// Replace ParticleSystem with another ParticleSystem. + virtual bool replaceParticleSystem(ParticleSystem* origPS, ParticleSystem* newPS); + + /// set a particle system by index. + virtual bool setParticleSystem( unsigned int i, ParticleSystem* ps ); + + /// Return the number of particle systems on the list. + inline unsigned int getNumParticleSystems() const; + + /// Get a particle system from the list. + inline ParticleSystem* getParticleSystem(unsigned int i); + + /// Get a particle system from the list. + inline const ParticleSystem* getParticleSystem(unsigned int i) const; + + /// return true if ParticleSystem is contained within ParticlsSystemUpdater. + inline bool containsParticleSystem( const ParticleSystem* ps ) const; + + /// get index number of ParticleSystem. + inline unsigned int getParticleSystemIndex( const ParticleSystem* ps ) const; + + virtual void traverse(osg::NodeVisitor& nv); + + virtual osg::BoundingSphere computeBound() const; + + protected: + virtual ~ParticleSystemUpdater() {} + ParticleSystemUpdater &operator=(const ParticleSystemUpdater &) { return *this; } + + private: + typedef std::vector > ParticleSystem_Vector; + + ParticleSystem_Vector _psv; + double _t0; + + //added 1/17/06- bgandere@nps.edu + //a var to keep from doing multiple updates per frame + unsigned int _frameNumber; + }; + + // INLINE FUNCTIONS + + inline unsigned int ParticleSystemUpdater::getNumParticleSystems() const + { + return static_cast(_psv.size()); + } + + inline ParticleSystem* ParticleSystemUpdater::getParticleSystem(unsigned int i) + { + return _psv[i].get(); + } + + inline const ParticleSystem* ParticleSystemUpdater::getParticleSystem(unsigned int i) const + { + return _psv[i].get(); + } + + inline bool ParticleSystemUpdater::containsParticleSystem( const ParticleSystem* ps ) const + { + for( ParticleSystem_Vector::const_iterator itr=_psv.begin(); + itr!=_psv.end(); + ++itr ) + { + if( itr->get() == ps ) return true; + } + return false; + } + + inline unsigned int ParticleSystemUpdater::getParticleSystemIndex( const ParticleSystem* ps ) const + { + for( unsigned int particleSystemNum=0; particleSystemNum<_psv.size(); ++particleSystemNum ) + { + if( _psv[particleSystemNum] == ps ) return particleSystemNum; + } + return _psv.size(); // node not found. + } + +} + +#endif diff --git a/libs/include/android/osgParticle/Placer b/libs/include/android/osgParticle/Placer new file mode 100755 index 0000000..c92a227 --- /dev/null +++ b/libs/include/android/osgParticle/Placer @@ -0,0 +1,68 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +//osgParticle - Copyright (C) 2002 Marco Jez + +#ifndef OSGPARTICLE_PLACER +#define OSGPARTICLE_PLACER 1 + +#include +#include +#include + +namespace osgParticle +{ + + class Particle; + + /** An abstract base class for implementing particle placers. A placer is an object which take + a particle as input, and places it somewhere by setting its position vector. Placer objects are + used by the ModularEmitter class as part of the particle emission process. + */ + class Placer: public osg::Object { + public: + inline Placer(); + inline Placer(const Placer& copy, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY); + + virtual const char* libraryName() const { return "osgParticle"; } + virtual const char* className() const { return "Placer"; } + virtual bool isSameKindAs(const osg::Object* obj) const { return dynamic_cast(obj) != 0; } + + /// Place a particle. Must be implemented in descendant classes. + virtual void place(Particle* P) const = 0; + + /// Volume of the placer. Can be implemented in descendant classes. + virtual float volume() const { return 1.0f; } + + /// Return the control position of particles that placer will generate. Must be implemented in descendant classes. + virtual osg::Vec3 getControlPosition() const = 0; + + protected: + ~Placer() {} + Placer& operator=(const Placer& ) { return *this; } + }; + + // INLINE FUNCTIONS + + inline Placer::Placer() + : osg::Object() + { + } + + inline Placer::Placer(const Placer& copy, const osg::CopyOp& copyop) + : osg::Object(copy, copyop) + { + } + +} + +#endif diff --git a/libs/include/android/osgParticle/PointPlacer b/libs/include/android/osgParticle/PointPlacer new file mode 100755 index 0000000..71db4a5 --- /dev/null +++ b/libs/include/android/osgParticle/PointPlacer @@ -0,0 +1,78 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +//osgParticle - Copyright (C) 2002 Marco Jez + +#ifndef OSGPARTICLE_POINT_PLACER +#define OSGPARTICLE_POINT_PLACER 1 + +#include +#include + +#include +#include + +namespace osgParticle +{ + + /** A point-shaped particle placer. + This placer class uses the center point defined in its base class CenteredPlacer + to place there all incoming particles. + */ + class PointPlacer: public CenteredPlacer { + public: + inline PointPlacer(); + inline PointPlacer(const PointPlacer& copy, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY); + + META_Object(osgParticle, PointPlacer); + + /** Place a particle. + This method is called automatically by ModularEmitter and should not be called + manually. + */ + inline void place(Particle* P) const; + + /// return the control position + inline osg::Vec3 getControlPosition() const; + + protected: + virtual ~PointPlacer() {} + PointPlacer& operator=(const PointPlacer&) { return *this; } + }; + + // INLINE FUNCTIONS + + inline PointPlacer::PointPlacer() + : CenteredPlacer() + { + } + + inline PointPlacer::PointPlacer(const PointPlacer& copy, const osg::CopyOp& copyop) + : CenteredPlacer(copy, copyop) + { + } + + inline void PointPlacer::place(Particle* P) const + { + P->setPosition(getCenter()); + } + + + inline osg::Vec3 PointPlacer::getControlPosition() const + { + return getCenter(); + } + +} + + +#endif diff --git a/libs/include/android/osgParticle/PrecipitationEffect b/libs/include/android/osgParticle/PrecipitationEffect new file mode 100755 index 0000000..1f713f4 --- /dev/null +++ b/libs/include/android/osgParticle/PrecipitationEffect @@ -0,0 +1,265 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGPARTICLE_PRECIPITATIONEFFECT +#define OSGPARTICLE_PRECIPITATIONEFFECT + +#include +#include +#include +#include + +#include + +#include + +namespace osgParticle +{ + class OSGPARTICLE_EXPORT PrecipitationEffect : public osg::Node + { + public: + + PrecipitationEffect(); + PrecipitationEffect(const PrecipitationEffect& copy, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY); + + virtual const char* libraryName() const { return "osgParticle"; } + virtual const char* className() const { return "PrecipitationEffect"; } + virtual bool isSameKindAs(const osg::Object* obj) const { return dynamic_cast(obj) != 0; } + virtual void accept(osg::NodeVisitor& nv) { if (nv.validNodeMask(*this)) { nv.pushOntoNodePath(this); nv.apply(*this); nv.popFromNodePath(); } } + + virtual void traverse(osg::NodeVisitor& nv); + + + /** Set all the parameters to create an rain effect of specified intensity.*/ + void rain(float intensity); + + /** Set all the parameters to create an snow effect of specified intensity.*/ + void snow(float intensity); + + void setMaximumParticleDensity(float density) { if (_maximumParticleDensity==density) return; _maximumParticleDensity = density; _dirty = true;} + float getMaximumParticleDensity() const { return _maximumParticleDensity; } + + void setWind(const osg::Vec3& wind) { _wind = wind; } + const osg::Vec3& getWind() const { return _wind; } + + void setPosition(const osg::Vec3& position) { _origin = position; } + const osg::Vec3& getPosition() const { return _origin; } + + void setCellSize(const osg::Vec3& cellSize) { if (_cellSize==cellSize) return; _cellSize = cellSize; _dirty = true; } + const osg::Vec3& getCellSize() const { return _cellSize; } + + void setParticleSpeed(float particleSpeed) { if (_particleSpeed==particleSpeed) return; _particleSpeed = particleSpeed; _dirty = true; } + float getParticleSpeed() const { return _particleSpeed; } + + void setParticleSize(float particleSize) { if (_particleSize==particleSize) return; _particleSize = particleSize; _dirty = true;} + float getParticleSize() const { return _particleSize; } + + void setParticleColor(const osg::Vec4& color) { if (_particleColor==color) return; _particleColor = color; _dirty = true;} + const osg::Vec4& getParticleColor() const { return _particleColor; } + + void setNearTransition(float nearTransition) { _nearTransition = nearTransition; } + float getNearTransition() const { return _nearTransition; } + + void setFarTransition(float farTransition) { _farTransition = farTransition; } + float getFarTransition() const { return _farTransition; } + + void setUseFarLineSegments(bool useFarLineSegments) { _useFarLineSegments = useFarLineSegments; } + bool getUseFarLineSegments() const { return _useFarLineSegments; } + + void setFog(osg::Fog* fog) { _fog = fog; } + osg::Fog* getFog() { return _fog.get(); } + const osg::Fog* getFog() const { return _fog.get(); } + + osg::Geometry* getQuadGeometry() { return _quadGeometry.get(); } + osg::StateSet* getQuadStateSet() { return _quadStateSet.get(); } + + osg::Geometry* getLineGeometry() { return _lineGeometry.get(); } + osg::StateSet* getLineStateSet() { return _lineStateSet.get(); } + + osg::Geometry* getPointGeometry() { return _pointGeometry.get(); } + osg::StateSet* getPointStateSet() { return _pointStateSet.get(); } + + /** Internal drawable used to render batches of cells.*/ + class OSGPARTICLE_EXPORT PrecipitationDrawable : public osg::Drawable + { + public: + + PrecipitationDrawable(); + PrecipitationDrawable(const PrecipitationDrawable& copy, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY); + + META_Object(osgParticle, PrecipitationDrawable); + + virtual bool supports(const osg::PrimitiveFunctor&) const { return false; } + virtual void accept(osg::PrimitiveFunctor&) const {} + virtual bool supports(const osg::PrimitiveIndexFunctor&) const { return false; } + virtual void accept(osg::PrimitiveIndexFunctor&) const {} + + void setRequiresPreviousMatrix(bool flag) { _requiresPreviousMatrix = flag; } + bool getRequiresPreviousMatrix() const { return _requiresPreviousMatrix; } + + void setGeometry(osg::Geometry* geom) { _geometry = geom; } + osg::Geometry* getGeometry() { return _geometry.get(); } + const osg::Geometry* getGeometry() const { return _geometry.get(); } + + void setDrawType(GLenum type) { _drawType = type; } + GLenum getDrawType() const { return _drawType; } + + void setNumberOfVertices(unsigned int numVertices) { _numberOfVertices = numVertices; } + unsigned int getNumberOfVertices() const { return _numberOfVertices; } + + virtual void drawImplementation(osg::RenderInfo& renderInfo) const; + + struct Cell + { + Cell(int in_i, int in_j, int in_k): + i(in_i), j(in_j), k(in_k) {} + + inline bool operator < (const Cell& rhs) const + { + if (irhs.i) return false; + if (jrhs.j) return false; + if (krhs.k) return false; + return false; + } + + int i; + int j; + int k; + }; + + struct DepthMatrixStartTime + { + inline bool operator < (const DepthMatrixStartTime& rhs) const + { + return depth < rhs.depth; + } + + float depth; + float startTime; + osg::Matrix modelview; + }; + + typedef std::map< Cell, DepthMatrixStartTime > CellMatrixMap; + + struct LessFunctor + { + inline bool operator () (const CellMatrixMap::value_type* lhs,const CellMatrixMap::value_type* rhs) const + { + return (*lhs).second<(*rhs).second; + } + }; + + + CellMatrixMap& getCurrentCellMatrixMap() { return _currentCellMatrixMap; } + CellMatrixMap& getPreviousCellMatrixMap() { return _previousCellMatrixMap; } + + inline void newFrame() + { + _previousCellMatrixMap.swap(_currentCellMatrixMap); + _currentCellMatrixMap.clear(); + } + + protected: + + virtual ~PrecipitationDrawable() {} + + bool _requiresPreviousMatrix; + + osg::ref_ptr _geometry; + + mutable CellMatrixMap _currentCellMatrixMap; + mutable CellMatrixMap _previousCellMatrixMap; + + GLenum _drawType; + unsigned int _numberOfVertices; + + }; + + protected: + + virtual ~PrecipitationEffect() {} + + void compileGLObjects(osg::RenderInfo& renderInfo) const; + + void update(); + + void createGeometry(unsigned int numParticles, + osg::Geometry* quad_geometry, + osg::Geometry* line_geometry, + osg::Geometry* point_geometry); + + void setUpGeometries(unsigned int numParticles); + + + struct PrecipitationDrawableSet + { + osg::ref_ptr _quadPrecipitationDrawable; + osg::ref_ptr _linePrecipitationDrawable; + osg::ref_ptr _pointPrecipitationDrawable; + }; + + void cull(PrecipitationDrawableSet& pds, osgUtil::CullVisitor* cv) const; + bool build(const osg::Vec3 eyeLocal, int i, int j, int k, float startTime, PrecipitationDrawableSet& pds, osg::Polytope& frustum, osgUtil::CullVisitor* cv) const; + + // parameters + bool _dirty; + osg::Vec3 _wind; + float _particleSpeed; + float _particleSize; + osg::Vec4 _particleColor; + float _maximumParticleDensity; + osg::Vec3 _cellSize; + float _nearTransition; + float _farTransition; + bool _useFarLineSegments; + osg::ref_ptr _fog; + + osg::ref_ptr _inversePeriodUniform; + osg::ref_ptr _particleSizeUniform; + osg::ref_ptr _particleColorUniform; + + typedef std::pair< osg::NodeVisitor*, osg::NodePath > ViewIdentifier; + typedef std::map< ViewIdentifier, PrecipitationDrawableSet > ViewDrawableMap; + + OpenThreads::Mutex _mutex; + ViewDrawableMap _viewDrawableMap; + + osg::ref_ptr _quadGeometry; + osg::ref_ptr _quadStateSet; + + osg::ref_ptr _lineGeometry; + osg::ref_ptr _lineStateSet; + + osg::ref_ptr _pointGeometry; + osg::ref_ptr _pointStateSet; + + // cache variables. + float _period; + osg::Vec3 _origin; + osg::Vec3 _du; + osg::Vec3 _dv; + osg::Vec3 _dw; + osg::Vec3 _inverse_du; + osg::Vec3 _inverse_dv; + osg::Vec3 _inverse_dw; + + double _previousFrameTime; + + }; + +} + +#endif diff --git a/libs/include/android/osgParticle/Program b/libs/include/android/osgParticle/Program new file mode 100755 index 0000000..855575e --- /dev/null +++ b/libs/include/android/osgParticle/Program @@ -0,0 +1,68 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +//osgParticle - Copyright (C) 2002 Marco Jez + +#ifndef OSGPARTICLE_PROGRAM +#define OSGPARTICLE_PROGRAM 1 + +#include +#include + +#include +#include +#include +#include + +namespace osgParticle +{ + + /** An abstract ParticleProcessor descendant for modifying particles "on the fly" + during the cull traversal. + Descendants of this class must implement the execute() method, which should iterate + through all particles in the linked particle system and modify them somehow + (usually updating their velocity vector). + */ + class OSGPARTICLE_EXPORT Program: public ParticleProcessor + { + public: + Program(); + Program(const Program& copy, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY); + + virtual const char* libraryName() const { return "osgParticle"; } + virtual const char* className() const { return "Program"; } + virtual bool isSameKindAs(const osg::Object* obj) const { return dynamic_cast(obj) != 0; } + virtual void accept(osg::NodeVisitor& nv) { if (nv.validNodeMask(*this)) { nv.pushOntoNodePath(this); nv.apply(*this); nv.popFromNodePath(); } } + + protected: + virtual ~Program() {} + Program& operator=(const Program&) { return *this; } + + /// Implementation of ParticleProcessor::process(). Do not call this method by yourself. + inline void process(double dt); + + /// Execute the program on the particle system. Must be overriden in descendant classes. + virtual void execute(double dt) = 0; + + private: + }; + + // INLINE FUNCTIONS + + inline void Program::process(double dt) + { + execute(dt); + } + +} + +#endif diff --git a/libs/include/android/osgParticle/RadialShooter b/libs/include/android/osgParticle/RadialShooter new file mode 100755 index 0000000..146c2a1 --- /dev/null +++ b/libs/include/android/osgParticle/RadialShooter @@ -0,0 +1,196 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +//osgParticle - Copyright (C) 2002 Marco Jez + +#ifndef OSGPARTICLE_RADIAL_SHOOTER +#define OSGPARTICLE_RADIAL_SHOOTER 1 + +#include +#include +#include + +#include +#include +#include + +namespace osgParticle +{ + + /** A shooter class that shoots particles radially. + This shooter computes the velocity vector of incoming particles by choosing a + random direction and a random speed. Both direction and speed are chosen within + specified ranges. The direction is defined by two angles: theta, which + is the angle between the velocity vector and the Z axis, and phi, which is + the angle between the X axis and the velocity vector projected onto the X-Y plane. + */ + class RadialShooter: public Shooter { + public: + inline RadialShooter(); + inline RadialShooter(const RadialShooter& copy, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY); + + META_Object(osgParticle, RadialShooter); + + /// Get the range of possible values for theta angle. + inline const rangef& getThetaRange() const; + + /// Set the range of possible values for theta angle. + inline void setThetaRange(const rangef& r); + + /// Set the range of possible values for theta angle. + inline void setThetaRange(float r1, float r2); + + /// Get the range of possible values for phi angle. + inline const rangef& getPhiRange() const; + + /// Set the range of possible values for phi angle. + inline void setPhiRange(const rangef& r); + + /// Set the range of possible values for phi angle. + inline void setPhiRange(float r1, float r2); + + /// Get the range of possible values for initial speed of particles. + inline const rangef& getInitialSpeedRange() const; + + /// Set the range of possible values for initial speed of particles. + inline void setInitialSpeedRange(const rangef& r); + + /// Set the range of possible values for initial speed of particles. + inline void setInitialSpeedRange(float r1, float r2); + + /// Get the range of possible values for initial rotational speed of particles. + inline const rangev3& getInitialRotationalSpeedRange() const; + + /// Set the range of possible values for initial rotational speed of particles. + inline void setInitialRotationalSpeedRange(const rangev3& r); + + /// Set the range of possible values for initial rotational speed of particles. + inline void setInitialRotationalSpeedRange(const osg::Vec3& r1, const osg::Vec3& r2); + + /// Shoot a particle. Do not call this method manually. + inline void shoot(Particle* P) const; + + protected: + virtual ~RadialShooter() {} + RadialShooter& operator=(const RadialShooter&) { return *this; } + + private: + rangef _theta_range; + rangef _phi_range; + rangef _speed_range; + rangev3 _rot_speed_range; + }; + + // INLINE FUNCTIONS + + inline RadialShooter::RadialShooter() + : Shooter(), + _theta_range(0, 0.5f*osg::PI_4), + _phi_range(0, 2*osg::PI), + _speed_range(10, 10), + _rot_speed_range(osg::Vec3(0,0,0), osg::Vec3(0,0,0)) + { + } + + inline RadialShooter::RadialShooter(const RadialShooter& copy, const osg::CopyOp& copyop) + : Shooter(copy, copyop), + _theta_range(copy._theta_range), + _phi_range(copy._phi_range), + _speed_range(copy._speed_range), + _rot_speed_range(copy._rot_speed_range) + { + } + + inline const rangef& RadialShooter::getThetaRange() const + { + return _theta_range; + } + + inline const rangef& RadialShooter::getPhiRange() const + { + return _phi_range; + } + + inline const rangef& RadialShooter::getInitialSpeedRange() const + { + return _speed_range; + } + + inline const rangev3& RadialShooter::getInitialRotationalSpeedRange() const + { + return _rot_speed_range; + } + + inline void RadialShooter::setThetaRange(const rangef& r) + { + _theta_range = r; + } + + inline void RadialShooter::setThetaRange(float r1, float r2) + { + _theta_range.minimum = r1; + _theta_range.maximum = r2; + } + + inline void RadialShooter::setPhiRange(const rangef& r) + { + _phi_range = r; + } + + inline void RadialShooter::setPhiRange(float r1, float r2) + { + _phi_range.minimum = r1; + _phi_range.maximum = r2; + } + + inline void RadialShooter::setInitialSpeedRange(const rangef& r) + { + _speed_range = r; + } + + inline void RadialShooter::setInitialSpeedRange(float r1, float r2) + { + _speed_range.minimum = r1; + _speed_range.maximum = r2; + } + + inline void RadialShooter::setInitialRotationalSpeedRange(const rangev3& r) + { + _rot_speed_range = r; + } + + inline void RadialShooter::setInitialRotationalSpeedRange(const osg::Vec3& r1, const osg::Vec3& r2) + { + _rot_speed_range.minimum = r1; + _rot_speed_range.maximum = r2; + } + + inline void RadialShooter::shoot(Particle* P) const + { + float theta = _theta_range.get_random(); + float phi = _phi_range.get_random(); + float speed = _speed_range.get_random(); + osg::Vec3 rot_speed = _rot_speed_range.get_random(); + + P->setVelocity(osg::Vec3( + speed * sinf(theta) * cosf(phi), + speed * sinf(theta) * sinf(phi), + speed * cosf(theta) + )); + + P->setAngularVelocity(rot_speed); + } + +} + + +#endif diff --git a/libs/include/android/osgParticle/RandomRateCounter b/libs/include/android/osgParticle/RandomRateCounter new file mode 100755 index 0000000..3c4462b --- /dev/null +++ b/libs/include/android/osgParticle/RandomRateCounter @@ -0,0 +1,76 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +//osgParticle - Copyright (C) 2002 Marco Jez + +#ifndef OSGPARTICLE_RANDOMRATE_COUNTER +#define OSGPARTICLE_RANDOMRATE_COUNTER 1 + +#include + +#include +#include + +namespace osgParticle +{ + + class RandomRateCounter: public VariableRateCounter { + public: + inline RandomRateCounter(); + inline RandomRateCounter(const RandomRateCounter& copy, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY); + + META_Object(osgParticle, RandomRateCounter); + + /// Return the number of particles to be created in this frame + inline int numParticlesToCreate(double dt) const; + + protected: + virtual ~RandomRateCounter() {} + + mutable float _np; + }; + + // INLINE FUNCTIONS + + inline RandomRateCounter::RandomRateCounter() + : VariableRateCounter(), _np(0) + { + } + + inline RandomRateCounter::RandomRateCounter(const RandomRateCounter& copy, const osg::CopyOp& copyop) + : VariableRateCounter(copy, copyop), _np(copy._np) + { + } + + inline int RandomRateCounter::numParticlesToCreate(double dt) const + { + // compute the number of new particles, clamping it to 1 second of particles at the maximum rate + float numNewParticles = osg::minimum(static_cast(dt * getRateRange().get_random()), getRateRange().maximum); + + // add the number of new particles to value carried over from the previous call + _np += numNewParticles; + + // round down the number of particles. + int n = static_cast(_np); + + // take away the number of rounded number of particles leaving the decimal place + // this is done so that two frames of 0.5's will results in first frame 0 new particles, second frame 1 + _np -= n; + + // return the rounded number of particles to be created + return n; + } + +} + + +#endif diff --git a/libs/include/android/osgParticle/SectorPlacer b/libs/include/android/osgParticle/SectorPlacer new file mode 100755 index 0000000..c5a9fd8 --- /dev/null +++ b/libs/include/android/osgParticle/SectorPlacer @@ -0,0 +1,149 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +//osgParticle - Copyright (C) 2002 Marco Jez + +#ifndef OSGPARTICLE_SECTOR_PLACER +#define OSGPARTICLE_SECTOR_PLACER 1 + +#include +#include +#include + +#include +#include +#include +#include + +namespace osgParticle +{ + + /** A sector-shaped particle placer. + This placer sets the initial position of incoming particle by choosing a random position + within a circular sector; this sector is defined by three parameters: a center point, + which is inherited directly from osgParticle::CenteredPlacer, a range of values + for radius, and a range of values for the central angle (sometimes called phi). + */ + class SectorPlacer: public CenteredPlacer { + public: + inline SectorPlacer(); + inline SectorPlacer(const SectorPlacer& copy, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY); + + /// Get the range of possible values for radius. + inline const rangef& getRadiusRange() const; + + /// Set the range of possible values for radius. + inline void setRadiusRange(const rangef& r); + + /// Set the range of possible values for radius. + inline void setRadiusRange(float r1, float r2); + + /// Get the range of possible values for the central angle. + inline const rangef& getPhiRange() const; + + /// Set the range of possible values for the central angle. + inline void setPhiRange(const rangef& r); + + /// Set the range of possible values for the central angle. + inline void setPhiRange(float r1, float r2); + + META_Object(osgParticle, SectorPlacer); + + /// Place a particle. Do not call it manually. + inline void place(Particle* P) const; + + /// return the area of the sector + inline float volume() const; + + /// return the control position + inline osg::Vec3 getControlPosition() const; + + protected: + virtual ~SectorPlacer() {} + SectorPlacer& operator=(const SectorPlacer&) { return *this; } + + private: + rangef _rad_range; + rangef _phi_range; + }; + + // INLINE FUNCTIONS + + inline SectorPlacer::SectorPlacer() + : CenteredPlacer(), _rad_range(0, 1), _phi_range(0, osg::PI*2) + { + } + + inline SectorPlacer::SectorPlacer(const SectorPlacer& copy, const osg::CopyOp& copyop) + : CenteredPlacer(copy, copyop), _rad_range(copy._rad_range), _phi_range(copy._phi_range) + { + } + + inline const rangef& SectorPlacer::getRadiusRange() const + { + return _rad_range; + } + + inline const rangef& SectorPlacer::getPhiRange() const + { + return _phi_range; + } + + inline void SectorPlacer::setRadiusRange(const rangef& r) + { + _rad_range = r; + } + + inline void SectorPlacer::setRadiusRange(float r1, float r2) + { + _rad_range.minimum = r1; + _rad_range.maximum = r2; + } + + inline void SectorPlacer::setPhiRange(const rangef& r) + { + _phi_range = r; + } + + inline void SectorPlacer::setPhiRange(float r1, float r2) + { + _phi_range.minimum = r1; + _phi_range.maximum = r2; + } + + inline void SectorPlacer::place(Particle* P) const + { + float rad = _rad_range.get_random_sqrtf(); + float phi = _phi_range.get_random(); + + osg::Vec3 pos( + getCenter().x() + rad * cosf(phi), + getCenter().y() + rad * sinf(phi), + getCenter().z()); + + P->setPosition(pos); + } + + inline float SectorPlacer::volume() const + { + return 0.5f * (_phi_range.maximum - _phi_range.minimum) * + (_rad_range.maximum*_rad_range.maximum - _rad_range.minimum*_rad_range.minimum); + } + + inline osg::Vec3 SectorPlacer::getControlPosition() const + { + return getCenter(); + } + +} + +#endif diff --git a/libs/include/android/osgParticle/SegmentPlacer b/libs/include/android/osgParticle/SegmentPlacer new file mode 100755 index 0000000..a008ff6 --- /dev/null +++ b/libs/include/android/osgParticle/SegmentPlacer @@ -0,0 +1,144 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +//osgParticle - Copyright (C) 2002 Marco Jez + +#ifndef OSGPARTICLE_SEGMENT_PLACER +#define OSGPARTICLE_SEGMENT_PLACER 1 + +#include +#include + +#include +#include +#include + +namespace osgParticle { + + /** A segment-shaped particle placer. + To use this placer you have to define a segment, by setting its two vertices (A and B); + when an emitter requests a SegmentPlacer to place a particle, the position is chosen randomly + within that segment. + */ + class SegmentPlacer: public Placer { + public: + inline SegmentPlacer(); + inline SegmentPlacer(const SegmentPlacer& copy, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY); + + META_Object(osgParticle, SegmentPlacer); + + /// get vertex A. + inline const osg::Vec3& getVertexA() const; + + /// Set vertex A of the segment as a vector. + inline void setVertexA(const osg::Vec3& v); + + /// Set vertex A of the segment as three floats. + inline void setVertexA(float x, float y, float z); + + /// get vertex B. + inline const osg::Vec3& getVertexB() const; + + /// Set vertex B of the segment as a vector. + inline void setVertexB(const osg::Vec3& v); + + /// Set vertex B of the segment as three floats. + inline void setVertexB(float x, float y, float z); + + /// Set both vertices. + inline void setSegment(const osg::Vec3& A, const osg::Vec3& B); + + /// Place a particle. This method is called by ModularEmitter, do not call it manually. + inline void place(Particle* P) const; + + /// return the length of the segment + inline float volume() const; + + /// return the control position + inline osg::Vec3 getControlPosition() const; + + protected: + virtual ~SegmentPlacer() {} + SegmentPlacer& operator=(const SegmentPlacer&) { return *this; } + + private: + osg::Vec3 _vertexA; + osg::Vec3 _vertexB; + }; + + // INLINE FUNCTIONS + + inline SegmentPlacer::SegmentPlacer() + : Placer(), _vertexA(-1, 0, 0), _vertexB(1, 0, 0) + { + } + + inline SegmentPlacer::SegmentPlacer(const SegmentPlacer& copy, const osg::CopyOp& copyop) + : Placer(copy, copyop), _vertexA(copy._vertexA), _vertexB(copy._vertexB) + { + } + + inline const osg::Vec3& SegmentPlacer::getVertexA() const + { + return _vertexA; + } + + inline const osg::Vec3& SegmentPlacer::getVertexB() const + { + return _vertexB; + } + + inline void SegmentPlacer::setSegment(const osg::Vec3& A, const osg::Vec3& B) + { + _vertexA = A; + _vertexB = B; + } + + inline void SegmentPlacer::place(Particle* P) const + { + P->setPosition(rangev3(_vertexA, _vertexB).get_random()); + } + + inline float SegmentPlacer::volume() const + { + return (_vertexB - _vertexA).length(); + } + + inline void SegmentPlacer::setVertexA(const osg::Vec3& v) + { + _vertexA = v; + } + + inline void SegmentPlacer::setVertexA(float x, float y, float z) + { + _vertexA.set(x, y, z); + } + + inline void SegmentPlacer::setVertexB(const osg::Vec3& v) + { + _vertexB = v; + } + + inline void SegmentPlacer::setVertexB(float x, float y, float z) + { + _vertexB.set(x, y, z); + } + + inline osg::Vec3 SegmentPlacer::getControlPosition() const + { + return (_vertexA+_vertexB)*0.5f; + } + + +} + +#endif diff --git a/libs/include/android/osgParticle/Shooter b/libs/include/android/osgParticle/Shooter new file mode 100755 index 0000000..a7aeb69 --- /dev/null +++ b/libs/include/android/osgParticle/Shooter @@ -0,0 +1,64 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +//osgParticle - Copyright (C) 2002 Marco Jez + +#ifndef OSGPARTICLE_SHOOTER +#define OSGPARTICLE_SHOOTER 1 + +#include +#include + +namespace osgParticle +{ + + class Particle; + + /** An abstract base class used by ModularEmitter to "shoot" the particles after they have been placed. + Descendants of this class must override the shoot() method. + */ + class Shooter: public osg::Object + { + public: + inline Shooter(); + inline Shooter(const Shooter& copy, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY); + + virtual const char* libraryName() const { return "osgParticle"; } + virtual const char* className() const { return "Shooter"; } + virtual bool isSameKindAs(const osg::Object* obj) const { return dynamic_cast(obj) != 0; } + + /** Shoot a particle. Must be overriden by descendants. + This method should only set the velocity vector of particle P, leaving other + attributes unchanged. + */ + virtual void shoot(Particle* P) const = 0; + + protected: + virtual ~Shooter() {} + Shooter &operator=(const Shooter &) { return *this; } + }; + + // INLINE FUNCTIONS + + inline Shooter::Shooter() + : osg::Object() + { + } + + inline Shooter::Shooter(const Shooter& copy, const osg::CopyOp& copyop) + : osg::Object(copy, copyop) + { + } + +} + +#endif diff --git a/libs/include/android/osgParticle/SinkOperator b/libs/include/android/osgParticle/SinkOperator new file mode 100755 index 0000000..372731a --- /dev/null +++ b/libs/include/android/osgParticle/SinkOperator @@ -0,0 +1,100 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2010 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +// Written by Wang Rui, (C) 2010 + +#ifndef OSGPARTICLE_SINKOPERATOR +#define OSGPARTICLE_SINKOPERATOR + +#include +#include + +namespace osgParticle +{ + + +/** A sink operator kills particles if positions or velocities inside/outside the specified domain. + Refer to David McAllister's Particle System API (http://www.particlesystems.org) +*/ +class OSGPARTICLE_EXPORT SinkOperator : public DomainOperator +{ +public: + enum SinkTarget { SINK_POSITION, SINK_VELOCITY, SINK_ANGULAR_VELOCITY }; + enum SinkStrategy { SINK_INSIDE, SINK_OUTSIDE }; + + SinkOperator() + : DomainOperator(), _sinkTarget(SINK_POSITION), _sinkStrategy(SINK_INSIDE) + {} + + SinkOperator( const SinkOperator& copy, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY ) + : DomainOperator(copy, copyop), _sinkTarget(copy._sinkTarget), _sinkStrategy(copy._sinkStrategy) + {} + + META_Object( osgParticle, SinkOperator ); + + /// Set the sink strategy + void setSinkTarget( SinkTarget so ) { _sinkTarget = so; } + + /// Get the sink strategy + SinkTarget getSinkTarget() const { return _sinkTarget; } + + /// Set the sink strategy + void setSinkStrategy( SinkStrategy ss ) { _sinkStrategy = ss; } + + /// Get the sink strategy + SinkStrategy getSinkStrategy() const { return _sinkStrategy; } + + /// Perform some initializations. Do not call this method manually. + void beginOperate( Program* prg ); + +protected: + virtual ~SinkOperator() {} + SinkOperator& operator=( const SinkOperator& ) { return *this; } + + virtual void handlePoint( const Domain& domain, Particle* P, double dt ); + virtual void handleLineSegment( const Domain& domain, Particle* P, double dt ); + virtual void handleTriangle( const Domain& domain, Particle* P, double dt ); + virtual void handleRectangle( const Domain& domain, Particle* P, double dt ); + virtual void handlePlane( const Domain& domain, Particle* P, double dt ); + virtual void handleSphere( const Domain& domain, Particle* P, double dt ); + virtual void handleBox( const Domain& domain, Particle* P, double dt ); + virtual void handleDisk( const Domain& domain, Particle* P, double dt ); + + inline const osg::Vec3& getValue( Particle* P ); + inline void kill( Particle* P, bool insideDomain ); + + SinkTarget _sinkTarget; + SinkStrategy _sinkStrategy; +}; + +// INLINE METHODS + +inline const osg::Vec3& SinkOperator::getValue( Particle* P ) +{ + switch ( _sinkTarget ) + { + case SINK_VELOCITY: return P->getVelocity(); + case SINK_ANGULAR_VELOCITY: return P->getAngularVelocity(); + case SINK_POSITION: default: return P->getPosition(); + } +} + +inline void SinkOperator::kill( Particle* P, bool insideDomain ) +{ + if ( !((_sinkStrategy==SINK_INSIDE) ^ insideDomain) ) + P->kill(); +} + + +} + +#endif diff --git a/libs/include/android/osgParticle/SmokeEffect b/libs/include/android/osgParticle/SmokeEffect new file mode 100755 index 0000000..4da6274 --- /dev/null +++ b/libs/include/android/osgParticle/SmokeEffect @@ -0,0 +1,56 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGPARTICLE_SMOKEEFFECT +#define OSGPARTICLE_SMOKEEFFECT + +#include +#include +#include + +namespace osgParticle +{ + + class OSGPARTICLE_EXPORT SmokeEffect : public ParticleEffect + { + public: + + explicit SmokeEffect(bool automaticSetup=true); + + SmokeEffect(const osg::Vec3& position, float scale=1.0f, float intensity=1.0f); + + SmokeEffect(const SmokeEffect& copy, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY); + + META_Node(osgParticle,SmokeEffect); + + virtual void setDefaults(); + + virtual void setUpEmitterAndProgram(); + + virtual Emitter* getEmitter() { return _emitter.get(); } + virtual const Emitter* getEmitter() const { return _emitter.get(); } + + virtual Program* getProgram() { return _program.get(); } + virtual const Program* getProgram() const { return _program.get(); } + + protected: + + virtual ~SmokeEffect() {} + + osg::ref_ptr _emitter; + osg::ref_ptr _program; + + }; +} + +#endif diff --git a/libs/include/android/osgParticle/SmokeTrailEffect b/libs/include/android/osgParticle/SmokeTrailEffect new file mode 100755 index 0000000..2c01434 --- /dev/null +++ b/libs/include/android/osgParticle/SmokeTrailEffect @@ -0,0 +1,56 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGPARTICLE_SMOKETRAILEFFECT +#define OSGPARTICLE_SMOKETRAILEFFECT + +#include +#include +#include + +namespace osgParticle +{ + + class OSGPARTICLE_EXPORT SmokeTrailEffect : public ParticleEffect + { + public: + + explicit SmokeTrailEffect(bool automaticSetup=true); + + SmokeTrailEffect(const osg::Vec3& position, float scale=1.0f, float intensity=1.0f); + + SmokeTrailEffect(const SmokeTrailEffect& copy, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY); + + META_Node(osgParticle,SmokeTrailEffect); + + virtual void setDefaults(); + + virtual void setUpEmitterAndProgram(); + + virtual Emitter* getEmitter() { return _emitter.get(); } + virtual const Emitter* getEmitter() const { return _emitter.get(); } + + virtual Program* getProgram() { return _program.get(); } + virtual const Program* getProgram() const { return _program.get(); } + + protected: + + virtual ~SmokeTrailEffect() {} + + osg::ref_ptr _emitter; + osg::ref_ptr _program; + + }; +} + +#endif diff --git a/libs/include/android/osgParticle/VariableRateCounter b/libs/include/android/osgParticle/VariableRateCounter new file mode 100755 index 0000000..6b97497 --- /dev/null +++ b/libs/include/android/osgParticle/VariableRateCounter @@ -0,0 +1,77 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +//osgParticle - Copyright (C) 2002 Marco Jez + +#ifndef OSGPARTICLE_VARIABLERATE_COUNTER +#define OSGPARTICLE_VARIABLERATE_COUNTER 1 + +#include +#include + +#include +#include + +namespace osgParticle +{ + + class VariableRateCounter: public Counter { + public: + inline VariableRateCounter(); + inline VariableRateCounter(const VariableRateCounter& copy, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY); + + virtual const char* libraryName() const { return "osgParticle"; } + virtual const char* className() const { return "VariableRateCounter"; } + virtual bool isSameKindAs(const osg::Object* obj) const { return dynamic_cast(obj) != 0; } + + inline const rangef& getRateRange() const; + inline void setRateRange(const rangef& r); + inline void setRateRange(float minrange, float maxrange); + + protected: + virtual ~VariableRateCounter() {} + + private: + rangef _rate_range; + }; + + // INLINE FUNCTIONS + + inline VariableRateCounter::VariableRateCounter() + : Counter(), _rate_range(1, 1) + { + } + + inline VariableRateCounter::VariableRateCounter(const VariableRateCounter& copy, const osg::CopyOp& copyop) + : Counter(copy, copyop), _rate_range(copy._rate_range) + { + } + + inline const rangef &VariableRateCounter::getRateRange() const + { + return _rate_range; + } + + inline void VariableRateCounter::setRateRange(const rangef& r) + { + _rate_range = r; + } + + inline void VariableRateCounter::setRateRange(float minrange, float maxrange) + { + _rate_range.set(minrange, maxrange); + } + +} + + +#endif diff --git a/libs/include/android/osgParticle/Version b/libs/include/android/osgParticle/Version new file mode 100755 index 0000000..0fdbd0e --- /dev/null +++ b/libs/include/android/osgParticle/Version @@ -0,0 +1,48 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +//osgParticle - Copyright (C) 2002 Marco Jez + +#ifndef OSGPARTICLE_VERSION +#define OSGPARTICLE_VERSION 1 + +#include + +extern "C" { + +/** + * osgParticleGetVersion() returns the library version number. + * Numbering convention : OpenSceneGraph-1.0 will return 1.0 from osgParticleGetVersion. + * + * This C function can be also used to check for the existence of the OpenSceneGraph + * library using autoconf and its m4 macro AC_CHECK_LIB. + * + * Here is the code to add to your configure.in: + \verbatim + # + # Check for the OpenSceneGraph Particle library + # + AC_CHECK_LIB(osg, osgParticleGetVersion, , + [AC_MSG_ERROR(OpenSceneGraph Particle library not found. See http://www.openscenegraph.org)],) + \endverbatim +*/ +OSGPARTICLE_EXPORT const char* osgParticleGetVersion(); + +/** + * osgParticleGetLibraryName() returns the library name in human friendly form. +*/ +OSGPARTICLE_EXPORT const char* osgParticleGetLibraryName(); + +} + +#endif + diff --git a/libs/include/android/osgParticle/range b/libs/include/android/osgParticle/range new file mode 100755 index 0000000..367b33e --- /dev/null +++ b/libs/include/android/osgParticle/range @@ -0,0 +1,89 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +//osgParticle - Copyright (C) 2002 Marco Jez + +#ifndef OSGPARTICLE_RANGE +#define OSGPARTICLE_RANGE 1 + +// include Export simply to disable Visual Studio silly warnings. +#include + +#include + +#include +#include +#include + +namespace osgParticle +{ + + /** + A simple struct template useful to store ranges of values as min/max pairs. + This struct template helps storing min/max ranges for values of any kind; class ValueType is + the type of values to be stored, and it must support operations ValueType + ValueType, ValueType - ValueType, + and ValueType * float, otherwise the geValueTyperandom() method will not compile. + This struct could be extended to customize the random number generator (now it uses only + std::rand()). + */ + template struct range + { + + /// Lower bound. + ValueType minimum; + + /// Higher bound. + ValueType maximum; + + /// Construct the object by calling default constructors for min and max. + range() : minimum(ValueType()), maximum(ValueType()) {} + + /// Construct and initialize min and max directly. + range(const ValueType& mn, const ValueType& mx) : minimum(mn), maximum(mx) {} + + /// Set min and max. + void set(const ValueType& mn, const ValueType& mx) { minimum = mn; maximum = mx; } + + /// Get a random value between min and max. + ValueType get_random() const + { + return minimum + (maximum - minimum) * rand() / RAND_MAX; + } + + /// Get a random square root value between min and max. + ValueType get_random_sqrtf() const + { + return minimum + (maximum - minimum) * sqrtf( static_cast(rand()) / static_cast(RAND_MAX) ); + } + + ValueType mid() const + { + return (minimum+maximum)*0.5f; + } + + }; + + /// Range of floats. + typedef range rangef; + + /// Range of osg::Vec2s. + typedef range rangev2; + + /// Range of osg::Vec3s. + typedef range rangev3; + + /// Range of osg::Vec4s. + typedef range rangev4; + +} + +#endif diff --git a/libs/include/android/osgPresentation/AnimationMaterial b/libs/include/android/osgPresentation/AnimationMaterial new file mode 100755 index 0000000..dbf0a72 --- /dev/null +++ b/libs/include/android/osgPresentation/AnimationMaterial @@ -0,0 +1,173 @@ +/* -*-c++-*- Present3D - Copyright (C) 1999-2006 Robert Osfield + * + * This software is open source and may be redistributed and/or modified under + * the terms of the GNU General Public License (GPL) version 2.0. + * The full license is in LICENSE.txt file included with this distribution,. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * include LICENSE.txt for more details. +*/ + +#ifndef OSG_ANIMATIONMATERIAL +#define OSG_ANIMATIONMATERIAL 1 + +#include +#include + +#include + +#include +#include +#include + +namespace osgPresentation { + +/** AnimationMaterial for specify the time varying transformation pathway to use when update camera and model objects. + * Subclassed from Transform::ComputeTransformCallback allows AnimationMaterial to + * be attached directly to Transform nodes to move subgraphs around the scene. +*/ +class OSGPRESENTATION_EXPORT AnimationMaterial : public virtual osg::Object +{ + public: + + AnimationMaterial():_loopMode(LOOP) {} + + AnimationMaterial(const AnimationMaterial& ap, const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY): + Object(ap,copyop), + _timeControlPointMap(ap._timeControlPointMap), + _loopMode(ap._loopMode) {} + + META_Object(osg,AnimationMaterial); + + + /** get the transformation matrix for a point in time.*/ + bool getMaterial(double time,osg::Material& material) const; + + void insert(double time,osg::Material* material); + + double getFirstTime() const { if (!_timeControlPointMap.empty()) return _timeControlPointMap.begin()->first; else return 0.0;} + double getLastTime() const { if (!_timeControlPointMap.empty()) return _timeControlPointMap.rbegin()->first; else return 0.0;} + double getPeriod() const { return getLastTime()-getFirstTime();} + + enum LoopMode + { + SWING, + LOOP, + NO_LOOPING + }; + + void setLoopMode(LoopMode lm) { _loopMode = lm; } + + LoopMode getLoopMode() const { return _loopMode; } + + + typedef std::map > TimeControlPointMap; + + TimeControlPointMap& getTimeControlPointMap() { return _timeControlPointMap; } + + const TimeControlPointMap& getTimeControlPointMap() const { return _timeControlPointMap; } + + /** read the anumation path from a flat ascii file stream.*/ + void read(std::istream& in); + + /** write the anumation path to a flat ascii file stream.*/ + void write(std::ostream& out) const; + + bool requiresBlending() const; + + protected: + + virtual ~AnimationMaterial() {} + + void interpolate(osg::Material& material, float r, const osg::Material& lhs,const osg::Material& rhs) const; + + TimeControlPointMap _timeControlPointMap; + LoopMode _loopMode; + +}; + + +class OSGPRESENTATION_EXPORT AnimationMaterialCallback : public osg::NodeCallback +{ + public: + + AnimationMaterialCallback(): + _timeOffset(0.0), + _timeMultiplier(1.0), + _firstTime(DBL_MAX), + _latestTime(0.0), + _pause(false), + _pauseTime(0.0) {} + + + AnimationMaterialCallback(const AnimationMaterialCallback& apc,const osg::CopyOp& copyop): + osg::NodeCallback(apc,copyop), + _animationMaterial(apc._animationMaterial), + _useInverseMatrix(apc._useInverseMatrix), + _timeOffset(apc._timeOffset), + _timeMultiplier(apc._timeMultiplier), + _firstTime(apc._firstTime), + _latestTime(apc._latestTime), + _pause(apc._pause), + _pauseTime(apc._pauseTime) {} + + + META_Object(osg,AnimationMaterialCallback); + + AnimationMaterialCallback(AnimationMaterial* ap,double timeOffset=0.0f,double timeMultiplier=1.0f): + _animationMaterial(ap), + _useInverseMatrix(false), + _timeOffset(timeOffset), + _timeMultiplier(timeMultiplier), + _firstTime(DBL_MAX), + _latestTime(0.0), + _pause(false), + _pauseTime(0.0) {} + + void setAnimationMaterial(AnimationMaterial* path) { _animationMaterial = path; } + + AnimationMaterial* getAnimationMaterial() { return _animationMaterial.get(); } + + const AnimationMaterial* getAnimationMaterial() const { return _animationMaterial.get(); } + + void setTimeOffset(double offset) { _timeOffset = offset; } + double getTimeOffset() const { return _timeOffset; } + + void setTimeMultiplier(double multiplier) { _timeMultiplier = multiplier; } + double getTimeMultiplier() const { return _timeMultiplier; } + + void reset(); + + void setPause(bool pause); + + /** get the animation time that is used to specify the position along the AnimationMaterial. + * Animation time is computed from the formula ((_latestTime-_firstTime)-_timeOffset)*_timeMultiplier.*/ + double getAnimationTime() const; + + /** implements the callback*/ + virtual void operator()(osg::Node* node, osg::NodeVisitor* nv); + + void update(osg::Node& node); + + public: + + osg::ref_ptr _animationMaterial; + bool _useInverseMatrix; + double _timeOffset; + double _timeMultiplier; + double _firstTime; + double _latestTime; + bool _pause; + double _pauseTime; + + protected: + + ~AnimationMaterialCallback(){} + +}; + +} + +#endif diff --git a/libs/include/android/osgPresentation/CompileSlideCallback b/libs/include/android/osgPresentation/CompileSlideCallback new file mode 100755 index 0000000..83c69c4 --- /dev/null +++ b/libs/include/android/osgPresentation/CompileSlideCallback @@ -0,0 +1,45 @@ +/* -*-c++-*- Present3D - Copyright (C) 1999-2006 Robert Osfield + * + * This software is open source and may be redistributed and/or modified under + * the terms of the GNU General Public License (GPL) version 2.0. + * The full license is in LICENSE.txt file included with this distribution,. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * include LICENSE.txt for more details. +*/ + +#ifndef OSG_COMPILESLIDECALLBACK +#define OSG_COMPILESLIDECALLBACK 1 + +#include +#include + +namespace osgPresentation { + +class OSGPRESENTATION_EXPORT CompileSlideCallback : public osg::Camera::DrawCallback +{ + public: + + CompileSlideCallback(): + _needCompile(false), + _frameNumber(0) {} + + virtual void operator()(const osg::Camera& camera) const; + + void needCompile(osg::Node* node) { _needCompile=true; _sceneToCompile = node; } + + protected: + + virtual ~CompileSlideCallback() {} + + mutable bool _needCompile; + mutable unsigned int _frameNumber; + osg::ref_ptr _sceneToCompile; + +}; + +} + +#endif diff --git a/libs/include/android/osgPresentation/Export b/libs/include/android/osgPresentation/Export new file mode 100755 index 0000000..9a9374f --- /dev/null +++ b/libs/include/android/osgPresentation/Export @@ -0,0 +1,49 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGPRESENTATION_EXPORT_ +#define OSGPRESENTATION_EXPORT_ 1 + +#include + +#if defined(_MSC_VER) && defined(OSG_DISABLE_MSVC_WARNINGS) + #pragma warning( disable : 4244 ) + #pragma warning( disable : 4251 ) + #pragma warning( disable : 4275 ) + #pragma warning( disable : 4786 ) + #pragma warning( disable : 4290 ) + #pragma warning( disable : 4305 ) + #pragma warning( disable : 4996 ) +#endif + +#if defined(_MSC_VER) || defined(__CYGWIN__) || defined(__MINGW32__) || defined( __BCPLUSPLUS__) || defined( __MWERKS__) + # if defined( OSG_LIBRARY_STATIC ) + # define OSGPRESENTATION_EXPORT + # elif defined( OSGPRESENTATION_LIBRARY ) + # define OSGPRESENTATION_EXPORT __declspec(dllexport) + # else + # define OSGPRESENTATION_EXPORT __declspec(dllimport) + # endif +#else + # define OSGPRESENTATION_EXPORT +#endif + + +/** + +\namespace osgPresentation + +The osgPresentation library is a NodeKit that extends the core scene graph to support 3D scene graph based presentations. +*/ + +#endif diff --git a/libs/include/android/osgPresentation/KeyEventHandler b/libs/include/android/osgPresentation/KeyEventHandler new file mode 100755 index 0000000..dc178af --- /dev/null +++ b/libs/include/android/osgPresentation/KeyEventHandler @@ -0,0 +1,68 @@ +/* -*-c++-*- Present3D - Copyright (C) 1999-2006 Robert Osfield + * + * This software is open source and may be redistributed and/or modified under + * the terms of the GNU General Public License (GPL) version 2.0. + * The full license is in LICENSE.txt file included with this distribution,. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * include LICENSE.txt for more details. +*/ + +#ifndef KEYEVENTHANDLER +#define KEYEVENTHANDLER 1 + +#include +#include + +#include + +#include + +namespace osgPresentation +{ + +class OSGPRESENTATION_EXPORT KeyEventHandler : public osgGA::GUIEventHandler +{ + public: + + KeyEventHandler(int key, osgPresentation::Operation operation, const JumpData& jumpData=JumpData()); + KeyEventHandler(int key, const std::string& str, osgPresentation::Operation operation, const JumpData& jumpData=JumpData()); + KeyEventHandler(int key, const osgPresentation::KeyPosition& keyPos, const JumpData& jumpData=JumpData()); + + void setKey(int key) { _key = key; } + int getKey() const { return _key; } + + void setOperation(osgPresentation::Operation operation) { _operation = operation; } + osgPresentation::Operation getOperation() const { return _operation; } + + void setCommand(const std::string& str) { _command = str; } + const std::string& getCommand() const { return _command; } + + void setKeyPosition(const osgPresentation::KeyPosition& keyPos) { _keyPos = keyPos; } + const osgPresentation::KeyPosition& getKeyPosition() const { return _keyPos; } + + void setJumpData(const JumpData& jumpData) { _jumpData = jumpData; } + const JumpData& getJumpData() const { return _jumpData; } + + virtual bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter& aa, osg::Object* object, osg::NodeVisitor* nv); + + virtual void accept(osgGA::GUIEventHandlerVisitor& v); + + virtual void getUsage(osg::ApplicationUsage& usage) const; + + void doOperation(); + + int _key; + + std::string _command; + osgPresentation::KeyPosition _keyPos; + osgPresentation::Operation _operation; + + JumpData _jumpData; +}; + +} + +#endif diff --git a/libs/include/android/osgPresentation/PickEventHandler b/libs/include/android/osgPresentation/PickEventHandler new file mode 100755 index 0000000..32031be --- /dev/null +++ b/libs/include/android/osgPresentation/PickEventHandler @@ -0,0 +1,65 @@ +/* -*-c++-*- Present3D - Copyright (C) 1999-2006 Robert Osfield + * + * This software is open source and may be redistributed and/or modified under + * the terms of the GNU General Public License (GPL) version 2.0. + * The full license is in LICENSE.txt file included with this distribution,. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * include LICENSE.txt for more details. +*/ + +#ifndef PICKEVENTHANDLER +#define PICKEVENTHANDLER 1 + +#include +#include + +#include + +#include + +namespace osgPresentation +{ + +class OSGPRESENTATION_EXPORT PickEventHandler : public osgGA::GUIEventHandler +{ + public: + + PickEventHandler(osgPresentation::Operation operation, const JumpData& jumpData=JumpData()); + PickEventHandler(const std::string& str, osgPresentation::Operation operation, const JumpData& jumpData=JumpData()); + PickEventHandler(const osgPresentation::KeyPosition& keyPos, const JumpData& jumpData=JumpData()); + + void setOperation(osgPresentation::Operation operation) { _operation = operation; } + osgPresentation::Operation getOperation() const { return _operation; } + + void setCommand(const std::string& str) { _command = str; } + const std::string& getCommand() const { return _command; } + + void setKeyPosition(const osgPresentation::KeyPosition& keyPos) { _keyPos = keyPos; } + const osgPresentation::KeyPosition& getKeyPosition() const { return _keyPos; } + + void setJumpData(const JumpData& jumpData) { _jumpData = jumpData; } + const JumpData& getJumpData() const { return _jumpData; } + + virtual bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter& aa, osg::Object* object, osg::NodeVisitor* nv); + + virtual void accept(osgGA::GUIEventHandlerVisitor& v); + + virtual void getUsage(osg::ApplicationUsage& usage) const; + + void doOperation(); + + std::string _command; + osgPresentation::KeyPosition _keyPos; + osgPresentation::Operation _operation; + + JumpData _jumpData; + std::set _drawablesOnPush; + +}; + +} + +#endif diff --git a/libs/include/android/osgPresentation/PropertyManager b/libs/include/android/osgPresentation/PropertyManager new file mode 100755 index 0000000..a0154fa --- /dev/null +++ b/libs/include/android/osgPresentation/PropertyManager @@ -0,0 +1,210 @@ +/* -*-c++-*- Present3D - Copyright (C) 1999-2006 Robert Osfield + * + * This software is open source and may be redistributed and/or modified under + * the terms of the GNU General Public License (GPL) version 2.0. + * The full license is in LICENSE.txt file included with this distribution,. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * include LICENSE.txt for more details. +*/ + +#ifndef PROPERTYMANAGER +#define PROPERTYMANAGER 1 + +#include +#include +#include +#include +#include + +#include + +#include + +namespace osgPresentation +{ + +class PropertyManager : protected osg::Object +{ +public: + + PropertyManager() {} + PropertyManager(const PropertyManager& pm, const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY): + osg::Object(pm,copyop) {} + + META_Object(osgPresentation, PropertyManager) + + /** Convinience method that casts the named UserObject to osg::TemplateValueObject and gets the value. + * To use this template method you need to include the osg/ValueObject header.*/ + template + bool getProperty(const std::string& name, T& value) const + { + OpenThreads::ScopedLock lock(_mutex); + return getUserValue(name, value); + } + + /** Convinience method that creates the osg::TemplateValueObject to store the + * specified value and adds it as a named UserObject. + * To use this template method you need to include the osg/ValueObject header. */ + template + void setProperty(const std::string& name, const T& value) + { + OpenThreads::ScopedLock lock(_mutex); + return setUserValue(name, value); + } + + int ref() const { return osg::Referenced::ref(); } + int unref() const { return osg::Referenced::unref(); } + +protected: + + mutable OpenThreads::Mutex _mutex; + +}; + +extern OSGPRESENTATION_EXPORT const osg::Object* getUserObject(const osg::NodePath& nodepath, const std::string& name); + +template +bool getUserValue(const osg::NodePath& nodepath, const std::string& name, T& value) +{ + typedef osg::TemplateValueObject UserValueObject; + const osg::Object* object = getUserObject(nodepath, name); + const UserValueObject* uvo = dynamic_cast(object); + + if (uvo) + { + value = uvo->getValue(); + return true; + } + else + { + return false; + } +} + +extern OSGPRESENTATION_EXPORT bool containsPropertyReference(const std::string& str); + +struct PropertyReader +{ + PropertyReader(const osg::NodePath& nodePath, const std::string& str): + _errorGenerated(false), + _nodePath(nodePath), + _sstream(str) {} + + template + bool read(T& value) + { + // skip white space. + while(!_sstream.fail() && _sstream.peek()==' ') _sstream.ignore(); + + // check to see if a &propertyName is used. + if (_sstream.peek()=='$') + { + std::string propertyName; + _sstream.ignore(1); + _sstream >> propertyName; + OSG_NOTICE<<"Reading propertyName="<> value; + OSG_NOTICE<<"Reading value="< + PropertyReader& operator>>( T& value ) { if (!read(value)) _errorGenerated=true; return *this; } + + bool ok() { return !_sstream.fail() && !_errorGenerated; } + bool fail() { return _sstream.fail() || _errorGenerated; } + + bool _errorGenerated; + osg::NodePath _nodePath; + std::istringstream _sstream; +}; + + +class OSGPRESENTATION_EXPORT PropertyAnimation : public osg::NodeCallback +{ +public: + PropertyAnimation(): + _firstTime(DBL_MAX), + _latestTime(0.0), + _pause(false), + _pauseTime(0.0) {} + + void setPropertyManager(PropertyManager* pm) { _pm = pm; } + PropertyManager* getPropertyManager() const { return _pm.get(); } + + typedef std::map > KeyFrameMap; + + KeyFrameMap& getKeyFrameMap() { return _keyFrameMap; } + const KeyFrameMap& getKeyFrameMap() const { return _keyFrameMap; } + + void addKeyFrame(double time, osg::UserDataContainer* udc) + { + _keyFrameMap[time] = udc; + } + + virtual void reset(); + + void setPause(bool pause); + bool getPause() const { return _pause; } + + double getAnimationTime() const; + + virtual void operator()(osg::Node* node, osg::NodeVisitor* nv); + + virtual void update(osg::Node& node); + + +protected: + + osg::ref_ptr _pm; + + void assign(osg::UserDataContainer* destination, osg::UserDataContainer* source); + void assign(osg::UserDataContainer* udc, osg::Object* obj); + + KeyFrameMap _keyFrameMap; + + double _firstTime; + double _latestTime; + bool _pause; + double _pauseTime; + +}; + + + +struct OSGPRESENTATION_EXPORT ImageSequenceUpdateCallback : public osg::NodeCallback +{ + ImageSequenceUpdateCallback(osg::ImageSequence* is, PropertyManager* pm, const std::string& propertyName): + _imageSequence(is), + _propertyManager(pm), + _propertyName(propertyName) {} + + virtual void operator()(osg::Node* node, osg::NodeVisitor* nv); + + osg::ref_ptr _imageSequence; + osg::ref_ptr _propertyManager; + std::string _propertyName; +}; + +struct OSGPRESENTATION_EXPORT PropertyEventCallback : public osgGA::GUIEventHandler +{ + PropertyEventCallback(PropertyManager* pm): + _propertyManager(pm) {} + + virtual bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter&); + + osg::ref_ptr _propertyManager; +}; + +} + +#endif diff --git a/libs/include/android/osgPresentation/SlideEventHandler b/libs/include/android/osgPresentation/SlideEventHandler new file mode 100755 index 0000000..c46bfee --- /dev/null +++ b/libs/include/android/osgPresentation/SlideEventHandler @@ -0,0 +1,386 @@ +/* -*-c++-*- Present3D - Copyright (C) 1999-2006 Robert Osfield + * + * This software is open source and may be redistributed and/or modified under + * the terms of the GNU General Public License (GPL) version 2.0. + * The full license is in LICENSE.txt file included with this distribution,. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * include LICENSE.txt for more details. +*/ + +#ifndef SLIDEEVENTHANDLER +#define SLIDEEVENTHANDLER 1 + +#include +#include +#include +#include + +#include +#include + +#include +#include + +namespace osgPresentation +{ + +// forward declare +class SlideEventHandler; + +/// Operations related to click to run/load/key events. +enum Operation +{ + RUN, + LOAD, + EVENT, + JUMP, + FORWARD_EVENT +}; + +struct JumpData +{ + JumpData(): + relativeJump(true), + slideNum(0), + layerNum(0) {} + + JumpData(bool in_relativeJump, int in_slideNum, int in_layerNum): + relativeJump(in_relativeJump), + slideNum(in_slideNum), + layerNum(in_layerNum) {} + + JumpData(const std::string& in_slideName, const std::string& in_layerName): + relativeJump(true), + slideNum(0), + layerNum(0), + slideName(in_slideName), + layerName(in_layerName) {} + + JumpData(const JumpData& rhs): + relativeJump(rhs.relativeJump), + slideNum(rhs.slideNum), + layerNum(rhs.layerNum), + slideName(rhs.slideName), + layerName(rhs.layerName) {} + + JumpData& operator = (const JumpData& rhs) + { + if (&rhs==this) return *this; + relativeJump = rhs.relativeJump; + slideNum = rhs.slideNum; + layerNum = rhs.layerNum; + slideName = rhs.slideName; + layerName = rhs.layerName; + return *this; + } + + bool requiresJump() const + { + if (!slideName.empty() || !layerName.empty()) return true; + return relativeJump ? (slideNum!=0 || layerNum!=0) : true; + } + + bool jump(SlideEventHandler* seh) const; + + bool relativeJump; + int slideNum; + int layerNum; + + std::string slideName; + std::string layerName; +}; + + +struct HomePosition : public virtual osg::Referenced +{ + HomePosition() {} + + HomePosition(const osg::Vec3& in_eye, const osg::Vec3& in_center, const osg::Vec3& in_up): + eye(in_eye), + center(in_center), + up(in_up) {} + + osg::Vec3 eye; + osg::Vec3 center; + osg::Vec3 up; +}; + +struct KeyPosition +{ + KeyPosition(unsigned int key=0, float x=FLT_MAX, float y=FLT_MAX): + _key((osgGA::GUIEventAdapter::KeySymbol)key), + _x(x), + _y(y) {} + + + void set(unsigned int key=0, float x=FLT_MAX, float y=FLT_MAX) + { + _key = (osgGA::GUIEventAdapter::KeySymbol)key; + _x = x; + _y = y; + } + + osgGA::GUIEventAdapter::KeySymbol _key; + float _x; + float _y; +}; + +struct LayerCallback : public virtual osg::Referenced +{ + virtual void operator() (osg::Node* node) const = 0; +}; + +struct OSGPRESENTATION_EXPORT LayerAttributes : public virtual osg::Referenced +{ + LayerAttributes():_duration(0) {} + LayerAttributes(double in_duration):_duration(in_duration) {} + + void setDuration(double duration) { _duration = duration; } + double getDuration() const { return _duration; } + + typedef std::vector Keys; + typedef std::vector RunStrings; + + void setKeys(const Keys& keys) { _keys = keys; } + const Keys& getKeys() const { return _keys; } + + void addKey(const KeyPosition& kp) { _keys.push_back(kp); } + + void setRunStrings(const RunStrings& runStrings) { _runStrings = runStrings; } + const RunStrings& getRunStrings() const { return _runStrings; } + + void addRunString(const std::string& runString) { _runStrings.push_back(runString); } + + void setJump(const JumpData& jumpData) { _jumpData = jumpData; } + const JumpData& getJumpData() const { return _jumpData; } + + double _duration; + Keys _keys; + RunStrings _runStrings; + JumpData _jumpData; + + void addEnterCallback(LayerCallback* lc) { _enterLayerCallbacks.push_back(lc); } + void addLeaveCallback(LayerCallback* lc) { _leaveLayerCallbacks.push_back(lc); } + + void callEnterCallbacks(osg::Node* node); + void callLeaveCallbacks(osg::Node* node); + + typedef std::list< osg::ref_ptr > LayerCallbacks; + LayerCallbacks _enterLayerCallbacks; + LayerCallbacks _leaveLayerCallbacks; +}; + +struct FilePathData : public virtual osg::Referenced +{ + FilePathData(const osgDB::FilePathList& fpl):filePathList(fpl) {} + + osgDB::FilePathList filePathList; +}; + + +struct dereference_less +{ + template + inline bool operator() (const T& lhs,const U& rhs) const + { + return *lhs < *rhs; + } +}; + +struct ObjectOperator : public osg::Referenced +{ + inline bool operator < (const ObjectOperator& rhs) const { return ptr() < rhs.ptr(); } + + virtual void* ptr() const = 0; + + virtual void enter(SlideEventHandler*) = 0; + virtual void frame(SlideEventHandler*) {} ; + virtual void maintain(SlideEventHandler*) = 0; + virtual void leave(SlideEventHandler*) = 0; + virtual void setPause(SlideEventHandler*, bool pause) = 0; + virtual void reset(SlideEventHandler*) = 0; + + virtual ~ObjectOperator() {} +}; + +class OSGPRESENTATION_EXPORT ActiveOperators +{ +public: + ActiveOperators(); + ~ActiveOperators(); + + void collect(osg::Node* incommingNode, osg::NodeVisitor::TraversalMode tm = osg::NodeVisitor::TRAVERSE_ACTIVE_CHILDREN); + + void process(SlideEventHandler* seh); + + void frame(SlideEventHandler*); + + void setPause(SlideEventHandler* seh, bool pause); + bool getPause() const { return _pause; } + + void reset(SlideEventHandler* seh); + + typedef std::set< osg::ref_ptr, dereference_less > OperatorList; + +protected: + + void processOutgoing(SlideEventHandler* seh); + void processIncomming(SlideEventHandler* seh); + void processMaintained(SlideEventHandler* seh); + + bool _pause; + + OperatorList _previous; + OperatorList _current; + + OperatorList _outgoing; + OperatorList _incomming; + OperatorList _maintained; + +}; + +class OSGPRESENTATION_EXPORT SlideEventHandler : public osgGA::GUIEventHandler +{ +public: + + SlideEventHandler(osgViewer::Viewer* viewer=0); + + static SlideEventHandler* instance(); + + META_Object(osgslideshowApp,SlideEventHandler); + + void set(osg::Node* model); + + virtual void accept(osgGA::GUIEventHandlerVisitor& v) { v.visit(*this); } + + /** Event traversal node callback method.*/ + virtual void operator()(osg::Node* node, osg::NodeVisitor* nv); + + virtual bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter&); + + virtual void getUsage(osg::ApplicationUsage& usage) const; + + osgViewer::Viewer* getViewer() { return _viewer.get(); } + + osg::Switch* getPresentationSwitch() { return _presentationSwitch.get(); } + + enum WhichPosition + { + FIRST_POSITION = 0, + LAST_POSITION = -1 + }; + + void compileSlide(unsigned int slideNum); + void releaseSlide(unsigned int slideNum); + + unsigned int getNumSlides(); + + int getActiveSlide() const { return _activeSlide; } + int getActiveLayer() const { return _activeLayer; } + + osg::Switch* getSlide(int slideNum); + osg::Node* getLayer(int slideNum, int layerNum); + + bool selectSlide(int slideNum,int layerNum=FIRST_POSITION); + bool selectLayer(int layerNum); + + bool nextLayerOrSlide(); + bool previousLayerOrSlide(); + + bool nextSlide(); + bool previousSlide(); + + bool nextLayer(); + bool previousLayer(); + + bool home(); + + void setAutoSteppingActive(bool flag = true) { _autoSteppingActive = flag; } + bool getAutoSteppingActive() const { return _autoSteppingActive; } + + void setTimeDelayBetweenSlides(double dt) { _timePerSlide = dt; } + double getTimeDelayBetweenSlides() const { return _timePerSlide; } + + double getDuration(const osg::Node* node) const; + + double getCurrentTimeDelayBetweenSlides() const; + + void setReleaseAndCompileOnEachNewSlide(bool flag) { _releaseAndCompileOnEachNewSlide = flag; } + bool getReleaseAndCompileOnEachNewSlide() const { return _releaseAndCompileOnEachNewSlide; } + + void setTimeDelayOnNewSlideWithMovies(float t) { _timeDelayOnNewSlideWithMovies = t; } + float getTimeDelayOnNewSlideWithMovies() const { return _timeDelayOnNewSlideWithMovies; } + + void setLoopPresentation(bool loop) { _loopPresentation = loop; } + bool getLoopPresentation() const { return _loopPresentation; } + + void dispatchEvent(const KeyPosition& keyPosition); + + void setRequestReload(bool flag); + bool getRequestReload() const { return _requestReload; } + + double getReferenceTime() const { return _referenceTime; } + +protected: + + ~SlideEventHandler() {} + SlideEventHandler(const SlideEventHandler&,const osg::CopyOp&) {} + + bool home(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter& aa); + + void updateAlpha(bool, bool, float x, float y); + void updateLight(float x, float y); + + void updateOperators(); + + + osg::observer_ptr _viewer; + + osg::observer_ptr _showSwitch; + int _activePresentation; + + osg::observer_ptr _presentationSwitch; + int _activeSlide; + + osg::observer_ptr _slideSwitch; + int _activeLayer; + + bool _firstTraversal; + double _referenceTime; + double _previousTime; + double _timePerSlide; + bool _autoSteppingActive; + bool _loopPresentation; + bool _pause; + bool _hold; + + bool _updateLightActive; + bool _updateOpacityActive; + float _previousX, _previousY; + + bool _cursorOn; + + bool _releaseAndCompileOnEachNewSlide; + + bool _firstSlideOrLayerChange; + osg::Timer_t _tickAtFirstSlideOrLayerChange; + osg::Timer_t _tickAtLastSlideOrLayerChange; + + float _timeDelayOnNewSlideWithMovies; + + double _minimumTimeBetweenKeyPresses; + double _timeLastKeyPresses; + + ActiveOperators _activeOperators; + + osg::ref_ptr _compileSlideCallback; + + bool _requestReload; +}; + +} + +#endif diff --git a/libs/include/android/osgPresentation/SlideShowConstructor b/libs/include/android/osgPresentation/SlideShowConstructor new file mode 100755 index 0000000..5c4a393 --- /dev/null +++ b/libs/include/android/osgPresentation/SlideShowConstructor @@ -0,0 +1,589 @@ +/* -*-c++-*- Present3D - Copyright (C) 1999-2006 Robert Osfield + * + * This software is open source and may be redistributed and/or modified under + * the terms of the GNU General Public License (GPL) version 2.0. + * The full license is in LICENSE.txt file included with this distribution,. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * include LICENSE.txt for more details. +*/ + +#ifndef SLIDESHOWCONSTRUCTOR +#define SLIDESHOWCONSTRUCTOR + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include + +#include +#include +#include +#include + +namespace osgPresentation +{ + + + +class OSGPRESENTATION_EXPORT HUDTransform : public osg::Transform +{ + public: + + HUDTransform(HUDSettings* hudSettings); + + virtual bool computeLocalToWorldMatrix(osg::Matrix& matrix,osg::NodeVisitor* nv) const; + + virtual bool computeWorldToLocalMatrix(osg::Matrix& matrix,osg::NodeVisitor*) const; + +protected: + + virtual ~HUDTransform(); + + osg::ref_ptr _hudSettings; + +}; + +class OSGPRESENTATION_EXPORT SlideShowConstructor +{ +public: + + + enum CoordinateFrame { SLIDE, MODEL }; + + + + LayerAttributes* getOrCreateLayerAttributes(osg::Node* node); + + void setDuration(osg::Node* node,double duration) + { + getOrCreateLayerAttributes(node)->setDuration(duration); + } + + void addKey(osg::Node* node,const KeyPosition& kp) + { + getOrCreateLayerAttributes(node)->addKey(kp); + } + + void addRunString(osg::Node* node, const std::string& runString) + { + getOrCreateLayerAttributes(node)->addRunString(runString); + } + + void setJump(osg::Node* node, const JumpData& jumpData) + { + getOrCreateLayerAttributes(node)->setJump(jumpData); + } + + void addPresentationKey(const KeyPosition& kp) + { + if (!_presentationSwitch) createPresentation(); + if (_presentationSwitch.valid()) addKey( _presentationSwitch.get(), kp); + } + + void addPresentationRunString(const std::string& runString) + { + if (!_presentationSwitch) createPresentation(); + if (_presentationSwitch.valid()) addRunString( _presentationSwitch.get(),runString); + } + + void addSlideKey(const KeyPosition& kp) + { + if (!_slide) addSlide(); + if (_slide.valid()) addKey(_slide.get(),kp); + } + + void addSlideRunString(const std::string& runString) + { + if (!_slide) addSlide(); + if (_slide.valid()) addRunString(_slide.get(),runString); + } + + void setSlideJump(const JumpData& jumpData) + { + if (!_slide) addSlide(); + if (_slide.valid()) setJump(_slide.get(),jumpData); + } + + void addLayerKey(const KeyPosition& kp) + { + if (!_currentLayer) addLayer(); + if (_currentLayer.valid()) addKey(_currentLayer.get(),kp); + } + + void addLayerRunString(const std::string& runString) + { + if (!_currentLayer) addLayer(); + if (_currentLayer.valid()) addRunString(_currentLayer.get(),runString); + } + + + void setLayerJump(const JumpData& jumpData) + { + if (!_currentLayer) addLayer(); + if (_currentLayer.valid()) setJump(_currentLayer.get(),jumpData); + } + + + + struct PositionData + { + PositionData(): + frame(SlideShowConstructor::SLIDE), + position(0.0f,1.0f,0.0f), + //position(0.5f,0.5f,0.0f), + scale(1.0f,1.0f,1.0f), + rotate(0.0f,0.0f,0.0f,1.0f), + rotation(0.0f,0.0f,1.0f,0.0f), + absolute_path(false), + inverse_path(false), + path_time_offset(0.0), + path_time_multiplier(1.0f), + path_loop_mode(osg::AnimationPath::NO_LOOPING), + animation_material_time_offset(0.0), + animation_material_time_multiplier(1.0), + animation_material_loop_mode(AnimationMaterial::NO_LOOPING), + autoRotate(false), + autoScale(false), + hud(false) {} + + + bool requiresPosition() const + { + return (position[0]!=0.0f || position[1]!=1.0f || position[2]!=1.0f); + } + + bool requiresScale() const + { + return (scale[0]!=1.0f || scale[1]!=1.0f || scale[2]!=1.0f); + } + + bool requiresRotate() const + { + return rotate[0]!=0.0f; + } + + bool requiresAnimation() const + { + return (rotation[0]!=0.0f || !path.empty()); + } + + bool requiresMaterialAnimation() const + { + return !animation_material_filename.empty() || !fade.empty(); + } + + CoordinateFrame frame; + osg::Vec3 position; + osg::Vec3 scale; + osg::Vec4 rotate; + osg::Vec4 rotation; + std::string animation_name; + bool absolute_path; + bool inverse_path; + double path_time_offset; + double path_time_multiplier; + osg::AnimationPath::LoopMode path_loop_mode; + std::string path; + double animation_material_time_offset; + double animation_material_time_multiplier; + AnimationMaterial::LoopMode animation_material_loop_mode; + std::string animation_material_filename; + std::string fade; + bool autoRotate; + bool autoScale; + bool hud; + }; + + struct ModelData + { + ModelData() {} + + std::string region; + std::string effect; + std::string options; + }; + + struct ImageData + { + ImageData(): + width(1.0f), + height(1.0f), + region(0.0f,0.0f,1.0f,1.0f), + region_in_pixel_coords(false), + texcoord_rotate(0.0f), + loopingMode(osg::ImageStream::NO_LOOPING), + page(-1), + backgroundColor(1.0f,1.0f,1.0f,1.0f), + fps(30.0), + duration(-1.0), + imageSequence(false), + imageSequencePagingMode(osg::ImageSequence::PAGE_AND_DISCARD_USED_IMAGES), + imageSequenceInteractionMode(PLAY_AUTOMATICALLY_LIKE_MOVIE), + blendingHint(USE_IMAGE_ALPHA), + delayTime(0.0), + startTime(0.0), + stopTime(-1.0), + volume("") + {} + + std::string options; + float width; + float height; + osg::Vec4 region; + bool region_in_pixel_coords; + float texcoord_rotate; + osg::ImageStream::LoopingMode loopingMode; + int page; + osg::Vec4 backgroundColor; + double fps; + double duration; + + bool imageSequence; + osg::ImageSequence::Mode imageSequencePagingMode; + + enum ImageSequenceInteractionMode + { + PLAY_AUTOMATICALLY_LIKE_MOVIE, + USE_MOUSE_X_POSITION, + USE_MOUSE_Y_POSITION + }; + ImageSequenceInteractionMode imageSequenceInteractionMode; + + enum BlendingHint + { + USE_IMAGE_ALPHA, + OFF, + ON + }; + + BlendingHint blendingHint; + + double delayTime; + double startTime; + double stopTime; + std::string volume; + + }; + + struct VolumeData + { + enum ShadingModel + { + Standard, + Light, + Isosurface, + MaximumIntensityProjection + }; + + VolumeData(): + shadingModel(Standard), + useTabbedDragger(false), + useTrackballDragger(false), + region_in_pixel_coords(false), + alphaValue("1.0"), + cutoffValue("0.1"), + sampleDensityValue("0.005"), + colorSpaceOperation(osg::NO_COLOR_SPACE_OPERATION), + colorModulate(1.0f,1.0f,1.0f,1.0f) + { + } + + std::string options; + ShadingModel shadingModel; + osg::ref_ptr transferFunction; + bool useTabbedDragger; + bool useTrackballDragger; + std::string region; + bool region_in_pixel_coords; + std::string alphaValue; + std::string cutoffValue; + std::string sampleDensityValue; + std::string sampleDensityWhenMovingValue; + + osg::ColorSpaceOperation colorSpaceOperation; + osg::Vec4 colorModulate; + }; + + + struct FontData + { + FontData(): + font("fonts/arial.ttf"), + layout(osgText::Text::LEFT_TO_RIGHT), + alignment(osgText::Text::LEFT_BASE_LINE), + axisAlignment(osgText::Text::XZ_PLANE), + characterSizeMode(osgText::Text::OBJECT_COORDS), + characterSize(0.04f), + maximumHeight(1.0f), + maximumWidth(1.0f), + color(1.0f,1.0f,1.0f,1.0f) {} + + std::string font; + osgText::Text::Layout layout; + osgText::Text::AlignmentType alignment; + osgText::Text::AxisAlignment axisAlignment; + osgText::Text::CharacterSizeMode characterSizeMode; + float characterSize; + float maximumHeight; + float maximumWidth; + osg::Vec4 color; + }; + + SlideShowConstructor(osgDB::Options* options); + + void createPresentation(); + + void setBackgroundColor(const osg::Vec4& color, bool updateClearNode); + const osg::Vec4& getBackgroundColor() const { return _backgroundColor; } + + void setTextColor(const osg::Vec4& color); + const osg::Vec4& getTextColor() const { return _textFontDataDefault.color; } + + void setPresentationName(const std::string& name); + + void setPresentationAspectRatio(float aspectRatio); + + void setPresentationAspectRatio(const std::string& str); + + void setPresentationDuration(double duration); + + + void addSlide(); + + void selectSlide(int slideNum); + + + void setSlideTitle(const std::string& name, PositionData& positionData, FontData& fontData) + { + _titlePositionData = positionData; + _titleFontData = fontData; + _slideTitle = name; + } + + void setSlideBackgrondHUD(bool hud) { _slideBackgroundAsHUD = hud; } + void setSlideBackground(const std::string& name) { _slideBackgroundImageFileName = name; } + + void setSlideDuration(double duration); + + Timeout* addTimeout(); + + void addLayer(bool inheritPreviousLayers=true, bool defineAsBaseLayer=false); + + void selectLayer(int layerNum); + + void setLayerDuration(double duration); + + + // title settings + FontData& getTitleFontData() { return _titleFontData; } + FontData& getTitleFontDataDefault() { return _titleFontDataDefault; } + + PositionData& getTitlePositionData() { return _titlePositionData; } + PositionData& getTitlePositionDataDefault() { return _titlePositionDataDefault; } + + // text settings + FontData& getTextFontData() { return _textFontData; } + FontData& getTextFontDataDefault() { return _textFontDataDefault; } + + PositionData& getTextPositionData() { return _textPositionData; } + PositionData& getTextPositionDataDefault() { return _textPositionDataDefault; } + + void translateTextCursor(const osg::Vec3& delta) { _textPositionData.position += delta; } + + // image settings + PositionData& getImagePositionData() { return _imagePositionData; } + PositionData& getImagePositionDataDefault() { return _imagePositionDataDefault; } + + // model settings + PositionData& getModelPositionData() { return _modelPositionData; } + PositionData& getModelPositionDataDefault() { return _modelPositionDataDefault; } + + + enum PresentationContext { + CURRENT_PRESENTATION, + CURRENT_SLIDE, + CURRENT_LAYER + }; + + void addEventHandler(PresentationContext presentationContext, osg::ref_ptr handler); + + void keyToDoOperation(PresentationContext presentationContext, int key, Operation operation, const JumpData& jumpData=JumpData()); + void keyToDoOperation(PresentationContext presentationContext, int key, const std::string& command, Operation operation, const JumpData& jumpData=JumpData()); + void keyEventOperation(PresentationContext presentationContext, int key, const KeyPosition& keyPos, const JumpData& jumpData=JumpData()); + + void layerClickToDoOperation(Operation operation, const JumpData& jumpData=JumpData()); + void layerClickToDoOperation(const std::string& command, Operation operation, const JumpData& jumpData=JumpData()); + void layerClickEventOperation(const KeyPosition& keyPos, const JumpData& jumpData=JumpData()); + + void addPropertyAnimation(PresentationContext presentationContext, PropertyAnimation* propertyAnimation); + + void addToCurrentLayer(osg::Node* subgraph); + + void addBullet(const std::string& bullet, PositionData& positionData, FontData& fontData); + + void addParagraph(const std::string& paragraph, PositionData& positionData, FontData& fontData); + + osg::Image* readImage(const std::string& filename, const ImageData& imageData); + + void addImage(const std::string& filename,const PositionData& positionData, const ImageData& imageData); + + void addStereoImagePair(const std::string& filenameLeft, const ImageData& imageDataLeft, const std::string& filenameRight,const ImageData& imageDataRight, const PositionData& positionData); + + void addGraph(const std::string& filename,const PositionData& positionData, const ImageData& imageData); + void addVNC(const std::string& filename,const PositionData& positionData, const ImageData& imageData, const std::string& password); + void addBrowser(const std::string& filename,const PositionData& positionData, const ImageData& imageData); + void addPDF(const std::string& filename,const PositionData& positionData, const ImageData& imageData); + osg::Image* addInteractiveImage(const std::string& filename,const PositionData& positionData, const ImageData& imageData); + + void addModel(osg::Node* subgraph, const PositionData& positionData, const ModelData& modelData); + + void addModel(const std::string& filename, const PositionData& positionData, const ModelData& modelData); + + void setUpVolumeScalarProperty(osgVolume::VolumeTile* tile, osgVolume::ScalarProperty* property, const std::string& source); + + void addVolume(const std::string& filename, const PositionData& positionData, const VolumeData& volumeData); + + osg::Group* takePresentation() { return _root.release(); } + + osg::Group* getPresentation() { return _root.get(); } + + osg::Switch* getPresentationSwitch() { return _presentationSwitch.get(); } + + osg::Switch* getCurrentSlide() { return _slide.get(); } + + void pushCurrentLayer(); + void popCurrentLayer(); + + osg::Group* getCurrentLayer() { return _currentLayer.get(); } + + void setLoopPresentation(bool loop) { _loopPresentation = loop; } + bool getLoopPresentation() const { return _loopPresentation; } + + void setAutoSteppingActive(bool flag = true) { _autoSteppingActive = flag; } + bool getAutoSteppingActive() const { return _autoSteppingActive; } + + void setHUDSettings(HUDSettings* hudSettings) { _hudSettings = hudSettings; } + HUDSettings* getHUDSettings() { return _hudSettings.get(); } + const HUDSettings* getHUDSettings() const { return _hudSettings.get(); } + + +protected: + + void findImageStreamsAndAddCallbacks(osg::Node* node); + + osg::Geometry* createTexturedQuadGeometry(const osg::Vec3& pos, const osg::Vec4& rotation, float width,float height, osg::Image* image, bool& usedTextureRectangle); + void setUpMovieVolume(osg::Node* subgraph, osg::ImageStream* imageStream, const ImageData& imageData); + + osg::Vec3 computePositionInModelCoords(const PositionData& positionData) const; + void updatePositionFromInModelCoords(const osg::Vec3& vertex, PositionData& positionData) const; + + osg::Vec3 convertSlideToModel(const osg::Vec3& position) const; + osg::Vec3 convertModelToSlide(const osg::Vec3& position) const; + + osg::AnimationPathCallback* getAnimationPathCallback(const PositionData& positionData); + + osg::Node* attachMaterialAnimation(osg::Node* model, const PositionData& positionData); + bool attachTexMat(osg::StateSet* stateset, const ImageData& imageData, float s, float t, bool textureRectangle); + + osg::StateSet* createTransformStateSet() + { + osg::StateSet* stateset = new osg::StateSet; + #if !defined(OSG_GLES2_AVAILABLE) + stateset->setMode(GL_NORMALIZE,osg::StateAttribute::ON); + #endif + return stateset; + } + + osg::Node* decorateSubgraphForPosition(osg::Node* node, PositionData& positionData); + + osg::ref_ptr _options; + + osg::Vec3 _slideOrigin; + osg::Vec3 _eyeOrigin; + double _slideWidth; + double _slideHeight; + double _slideDistance; + unsigned int _leftEyeMask; + unsigned int _rightEyeMask; + + osg::ref_ptr _hudSettings; + + // title settings + FontData _titleFontData; + FontData _titleFontDataDefault; + + PositionData _titlePositionData; + PositionData _titlePositionDataDefault; + + // text settings + FontData _textFontData; + FontData _textFontDataDefault; + + PositionData _textPositionData; + PositionData _textPositionDataDefault; + + // image settings + PositionData _imagePositionData; + PositionData _imagePositionDataDefault; + + // model settings + PositionData _modelPositionData; + PositionData _modelPositionDataDefault; + + + bool _loopPresentation; + bool _autoSteppingActive; + osg::Vec4 _backgroundColor; + std::string _presentationName; + double _presentationDuration; + + osg::ref_ptr _propertyManager; + osg::ref_ptr _propertyEventCallback; + + osg::ref_ptr _root; + osg::ref_ptr _presentationSwitch; + + osg::ref_ptr _slideClearNode; + osg::ref_ptr _slide; + std::string _slideTitle; + std::string _slideBackgroundImageFileName; + bool _slideBackgroundAsHUD; + + osg::ref_ptr _previousLayer; + osg::ref_ptr _currentLayer; + typedef std::vector< osg::ref_ptr > LayerStack; + LayerStack _layerStack; + + osg::ref_ptr _filePathData; + + osg::ref_ptr _layerToApplyEventCallbackTo; + + typedef std::list< osg::ref_ptr > EventHandlerList; + EventHandlerList _currentEventCallbacksToApply; + + + std::string findFileAndRecordPath(const std::string& filename); + + void recordOptionsFilePath(const osgDB::Options* options); + +}; + +} + +#endif diff --git a/libs/include/android/osgPresentation/Timeout b/libs/include/android/osgPresentation/Timeout new file mode 100755 index 0000000..8a9f376 --- /dev/null +++ b/libs/include/android/osgPresentation/Timeout @@ -0,0 +1,121 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGPRESENTATION_TIMOUTOUT +#define OSGPRESENTATION_TIMOUTOUT 1 + +#include + +#include + +namespace osgPresentation { + +class OSGPRESENTATION_EXPORT HUDSettings : public osg::Referenced +{ + public: + HUDSettings(double slideDistance, float eyeOffset, unsigned int leftMask, unsigned int rightMask); + + virtual bool getModelViewMatrix(osg::Matrix& matrix, osg::NodeVisitor* nv) const; + + virtual bool getInverseModelViewMatrix(osg::Matrix& matrix, osg::NodeVisitor* nv) const; + + double _slideDistance; + double _eyeOffset; + unsigned int _leftMask; + unsigned int _rightMask; + +protected: + + virtual ~HUDSettings(); +}; + +class OSGPRESENTATION_EXPORT Timeout : public osg::Transform +{ + public: + + Timeout(HUDSettings* hudSettings=0); + + /** Copy constructor using CopyOp to manage deep vs shallow copy.*/ + Timeout(const Timeout& timeout,const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY); + + META_Node(osgPresentation, Timeout); + + + void setIdleDurationBeforeTimeoutDisplay(double t) { _idleDurationBeforeTimeoutDisplay = t; } + double getIdleDurationBeforeTimeoutDisplay() const { return _idleDurationBeforeTimeoutDisplay; } + + void setIdleDurationBeforeTimeoutAction(double t) { _idleDurationBeforeTimeoutAction = t; } + double getIdleDurationBeforeTimeoutAction() const { return _idleDurationBeforeTimeoutAction; } + + + void setKeyStartsTimoutDisplay(int key) { _keyStartsTimoutDisplay = key; } + int getKeyStartsTimoutDisplay() const { return _keyStartsTimoutDisplay; } + + void setKeyDismissTimoutDisplay(int key) { _keyDismissTimoutDisplay = key; } + int getKeyDismissTimoutDisplay() const { return _keyDismissTimoutDisplay; } + + void setKeyRunTimoutAction(int key) { _keyRunTimeoutAction = key; } + int getKeyRunTimoutAction() const { return _keyRunTimeoutAction; } + + + void setDisplayBroadcastKeyPosition(const osgPresentation::KeyPosition& keyPos) { _displayBroadcastKeyPos = keyPos; } + const osgPresentation::KeyPosition& getDisplayBroadcastKeyPosition() const { return _displayBroadcastKeyPos; } + + void setDismissBroadcastKeyPosition(const osgPresentation::KeyPosition& keyPos) { _dismissBroadcastKeyPos = keyPos; } + const osgPresentation::KeyPosition& getDismissBroadcastKeyPosition() const { return _dismissBroadcastKeyPos; } + + void setActionKeyPosition(const osgPresentation::KeyPosition& keyPos) { _actionKeyPos = keyPos; } + const osgPresentation::KeyPosition& getActionKeyPosition() const { return _actionKeyPos; } + + void setActionBroadcastKeyPosition(const osgPresentation::KeyPosition& keyPos) { _actionBroadcastKeyPos = keyPos; } + const osgPresentation::KeyPosition& getActionBroadcastKeyPosition() const { return _actionBroadcastKeyPos; } + + void setActionJumpData(const JumpData& jumpData) { _actionJumpData = jumpData; } + const JumpData& getActionJumpData() const { return _actionJumpData; } + + virtual bool computeLocalToWorldMatrix(osg::Matrix& matrix,osg::NodeVisitor* nv) const; + + virtual bool computeWorldToLocalMatrix(osg::Matrix& matrix,osg::NodeVisitor*) const; + + virtual void traverse(osg::NodeVisitor& nv); + + protected: + + virtual ~Timeout(); + + void broadcastEvent(osgViewer::Viewer* viewer, const osgPresentation::KeyPosition& keyPos); + + osg::ref_ptr _hudSettings; + + int _previousFrameNumber; + double _timeOfLastEvent; + bool _displayTimeout; + + double _idleDurationBeforeTimeoutDisplay; + double _idleDurationBeforeTimeoutAction; + + int _keyStartsTimoutDisplay; + int _keyDismissTimoutDisplay; + int _keyRunTimeoutAction; + + osgPresentation::KeyPosition _displayBroadcastKeyPos; + osgPresentation::KeyPosition _dismissBroadcastKeyPos; + + osgPresentation::KeyPosition _actionKeyPos; + osgPresentation::KeyPosition _actionBroadcastKeyPos; + JumpData _actionJumpData; +}; + +} + +#endif \ No newline at end of file diff --git a/libs/include/android/osgQt/Export b/libs/include/android/osgQt/Export new file mode 100755 index 0000000..41efb3c --- /dev/null +++ b/libs/include/android/osgQt/Export @@ -0,0 +1,52 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +// The following symbol has a underscore suffix for compatibility. +#ifndef OSGQT_EXPORT_ +#define OSGQT_EXPORT_ 1 + +#include + +#if defined(_MSC_VER) && defined(OSG_DISABLE_MSVC_WARNINGS) + #pragma warning( disable : 4244 ) + #pragma warning( disable : 4251 ) + #pragma warning( disable : 4267 ) + #pragma warning( disable : 4275 ) + #pragma warning( disable : 4290 ) + #pragma warning( disable : 4786 ) + #pragma warning( disable : 4305 ) + #pragma warning( disable : 4996 ) +#endif + +#if defined(_MSC_VER) || defined(__CYGWIN__) || defined(__MINGW32__) || defined( __BCPLUSPLUS__) || defined( __MWERKS__) + # if defined( OSG_LIBRARY_STATIC ) + # define OSGQT_EXPORT + # elif defined( OSGQT_LIBRARY ) + # define OSGQT_EXPORT __declspec(dllexport) + # else + # define OSGQT_EXPORT __declspec(dllimport) + #endif +#else + #define OSGQT_EXPORT +#endif + +#endif + + +/** + +\namespace osgQt + +The osgQt utility library provides various classes to aid the integration of OpenSceneGraph and Qt. + +*/ diff --git a/libs/include/android/osgQt/GraphicsWindowQt b/libs/include/android/osgQt/GraphicsWindowQt new file mode 100755 index 0000000..49e4df5 --- /dev/null +++ b/libs/include/android/osgQt/GraphicsWindowQt @@ -0,0 +1,181 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 2009 Wang Rui + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGVIEWER_GRAPHICSWINDOWQT +#define OSGVIEWER_GRAPHICSWINDOWQT + +#include +#include + +#include +#include +#include +#include +#include + +class QInputEvent; + +namespace osgViewer { + class ViewerBase; +} + +namespace osgQt +{ + +// forward declarations +class GraphicsWindowQt; + +/// The function sets the WindowingSystem to Qt. +void OSGQT_EXPORT initQtWindowingSystem(); + +/** The function sets the viewer that will be used after entering + * the Qt main loop (QCoreApplication::exec()). + * + * The function also initializes internal structures required for proper + * scene rendering. + * + * The method must be called from main thread. */ +void OSGQT_EXPORT setViewer( osgViewer::ViewerBase *viewer ); + + +class OSGQT_EXPORT GLWidget : public QGLWidget +{ + typedef QGLWidget inherited; + +public: + + GLWidget( QWidget* parent = NULL, const QGLWidget* shareWidget = NULL, Qt::WindowFlags f = 0, bool forwardKeyEvents = false ); + GLWidget( QGLContext* context, QWidget* parent = NULL, const QGLWidget* shareWidget = NULL, Qt::WindowFlags f = 0, bool forwardKeyEvents = false ); + GLWidget( const QGLFormat& format, QWidget* parent = NULL, const QGLWidget* shareWidget = NULL, Qt::WindowFlags f = 0, bool forwardKeyEvents = false ); + virtual ~GLWidget(); + + inline void setGraphicsWindow( GraphicsWindowQt* gw ) { _gw = gw; } + inline GraphicsWindowQt* getGraphicsWindow() { return _gw; } + inline const GraphicsWindowQt* getGraphicsWindow() const { return _gw; } + + inline bool getForwardKeyEvents() const { return _forwardKeyEvents; } + virtual void setForwardKeyEvents( bool f ) { _forwardKeyEvents = f; } + + void setKeyboardModifiers( QInputEvent* event ); + + virtual void keyPressEvent( QKeyEvent* event ); + virtual void keyReleaseEvent( QKeyEvent* event ); + virtual void mousePressEvent( QMouseEvent* event ); + virtual void mouseReleaseEvent( QMouseEvent* event ); + virtual void mouseDoubleClickEvent( QMouseEvent* event ); + virtual void mouseMoveEvent( QMouseEvent* event ); + virtual void wheelEvent( QWheelEvent* event ); + +protected: + + int getNumDeferredEvents() + { + QMutexLocker lock(&_deferredEventQueueMutex); + return _deferredEventQueue.count(); + } + void enqueueDeferredEvent(QEvent::Type eventType, QEvent::Type removeEventType = QEvent::None) + { + QMutexLocker lock(&_deferredEventQueueMutex); + + if (removeEventType != QEvent::None) + { + if (_deferredEventQueue.removeOne(removeEventType)) + _eventCompressor.remove(eventType); + } + + if (_eventCompressor.find(eventType) == _eventCompressor.end()) + { + _deferredEventQueue.enqueue(eventType); + _eventCompressor.insert(eventType); + } + } + void processDeferredEvents(); + + friend class GraphicsWindowQt; + GraphicsWindowQt* _gw; + + QMutex _deferredEventQueueMutex; + QQueue _deferredEventQueue; + QSet _eventCompressor; + + bool _forwardKeyEvents; + + virtual void resizeEvent( QResizeEvent* event ); + virtual void moveEvent( QMoveEvent* event ); + virtual void glDraw(); + virtual bool event( QEvent* event ); +}; + +class OSGQT_EXPORT GraphicsWindowQt : public osgViewer::GraphicsWindow +{ +public: + GraphicsWindowQt( osg::GraphicsContext::Traits* traits, QWidget* parent = NULL, const QGLWidget* shareWidget = NULL, Qt::WindowFlags f = 0 ); + GraphicsWindowQt( GLWidget* widget ); + virtual ~GraphicsWindowQt(); + + inline GLWidget* getGLWidget() { return _widget; } + inline const GLWidget* getGLWidget() const { return _widget; } + + /// deprecated + inline GLWidget* getGraphWidget() { return _widget; } + /// deprecated + inline const GLWidget* getGraphWidget() const { return _widget; } + + struct WindowData : public osg::Referenced + { + WindowData( GLWidget* widget = NULL, QWidget* parent = NULL ): _widget(widget), _parent(parent) {} + GLWidget* _widget; + QWidget* _parent; + }; + + bool init( QWidget* parent, const QGLWidget* shareWidget, Qt::WindowFlags f ); + + static QGLFormat traits2qglFormat( const osg::GraphicsContext::Traits* traits ); + static void qglFormat2traits( const QGLFormat& format, osg::GraphicsContext::Traits* traits ); + static osg::GraphicsContext::Traits* createTraits( const QGLWidget* widget ); + + virtual bool setWindowRectangleImplementation( int x, int y, int width, int height ); + virtual void getWindowRectangle( int& x, int& y, int& width, int& height ); + virtual bool setWindowDecorationImplementation( bool windowDecoration ); + virtual bool getWindowDecoration() const; + virtual void grabFocus(); + virtual void grabFocusIfPointerInWindow(); + virtual void raiseWindow(); + virtual void setWindowName( const std::string& name ); + virtual std::string getWindowName(); + virtual void useCursor( bool cursorOn ); + virtual void setCursor( MouseCursor cursor ); + + virtual bool valid() const; + virtual bool realizeImplementation(); + virtual bool isRealizedImplementation() const; + virtual void closeImplementation(); + virtual bool makeCurrentImplementation(); + virtual bool releaseContextImplementation(); + virtual void swapBuffersImplementation(); + virtual void runOperations(); + + virtual void requestWarpPointer( float x, float y ); + +protected: + + friend class GLWidget; + GLWidget* _widget; + bool _ownsWidget; + QCursor _currentCursor; + bool _realized; +}; + +} + +#endif diff --git a/libs/include/android/osgQt/QFontImplementation b/libs/include/android/osgQt/QFontImplementation new file mode 100755 index 0000000..4bc45dc --- /dev/null +++ b/libs/include/android/osgQt/QFontImplementation @@ -0,0 +1,51 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 2009-2010 Mathias Froehlich + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ +#ifndef QFontImplementation_H +#define QFontImplementation_H + +#include +#include + +#include + +#include + +namespace osgQt { + +class OSGQT_EXPORT QFontImplementation : public osgText::Font::FontImplementation +{ +public: + QFontImplementation(const QFont& font); + virtual ~QFontImplementation(); + + virtual std::string getFileName() const; + + virtual bool supportsMultipleFontResolutions() const { return true; } + + virtual osgText::Glyph* getGlyph(const osgText::FontResolution& fontRes, unsigned int charcode); + + virtual osgText::Glyph3D* getGlyph3D(unsigned int /*charcode*/) { return 0; } + + virtual osg::Vec2 getKerning(unsigned int leftcharcode, unsigned int rightcharcode, osgText::KerningType kerningType); + + virtual bool hasVertical() const; + +protected: + + std::string _filename; + QFont _font; +}; + +} + +#endif diff --git a/libs/include/android/osgQt/QGraphicsViewAdapter b/libs/include/android/osgQt/QGraphicsViewAdapter new file mode 100755 index 0000000..0458a00 --- /dev/null +++ b/libs/include/android/osgQt/QGraphicsViewAdapter @@ -0,0 +1,112 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2009 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef QGRAPHICSVIEWADAPTER +#define QGRAPHICSVIEWADAPTER + +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace osgQt +{ + +extern OSGQT_EXPORT QCoreApplication* getOrCreateQApplication(); + +class OSGQT_EXPORT QGraphicsViewAdapter : public QObject +{ + Q_OBJECT + + public: + + QGraphicsViewAdapter(osg::Image* image, QWidget* widget); + + void setUpKeyMap(); + + bool sendPointerEvent(int x, int y, int buttonMask); + + + bool sendKeyEvent(int key, bool keyDown); + + + void setFrameLastRendered(const osg::FrameStamp* frameStamp); + + void clearWriteBuffer(); + + void render(); + + void assignImage(unsigned int i); + + void resize(int width, int height); + + void setBackgroundColor(QColor color) { _backgroundColor = color; } + QColor getBackgroundColor() const { return _backgroundColor; } + + QGraphicsView* getQGraphicsView() { return _graphicsView; } + QGraphicsScene* getQGraphicsScene() { return _graphicsScene; } + + protected: + + bool handlePointerEvent(int x, int y, int buttonMask); + bool handleKeyEvent(int key, bool keyDown); + QWidget* getWidgetAt(const QPoint& pos); + + osg::observer_ptr _image; + + int _previousButtonMask; + int _previousMouseX; + int _previousMouseY; + int _previousQtMouseX; + int _previousQtMouseY; + bool _previousSentEvent; + + int _width; + int _height; + + typedef std::map KeyMap; + KeyMap _keyMap; + Qt::KeyboardModifiers _qtKeyModifiers; + + QColor _backgroundColor; + QPointer _graphicsView; + QPointer _graphicsScene; + QPointer _widget; + + OpenThreads::Mutex _qimagesMutex; + OpenThreads::Mutex _qresizeMutex; + unsigned int _previousFrameNumber; + bool _newImageAvailable; + unsigned int _currentRead; + unsigned int _currentWrite; + unsigned int _previousWrite; + QImage _qimages[3]; + + virtual void customEvent ( QEvent * event ) ; + + private slots: + + void repaintRequestedSlot(const QList ®ions); + void repaintRequestedSlot(const QRectF ®ion); + +}; + +} + +#endif diff --git a/libs/include/android/osgQt/QWebViewImage b/libs/include/android/osgQt/QWebViewImage new file mode 100755 index 0000000..be16446 --- /dev/null +++ b/libs/include/android/osgQt/QWebViewImage @@ -0,0 +1,105 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2009 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef QWEBVIEWIMAGE +#define QWEBVIEWIMAGE + +// make sure this header isn't built as par of osgQt, leaving it to applications to build +#if !defined(OSGQT_LIBRARY) && !defined(OSG_LIBRARY_STATIC) + +#if QT_VERSION >= 0x050000 +# include +#else +# include +#endif + + +#include +#include + +namespace osgQt +{ + +class QWebViewImage : public osgWidget::BrowserImage +{ + public: + + QWebViewImage() + { + // make sure we have a valid QApplication before we start creating widgets. + getOrCreateQApplication(); + + _webView = new QWebView; + + _webPage = new QWebPage; + _webPage->settings()->setAttribute(QWebSettings::JavascriptEnabled, true); + _webPage->settings()->setAttribute(QWebSettings::PluginsEnabled, true); + + _webView->setPage(_webPage); + + _adapter = new QGraphicsViewAdapter(this, _webView.data()); + } + + virtual void navigateTo(const std::string& url) + { + _webView->load(QUrl(url.c_str())); + } + + QWebView* getQWebView() { return _webView; } + QWebPage* getQWebPage() { return _webPage; } + QGraphicsViewAdapter* getQGraphicsViewAdapter() { return _adapter; } + + void clearWriteBuffer() + { + _adapter->clearWriteBuffer(); + } + + void render() + { + _adapter->render(); + } + + virtual bool sendFocusHint(bool focus) + { + QFocusEvent event(focus ? QEvent::FocusIn : QEvent::FocusOut, Qt::OtherFocusReason); + QCoreApplication::sendEvent(_webPage, &event); + return true; + } + + virtual bool sendPointerEvent(int x, int y, int buttonMask) + { + return _adapter->sendPointerEvent(x,y,buttonMask); + } + + virtual bool sendKeyEvent(int key, bool keyDown) + { + return QWebViewImage::_adapter->sendKeyEvent(key, keyDown); + } + + virtual void setFrameLastRendered(const osg::FrameStamp* frameStamp) + { + _adapter->setFrameLastRendered(frameStamp); + } + + protected: + + QPointer _adapter; + QPointer _webView; + QPointer _webPage; +}; + +} + +#endif + +#endif diff --git a/libs/include/android/osgQt/QWidgetImage b/libs/include/android/osgQt/QWidgetImage new file mode 100755 index 0000000..c98f390 --- /dev/null +++ b/libs/include/android/osgQt/QWidgetImage @@ -0,0 +1,57 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2009 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef QWIDGETIMAGE +#define QWIDGETIMAGE + +#include +#include + +namespace osgQt +{ + +class OSGQT_EXPORT QWidgetImage : public osg::Image +{ + public: + + QWidgetImage( QWidget* widget=0 ); + + QWidget* getQWidget() { return _widget; } + QGraphicsViewAdapter* getQGraphicsViewAdapter() { return _adapter; } + + + void clearWriteBuffer(); + + void render(); + + /// Overridden scaleImage used to catch cases where the image is + /// fullscreen and the window is resized. + virtual void scaleImage(int s,int t,int r, GLenum newDataType); + + virtual bool sendFocusHint(bool focus); + + virtual bool sendPointerEvent(int x, int y, int buttonMask); + + virtual bool sendKeyEvent(int key, bool keyDown); + + virtual void setFrameLastRendered(const osg::FrameStamp* frameStamp); + + protected: + + QPointer _adapter; + QPointer _widget; +}; + +} + +#endif diff --git a/libs/include/android/osgShadow/ConvexPolyhedron b/libs/include/android/osgShadow/ConvexPolyhedron new file mode 100755 index 0000000..73fa181 --- /dev/null +++ b/libs/include/android/osgShadow/ConvexPolyhedron @@ -0,0 +1,123 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. + * + * ViewDependentShadow codes Copyright (C) 2008 Wojciech Lewandowski + * Thanks to to my company http://www.ai.com.pl for allowing me free this work. +*/ + +#ifndef OSGSHADOW_CONVEXPOLYHEDRON +#define OSGSHADOW_CONVEXPOLYHEDRON 1 + +#include +#include +#include + +//////////////////////////////////////////////////////////////////////////////// +// Class based on CustomPolytope defined and used in osgSim::OverlayNode.cpp. +// Honors should go to Robert Osfield for writing such useful piece of code. +// First incarnations of my ConvexPolyhedron were derived from CustomPolytope. +// Later I made a number of modifications aimed at improving convex hull +// precision of intersection & extrusion operations and ended up with code +// so mixed that I decided to rewrite it as separate class. +//////////////////////////////////////////////////////////////////////////////// + +namespace osgShadow { + +class OSGSHADOW_EXPORT ConvexPolyhedron +{ + public: + typedef std::vector Vertices; + + static const osg::Matrix & defaultMatrix; + + struct Face + { + std::string name; + osg::Plane plane; + Vertices vertices; + }; + + typedef std::list Faces; + Faces _faces; + + ConvexPolyhedron( void ) { } + + ConvexPolyhedron( const osg::Matrix& matrix, const osg::Matrix& inverse, + const osg::BoundingBox& bb = osg::BoundingBox(-1,-1,-1,1,1,1)); + + Face& createFace() { _faces.push_back(Face()); return _faces.back(); } + void clear() { _faces.clear(); } + + + void setToUnitFrustum(bool withNear=true, bool withFar=true); + void setToBoundingBox(const osg::BoundingBox& bb); + void transform(const osg::Matrix& matrix, const osg::Matrix& inverse); + void transformClip(const osg::Matrix& matrix, const osg::Matrix& inverse); + + + bool mergeFaces + ( const Face & face0, const Face & face1, Face & face ); + + void mergeCoplanarFaces( const double & plane_normal_dot_tolerance = 0.0, + const double & plane_distance_tolerance = 0.0 ); + + void removeDuplicateVertices( void ); + + + static int pointsColinear + ( const osg::Vec3d & va, const osg::Vec3d & vb, const osg::Vec3d & vc, + const double & edge_normal_dot_tolerance = 0.0, + const double & null_edge_length_tolerance = 0.0 ); + + static int isFacePolygonConvex( Face & face, bool ignoreCollinearVertices = true ); + + bool checkCoherency + ( bool checkForNonConvexPolys = false, const char * errorPrefix = NULL ); + + + void cut(const osg::Polytope& polytope); + + void cut(const ConvexPolyhedron& polytope); + + void cut(const osg::Plane& plane, const std::string& name=std::string()); + + void extrude( const osg::Vec3d & offset ); + + void translate( const osg::Vec3d & offset ); + + + void getPolytope(osg::Polytope& polytope) const; + void getPoints(Vertices& vertices) const; + osg::BoundingBox computeBoundingBox( const osg::Matrix & m = osgShadow::ConvexPolyhedron::defaultMatrix ) const; + + osg::Geometry* buildGeometry( const osg::Vec4d& colorOutline, + const osg::Vec4d& colorInside, + osg::Geometry* useGeometry = NULL ) const; + + + bool dumpGeometry( const Face * face = NULL, + const osg::Plane * plane = NULL, + ConvexPolyhedron * basehull = NULL, + const char * filename = "convexpolyhedron.osg", + const osg::Vec4d& colorOutline = osg::Vec4( 0,1,0,0.5 ), + const osg::Vec4d& colorInside = osg::Vec4( 0,1,0,0.25 ), + const osg::Vec4d& faceColorOutline = osg::Vec4( 0,0,1,0.5 ), + const osg::Vec4d& faceColorInside = osg::Vec4( 0,0,1,0.25 ), + const osg::Vec4d& planeColorOutline = osg::Vec4( 1,0,0,0.5 ), + const osg::Vec4d& planeColorInside = osg::Vec4( 1,0,0,0.25 ), + const osg::Vec4d& baseColorOutline = osg::Vec4( 0,0,0,0.5 ), + const osg::Vec4d& baseColorInside = osg::Vec4( 0,0,0,0.25 ) ) const; +}; + +} // namespace osgShadow + +#endif diff --git a/libs/include/android/osgShadow/DebugShadowMap b/libs/include/android/osgShadow/DebugShadowMap new file mode 100755 index 0000000..8f4dc15 --- /dev/null +++ b/libs/include/android/osgShadow/DebugShadowMap @@ -0,0 +1,192 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. + * + * ViewDependentShadow codes Copyright (C) 2008 Wojciech Lewandowski + * Thanks to to my company http://www.ai.com.pl for allowing me free this work. +*/ + +#ifndef OSGSHADOW_DEBUGSHADOWMAP +#define OSGSHADOW_DEBUGSHADOWMAP 1 + +#include +#include +#include +#include +#include +#include +#include + +namespace osgShadow { + +/** +Class used as a layer for debuging resources used by derived xxxShadowMap classes. +As designed by its base ViewDepndentShadowTechnique, DebugShadowMap serves mainly as container of +DebugShadowMap::ViewData objects. Most of the debuging support work is done by these objects. +DebugShadowMap technique only initializes them in initViewDependentData method. + +Debuging outputs present: + Shadow maps (pseudo colored to improve readability) + Shadow and related volumes (represented as convex polyhedra) +*/ + +class OSGSHADOW_EXPORT DebugShadowMap : public ViewDependentShadowTechnique +{ + public : + + /* + All classes stemming from ViewDependentShadowTechnique follow the same pattern. + + They are always based on some underlying level base Technique and they always + derive their ViewData from ViewData structure defined in underlying base Technique. + + I use some typedefs to make these inheritance patterns easier to declare/define. + */ + + /** Convenient typedef used in definition of ViewData struct and methods */ + typedef DebugShadowMap ThisClass; + /** Convenient typedef used in definition of ViewData struct and methods */ + typedef ViewDependentShadowTechnique BaseClass; + + /** Classic OSG constructor */ + DebugShadowMap(); + + /** Classic OSG cloning constructor */ + DebugShadowMap(const DebugShadowMap& dsm, const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY); + + /** Declaration of standard OSG object methods */ + META_Object( osgShadow, DebugShadowMap ); + + /** Turn on/off debuging hud & rendering of debug volumes in main view */ + void setDebugDraw( bool draw ) { _doDebugDraw = draw; } + + /** Tell if debuging hud & rendering of debug volumes is active */ + bool getDebugDraw( void ) const { return _doDebugDraw; } + + /** Get the file name of debuging dump */ + std::string getDebugDump( void ) const { return _debugDump; } + + /** Set the file name of debuging dump */ + void setDebugDump( const std::string & debugDumpFile ) { _debugDump = debugDumpFile; } + + protected: + /** Classic protected OSG destructor */ + virtual ~DebugShadowMap(); + + // forward declare, interface and implementation provided in DebugShadowMap.cpp + class DrawableDrawWithDepthShadowComparisonOffCallback; + + osg::Vec2s _hudSize; + osg::Vec2s _hudOrigin; + osg::Vec2s _viewportSize; + osg::Vec2s _viewportOrigin; + osg::Vec2s _orthoSize; + osg::Vec2s _orthoOrigin; + + bool _doDebugDraw; + std::string _debugDump; + + osg::ref_ptr< osg::Shader > _depthColorFragmentShader; + + struct OSGSHADOW_EXPORT ViewData: public BaseClass::ViewData + { + /** + Texture used as ShadowMap - initialized by derived classes. + But it has to be defined now since DebugShadowMap::ViewData methods use it + */ + osg::ref_ptr< osg::Texture > _texture; + /** + Camera used to render ShadowMap - initialized by derived classes. + But it has to be defined now since DebugShadowMap::ViewData methods use it + */ + osg::ref_ptr< osg::Camera > _camera; + + osg::Matrixd _viewProjection; + osg::observer_ptr _viewCamera; + + // Debug hud variables + + /** Coloring Shader used to present shadow depth map contents */ + osg::ref_ptr< osg::Shader > _depthColorFragmentShader; + + struct PolytopeGeometry { + + ConvexPolyhedron _polytope; + osg::ref_ptr< osg::Geometry > _geometry[2]; + osg::Vec4 _colorOutline; + osg::Vec4 _colorInside; + }; + + typedef std::map< std::string, PolytopeGeometry > PolytopeGeometryMap; + + osg::Vec2s _hudSize; + osg::Vec2s _hudOrigin; + osg::Vec2s _viewportSize; + osg::Vec2s _viewportOrigin; + osg::Vec2s _orthoSize; + osg::Vec2s _orthoOrigin; + + bool *_doDebugDrawPtr; + std::string *_debugDumpPtr; + + PolytopeGeometryMap _polytopeGeometryMap; + osg::ref_ptr< osg::Geode > _geode[2]; + osg::ref_ptr< osg::MatrixTransform > _transform[2]; + + std::map< std::string, osg::Matrix > _matrixMap; + std::map< std::string, osg::Polytope > _polytopeMap; + std::map< std::string, osg::BoundingBox > _boundingBoxMap; + + osg::ref_ptr _cameraDebugHUD; + + bool getDebugDraw() { return *_doDebugDrawPtr; } + std::string * getDebugDump() { return _debugDumpPtr; } + + virtual void init( ThisClass * st, osgUtil::CullVisitor * cv ); + + virtual void cull( ); + + virtual void createDebugHUD( void ); + + virtual void cullDebugGeometry( ); + + virtual void updateDebugGeometry( const osg::Camera * screenCam, + const osg::Camera * shadowCam ); + + void setDebugPolytope( const char * name, + const ConvexPolyhedron & polytope = *(ConvexPolyhedron*)( NULL ), + osg::Vec4 colorOutline = osg::Vec4(0,0,0,0), + osg::Vec4 colorInside = osg::Vec4(0,0,0,0) ); + + bool DebugBoundingBox( const osg::BoundingBox & bb, const char * name = "" ); + bool DebugPolytope( const osg::Polytope & p, const char * name = "" ); + bool DebugMatrix( const osg::Matrix & m, const char * name = "" ); + + static osg::Vec3d computeShadowTexelToPixelError + ( const osg::Matrix & mvpwView, + const osg::Matrix & mvpwShadow, + const osg::Vec3d & vWorld, + const osg::Vec3d & vDelta = osg::Vec3d( 0.01,0.01,0.01 ) ); + + static void displayShadowTexelToPixelErrors + ( const osg::Camera * viewCam, + const osg::Camera * shadowCam, + const ConvexPolyhedron * hull ); + + void dump( const std::string & filename ); + }; + + META_ViewDependentShadowTechniqueData( ThisClass, ViewData ) +}; + +} // namespace osgShadow + +#endif diff --git a/libs/include/android/osgShadow/Export b/libs/include/android/osgShadow/Export new file mode 100755 index 0000000..6aeb7e0 --- /dev/null +++ b/libs/include/android/osgShadow/Export @@ -0,0 +1,49 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGSHADOW_EXPORT_ +#define OSGSHADOW_EXPORT_ 1 + +#include + +#if defined(_MSC_VER) && defined(OSG_DISABLE_MSVC_WARNINGS) + #pragma warning( disable : 4244 ) + #pragma warning( disable : 4251 ) + #pragma warning( disable : 4267 ) + #pragma warning( disable : 4275 ) + #pragma warning( disable : 4290 ) + #pragma warning( disable : 4786 ) + #pragma warning( disable : 4305 ) + #pragma warning( disable : 4996 ) +#endif + +#if defined(_MSC_VER) || defined(__CYGWIN__) || defined(__MINGW32__) || defined( __BCPLUSPLUS__) + # if defined( OSG_LIBRARY_STATIC ) + # define OSGSHADOW_EXPORT + # elif defined( OSGSHADOW_LIBRARY ) + # define OSGSHADOW_EXPORT __declspec(dllexport) + # else + # define OSGSHADOW_EXPORT __declspec(dllimport) + # endif +#else + # define OSGSHADOW_EXPORT +#endif + +/** + +\namespace osgShadow + +The osgShadow library is a NodeKit that extends the core scene graph to add support for a range of shadow techniques. +*/ + +#endif diff --git a/libs/include/android/osgShadow/LightSpacePerspectiveShadowMap b/libs/include/android/osgShadow/LightSpacePerspectiveShadowMap new file mode 100755 index 0000000..405da73 --- /dev/null +++ b/libs/include/android/osgShadow/LightSpacePerspectiveShadowMap @@ -0,0 +1,122 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. + * + * ViewDependentShadow codes Copyright (C) 2008 Wojciech Lewandowski + * Thanks to to my company http://www.ai.com.pl for allowing me free this work. +*/ + + +#ifndef OSGSHADOW_LIGHTSPACEPERSPECTIVESHADOWMAP +#define OSGSHADOW_LIGHTSPACEPERSPECTIVESHADOWMAP 1 + +#include +#include +#include + +namespace osgShadow { + +// Class implements +// "Light Space Perspective Shadow Maps" algorithm by +// Michael Wimmer, Daniel Scherzer, Werner Purgathofer +// http://www.cg.tuwien.ac.at/research/vr/lispsm/ + +class LispSM; + +class OSGSHADOW_EXPORT LightSpacePerspectiveShadowMapAlgorithm +{ + public: + LightSpacePerspectiveShadowMapAlgorithm(); + ~LightSpacePerspectiveShadowMapAlgorithm(); + + void operator() ( + const osgShadow::ConvexPolyhedron* hullShadowedView, + const osg::Camera* cameraMain, + osg::Camera* cameraShadow ) const; + + protected: + LispSM * lispsm; +}; + +// Optimized for draw traversal shadow bounds +class OSGSHADOW_EXPORT LightSpacePerspectiveShadowMapDB: public ProjectionShadowMap< MinimalDrawBoundsShadowMap, LightSpacePerspectiveShadowMapAlgorithm > +{ + public: + /** Convenient typedef used in definition of ViewData struct and methods */ + typedef ProjectionShadowMap< MinimalDrawBoundsShadowMap, LightSpacePerspectiveShadowMapAlgorithm > BaseClass; + + /** Classic OSG constructor */ + LightSpacePerspectiveShadowMapDB() + { + } + + /** Classic OSG cloning constructor */ + LightSpacePerspectiveShadowMapDB( + const LightSpacePerspectiveShadowMapDB& copy, + const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY) : BaseClass(copy,copyop) + { + } + + /** Declaration of standard OSG object methods */ + META_Object( osgShadow, LightSpacePerspectiveShadowMapDB ); +}; + +// Optimized for cull traversal shadow bounds +class OSGSHADOW_EXPORT LightSpacePerspectiveShadowMapCB: public ProjectionShadowMap< MinimalCullBoundsShadowMap, LightSpacePerspectiveShadowMapAlgorithm > +{ + public: + /** Convenient typedef used in definition of ViewData struct and methods */ + typedef ProjectionShadowMap< MinimalCullBoundsShadowMap, LightSpacePerspectiveShadowMapAlgorithm > BaseClass; + + /** Classic OSG constructor */ + LightSpacePerspectiveShadowMapCB() + { + } + + /** Classic OSG cloning constructor */ + LightSpacePerspectiveShadowMapCB( + const LightSpacePerspectiveShadowMapCB& copy, + const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY) : BaseClass(copy,copyop) + { + } + + /** Declaration of standard OSG object methods */ + META_Object( osgShadow, LightSpacePerspectiveShadowMapCB ); +}; + +// Optimized for view frustum bounds +class OSGSHADOW_EXPORT LightSpacePerspectiveShadowMapVB: public ProjectionShadowMap< MinimalShadowMap, LightSpacePerspectiveShadowMapAlgorithm > +{ + public: + /** Convenient typedef used in definition of ViewData struct and methods */ + typedef ProjectionShadowMap< MinimalShadowMap, LightSpacePerspectiveShadowMapAlgorithm > BaseClass; + + /** Classic OSG constructor */ + LightSpacePerspectiveShadowMapVB() + { + } + + /** Classic OSG cloning constructor */ + LightSpacePerspectiveShadowMapVB( + const LightSpacePerspectiveShadowMapVB& copy, + const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY) : BaseClass(copy,copyop) + { + } + + /** Declaration of standard OSG object methods */ + META_Object( osgShadow, LightSpacePerspectiveShadowMapVB ); +}; + +typedef LightSpacePerspectiveShadowMapDB LightSpacePerspectiveShadowMap; + +} // namespace osgShadow + +#endif diff --git a/libs/include/android/osgShadow/MinimalCullBoundsShadowMap b/libs/include/android/osgShadow/MinimalCullBoundsShadowMap new file mode 100755 index 0000000..5b2c086 --- /dev/null +++ b/libs/include/android/osgShadow/MinimalCullBoundsShadowMap @@ -0,0 +1,82 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. + * + * ViewDependentShadow codes Copyright (C) 2008 Wojciech Lewandowski + * Thanks to to my company http://www.ai.com.pl for allowing me free this work. +*/ + +#ifndef OSGSHADOW_MINIMALCULLBOUNDSSHADOWMAP +#define OSGSHADOW_MINIMALCULLBOUNDSSHADOWMAP 1 + +#include + +namespace osgShadow { + +class OSGSHADOW_EXPORT MinimalCullBoundsShadowMap + : public MinimalShadowMap +{ + public : + /** Convenient typedef used in definition of ViewData struct and methods */ + typedef MinimalCullBoundsShadowMap ThisClass; + /** Convenient typedef used in definition of ViewData struct and methods */ + typedef MinimalShadowMap BaseClass; + + /** Classic OSG constructor */ + MinimalCullBoundsShadowMap(); + + /** Classic OSG cloning constructor */ + MinimalCullBoundsShadowMap( + const MinimalCullBoundsShadowMap& mcbsm, + const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY); + + /** Declaration of standard OSG object methods */ + META_Object( osgShadow, MinimalCullBoundsShadowMap ); + + protected: + /** Classic protected OSG destructor */ + virtual ~MinimalCullBoundsShadowMap(void); + + struct OSGSHADOW_EXPORT ViewData: public MinimalShadowMap::ViewData + { + virtual void init( ThisClass * st, osgUtil::CullVisitor * cv ); + + virtual void cullShadowReceivingScene( ); + + virtual void aimShadowCastingCamera( const osg::Light *light, + const osg::Vec4 &worldLightPos, + const osg::Vec3 &worldLightDir, + const osg::Vec3 &worldLightUp + = osg::Vec3(0,1,0) ); + + typedef std::vector< osgUtil::RenderLeaf* > RenderLeafList; + + static unsigned RemoveOldRenderLeaves + ( RenderLeafList &rllNew, RenderLeafList &rllOld ); + + static unsigned RemoveIgnoredRenderLeaves( RenderLeafList &rll ); + + static osg::BoundingBox ComputeRenderLeavesBounds + ( RenderLeafList &rll, osg::Matrix & projectionToWorld ); + + static osg::BoundingBox ComputeRenderLeavesBounds + ( RenderLeafList &rll, osg::Matrix & projectionToWorld, osg::Polytope & polytope ); + + static void GetRenderLeaves + ( osgUtil::RenderBin *rb, RenderLeafList &rll ); + }; + + META_ViewDependentShadowTechniqueData( ThisClass, ThisClass::ViewData ) +}; + +} // namespace osgShadow + +#endif diff --git a/libs/include/android/osgShadow/MinimalDrawBoundsShadowMap b/libs/include/android/osgShadow/MinimalDrawBoundsShadowMap new file mode 100755 index 0000000..2c85b34 --- /dev/null +++ b/libs/include/android/osgShadow/MinimalDrawBoundsShadowMap @@ -0,0 +1,128 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. + * + * ViewDependentShadow codes Copyright (C) 2008 Wojciech Lewandowski + * Thanks to to my company http://www.ai.com.pl for allowing me free this work. +*/ + + +#ifndef OSGSHADOW_MINIMALDRAWBOUNDSSHADOWMAP +#define OSGSHADOW_MINIMALDRAWBOUNDSSHADOWMAP 1 + +#include + +namespace osgShadow { + +class OSGSHADOW_EXPORT MinimalDrawBoundsShadowMap + : public MinimalShadowMap +{ + public : + /** Convenient typedef used in definition of ViewData struct and methods */ + typedef MinimalDrawBoundsShadowMap ThisClass; + /** Convenient typedef used in definition of ViewData struct and methods */ + typedef MinimalShadowMap BaseClass; + + /** Classic OSG constructor */ + MinimalDrawBoundsShadowMap(); + + /** Classic OSG cloning constructor */ + MinimalDrawBoundsShadowMap( + const MinimalDrawBoundsShadowMap& mdbsm, + const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY); + + /** Declaration of standard OSG object methods */ + META_Object( osgShadow, MinimalDrawBoundsShadowMap ); + + protected: + /** Classic protected OSG destructor */ + virtual ~MinimalDrawBoundsShadowMap(void); + + struct OSGSHADOW_EXPORT ViewData: public BaseClass::ViewData + { + osg::ref_ptr< osg::RefMatrix > _projection; + osg::Vec2s _boundAnalysisSize; + osg::ref_ptr< osg::Image > _boundAnalysisImage; + osg::ref_ptr< osg::Texture2D > _boundAnalysisTexture; + osg::ref_ptr< osg::Camera > _boundAnalysisCamera; + osg::observer_ptr< osg::Camera > _mainCamera; + + void setShadowCameraProjectionMatrixPtr( osg::RefMatrix * projection ) + { _projection = projection; } + + osg::RefMatrix * getShadowCameraProjectionMatrixPtr( void ) + { return _projection.get(); } + + virtual void init( ThisClass * st, osgUtil::CullVisitor * cv ); + + virtual void cullShadowReceivingScene( ); + + virtual void createDebugHUD( ); + + virtual void recordShadowMapParams( ); + + virtual void cullBoundAnalysisScene( ); + + static osg::BoundingBox scanImage( const osg::Image * image, osg::Matrix m ); + + virtual void performBoundAnalysis( const osg::Camera& camera ); + + ViewData( void ): _boundAnalysisSize( 64, 64 ) {} + }; + + friend struct ViewData; + + META_ViewDependentShadowTechniqueData( ThisClass, ThisClass::ViewData ) + + + struct CameraPostDrawCallback : public osg::Camera::DrawCallback { + + CameraPostDrawCallback( ViewData * vd ): _vd( vd ) + { + } + + virtual void operator ()( const osg::Camera& camera ) const + { + if( _vd.valid() ) + _vd->performBoundAnalysis( camera ); + } + + osg::observer_ptr< ViewData > _vd; + }; + + struct CameraCullCallback: public osg::NodeCallback { + + CameraCullCallback(ViewData * vd, osg::NodeCallback * nc): _vd(vd), _nc(nc) + { + } + + virtual void operator()(osg::Node* node, osg::NodeVisitor* nv) + { + osgUtil::CullVisitor *cv = dynamic_cast< osgUtil::CullVisitor *>( nv ); + + if( _nc.valid() ) + _nc->operator()(node,nv); + else + traverse(node,nv); + + if( cv ) + _vd->recordShadowMapParams( ); + } + + protected: + osg::observer_ptr< ViewData > _vd; + osg::ref_ptr< osg::NodeCallback > _nc; + }; +}; + +} // namespace osgShadow + +#endif diff --git a/libs/include/android/osgShadow/MinimalShadowMap b/libs/include/android/osgShadow/MinimalShadowMap new file mode 100755 index 0000000..6efac78 --- /dev/null +++ b/libs/include/android/osgShadow/MinimalShadowMap @@ -0,0 +1,164 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. + * + * ViewDependentShadow codes Copyright (C) 2008 Wojciech Lewandowski + * Thanks to to my company http://www.ai.com.pl for allowing me free this work. +*/ + +#ifndef OSGSHADOW_MINIMALSHADOWMAP +#define OSGSHADOW_MINIMALSHADOWMAP 1 + +#include + +namespace osgShadow { + +class OSGSHADOW_EXPORT MinimalShadowMap : public StandardShadowMap +{ + public : + /** Convenient typedef used in definition of ViewData struct and methods */ + typedef MinimalShadowMap ThisClass; + /** Convenient typedef used in definition of ViewData struct and methods */ + typedef StandardShadowMap BaseClass; + + /** Classic OSG constructor */ + MinimalShadowMap(); + + /** Classic OSG cloning constructor */ + MinimalShadowMap( + const MinimalShadowMap& msm, + const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY); + + /** Declaration of standard OSG object methods */ + META_Object( osgShadow, MinimalShadowMap ); + + void setModellingSpaceToWorldTransform( const osg::Matrix & modellingSpaceToWorld ) + { _modellingSpaceToWorld = modellingSpaceToWorld; } + + const osg::Matrix & getModellingSpaceToWorldTransform( void ) const + { return _modellingSpaceToWorld; } + + float getMaxFarPlane( ) const + { return _maxFarPlane; } + + void setMaxFarPlane( float maxFarPlane ) + { _maxFarPlane = maxFarPlane; } + + float getMinLightMargin( ) const + { return _minLightMargin; } + + void setMinLightMargin( float minLightMargin ) + { _minLightMargin = minLightMargin; } + + enum ShadowReceivingCoarseBoundAccuracy { + EMPTY_BOX, + BOUNDING_SPHERE, + BOUNDING_BOX, + DEFAULT_ACCURACY = BOUNDING_BOX + }; + + void setShadowReceivingCoarseBoundAccuracy + ( ShadowReceivingCoarseBoundAccuracy accuracy ) + { _shadowReceivingCoarseBoundAccuracy = accuracy; } + + ShadowReceivingCoarseBoundAccuracy + getShadowReceivingCoarseBoundAccuracy() const + { return _shadowReceivingCoarseBoundAccuracy; } + + protected: + /** Classic protected OSG destructor */ + virtual ~MinimalShadowMap(void); + + protected: + // Matrix modellingSpaceToWorld and its inverse + // are used to define Modelling Space where shadowed scene drawables + // have minimal (smallest possible extent) bounding boxes. + + // Computing visible shadow range in this space + // allows for optimal use of ShadowMap resolution. + + // By default it is set to identity ie computations are in world space. + // But it should be set to ElipsoidModel::localToWorld + // when scene objects are put on earth ellipsoid surface. + + // Other scenarios are also possible for example when models are + // built in XZY space which would require identity matrix with swapped colums + + osg::Matrix _modellingSpaceToWorld; + float _maxFarPlane; + float _minLightMargin; + ShadowReceivingCoarseBoundAccuracy _shadowReceivingCoarseBoundAccuracy; + + struct OSGSHADOW_EXPORT ViewData: public BaseClass::ViewData + { + osg::Matrix *_modellingSpaceToWorldPtr; + float *_maxFarPlanePtr; + float *_minLightMarginPtr; + int _frameShadowCastingCameraPasses; + + ConvexPolyhedron _sceneReceivingShadowPolytope; + std::vector< osg::Vec3d > _sceneReceivingShadowPolytopePoints; + + osg::Matrixd _clampedProjection; + + virtual void init( ThisClass * st, osgUtil::CullVisitor * cv ); + + virtual osg::BoundingBox computeShadowReceivingCoarseBounds( ); + + virtual void cullShadowReceivingScene( ); + + virtual void aimShadowCastingCamera( + const osg::BoundingSphere &bounds, + const osg::Light *light, + const osg::Vec4 &worldLightPos, + const osg::Vec3 &worldLightDir, + const osg::Vec3 &worldLightUp = osg::Vec3(0,1,0) ); + + virtual void aimShadowCastingCamera( const osg::Light *light, + const osg::Vec4 &worldLightPos, + const osg::Vec3 &worldLightDir, + const osg::Vec3 &worldLightUp + = osg::Vec3(0,1,0) ); + + virtual void frameShadowCastingCamera + ( const osg::Camera* cameraMain, osg::Camera* cameraShadow, int pass = 1 ); + + void cutScenePolytope( const osg::Matrix & matrix, + const osg::Matrix & inverse, + const osg::BoundingBox &bb = + osg::BoundingBox(-1,-1,-1,1,1,1) ); + + osg::BoundingBox computeScenePolytopeBounds + ( const osg::Matrix & m = *(osg::Matrix*)(NULL) ); + + // Utility methods for adjusting projection matrices + + // Modify projection matrix so that some output subrange + // is remapped to whole clip space (-1..1,-1..1,-1..1). + // Bit mask can be used to limit remaping to selected bounds only. + static void trimProjection + ( osg::Matrixd & projection, osg::BoundingBox subrange, + unsigned int trimMask = (1|2|4|8|16|32) + /*1=left|2=right|4=bottom|8=top|16=near|32=far*/); + + static void clampProjection + ( osg::Matrixd & projection, float n = 0, float f = FLT_MAX ); + + static void extendProjection + ( osg::Matrixd & projection, osg::Viewport * viewport, const osg::Vec2& margin ); + }; + + META_ViewDependentShadowTechniqueData( ThisClass, ThisClass::ViewData ) +}; + +} // namespace osgShadow + +#endif diff --git a/libs/include/android/osgShadow/OccluderGeometry b/libs/include/android/osgShadow/OccluderGeometry new file mode 100755 index 0000000..c81ae5f --- /dev/null +++ b/libs/include/android/osgShadow/OccluderGeometry @@ -0,0 +1,259 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGSHADOW_OCCLUDERGEOMETRY +#define OSGSHADOW_OCCLUDERGEOMETRY 1 + +#include +#include +#include +#include + +#include + + +namespace osgShadow { + +class ShadowVolumeGeometry; + +/** OccluderGeometry provides a sepecialised geometry representation of objects in scene that occlude light and therefore cast shadows. + * OccluderGeometry supports the computation of silhouette edges and shadow volume geometries, as well as use as geometry that one can rendering + * into a shadow map or end caps for the ZP+ algorithm. OccluderGeometry may be of the same resolution as an underlying geometry that it + * represents, or can be of lower resolution and combine manager seperate geometries together into a single shadow casting object. + * OccluderGeometry may be attached as UserData to Nodes or to Drawables. */ +class OSGSHADOW_EXPORT OccluderGeometry : public osg::Drawable +{ + public : + OccluderGeometry(); + + OccluderGeometry(const OccluderGeometry& oc, const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY); + + virtual Object* cloneType() const { return new OccluderGeometry(); } + virtual Object* clone(const osg::CopyOp& copyop) const { return new OccluderGeometry(*this,copyop); } + virtual bool isSameKindAs(const osg::Object* obj) const { return dynamic_cast(obj)!=NULL; } + virtual const char* libraryName() const { return "osgShadow"; } + virtual const char* className() const { return "OccluderGeometry"; } + + /** Compute an occluder geometry containing all the geometry in specified subgraph.*/ + void computeOccluderGeometry(osg::Node* subgraph, osg::Matrix* matrix=0, float sampleRatio=1.0f); + + /** Compute an occluder geometry containing the geometry in specified drawable.*/ + void computeOccluderGeometry(osg::Drawable* drawable, osg::Matrix* matrix=0, float sampleRatio=1.0f); + + + /** Compute ShadowVolumeGeometry. */ + void computeShadowVolumeGeometry(const osg::Vec4& lightpos, ShadowVolumeGeometry& svg) const; + + + /** Set the bounding polytope of the OccluderGeometry.*/ + void setBoundingPolytope(const osg::Polytope& polytope) { _boundingPolytope = polytope; } + + /** Get the bounding polytope of the OccluderGeometry.*/ + osg::Polytope& getBoundingPolytope() { return _boundingPolytope; } + + /** Get the const bounding polytope of the OccluderGeometry.*/ + const osg::Polytope& getBoundingPolytope() const { return _boundingPolytope; } + + + /** Render the occluder geometry. */ + virtual void drawImplementation(osg::RenderInfo& renderInfo) const; + + /** Compute the bounding box around occluder geometry.*/ + virtual osg::BoundingBox computeBound() const; + + typedef std::vector Vec3List; + typedef std::vector UIntList; + + public: + + void processGeometry(osg::Drawable* drawable, osg::Matrix* matrix=0, float sampleRatio=1.0f); + + protected : + + virtual ~OccluderGeometry() {} + + struct Edge + { + Edge(): + _p1(0), + _p2(0), + _t1(-1), + _t2(-1) {} + + Edge(unsigned int p1, unsigned int p2): + _p1(p1), + _p2(p2), + _t1(-1), + _t2(-1) + { + if (p1>p2) + { + // swap ordering so p1 is less than or equal to p2 + _p1 = p2; + _p2 = p1; + } + } + + inline bool operator < (const Edge& rhs) const + { + if (_p1 < rhs._p1) return true; + if (_p1 > rhs._p1) return false; + return (_p2 < rhs._p2); + } + + bool addTriangle(unsigned int tri) const + { + if (_t1<0) + { + _t1 = tri; + return true; + } + else if (_t2<0) + { + _t2 = tri; + return true; + } + // argg more than two triangles assigned + return false; + } + + bool boundaryEdge() const { return _t2<0; } + + unsigned int _p1; + unsigned int _p2; + + mutable int _t1; + mutable int _t2; + + mutable osg::Vec3 _normal; + }; + + typedef std::vector EdgeList; + + inline bool isLightPointSilhouetteEdge(const osg::Vec3& lightpos, const Edge& edge) const + { + if (edge.boundaryEdge()) return true; + + float offset = 0.0f; + + osg::Vec3 delta(lightpos-_vertices[edge._p1]); + delta.normalize(); + + float n1 = delta * _triangleNormals[edge._t1] + offset; + float n2 = delta * _triangleNormals[edge._t2] + offset; + + float angle_offset = 0.0f; + + n1 = cos(acosf(n1) + angle_offset); + n2 = cos(acosf(n2) + angle_offset); + + if (n1==0.0f && n2==0.0f) return false; + + return n1*n2 <= 0.0f; + } + + inline bool isLightDirectionSilhouetteEdge(const osg::Vec3& lightdirection, const Edge& edge) const + { + if (edge.boundaryEdge()) return true; + + float offset = 0.0f; + + float n1 = lightdirection * _triangleNormals[edge._t1] + offset; + float n2 = lightdirection * _triangleNormals[edge._t2] + offset; + + float angle_offset = 0.0f; + + n1 = cos(acosf(n1) + angle_offset); + n2 = cos(acosf(n2) + angle_offset); + + if (n1==0.0f && n2==0.0f) return false; + + return n1*n2 <= 0.0f; + } + + void setUpInternalStructures(); + + void removeDuplicateVertices(); + void removeNullTriangles(); + void computeNormals(); + void buildEdgeMaps(); + + void computeLightDirectionSilhouetteEdges(const osg::Vec3& lightdirection, UIntList& silhouetteIndices) const; + void computeLightPositionSilhouetteEdges(const osg::Vec3& lightpos, UIntList& silhouetteIndices) const; + + osg::Polytope _boundingPolytope; + + Vec3List _vertices; + Vec3List _normals; + Vec3List _triangleNormals; + UIntList _triangleIndices; + + EdgeList _edges; +}; + +class OSGSHADOW_EXPORT ShadowVolumeGeometry : public osg::Drawable +{ + public : + ShadowVolumeGeometry(); + + ShadowVolumeGeometry(const ShadowVolumeGeometry& oc, const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY); + + virtual Object* cloneType() const { return new ShadowVolumeGeometry(); } + virtual Object* clone(const osg::CopyOp& copyop) const { return new ShadowVolumeGeometry(*this,copyop); } + virtual bool isSameKindAs(const osg::Object* obj) const { return dynamic_cast(obj)!=NULL; } + virtual const char* libraryName() const { return "osgShadow"; } + virtual const char* className() const { return "ShadowVolumeGeometry"; } + + enum DrawMode + { + GEOMETRY, + STENCIL_TWO_PASS, + STENCIL_TWO_SIDED + }; + + void setDrawMode(DrawMode mode) { _drawMode = mode; } + DrawMode getDrawMode() const { return _drawMode; } + + typedef std::vector Vec3List; + typedef std::vector UIntList; + + void setVertices(const Vec3List& vertices) { _vertices = vertices; } + Vec3List& getVertices() { return _vertices; } + const Vec3List& getVertices() const { return _vertices; } + + void setNormals(const Vec3List& normals) { _normals = normals; } + Vec3List& getNormals() { return _normals; } + const Vec3List& getNormals() const { return _normals; } + + + /** Render the occluder geometry. */ + virtual void drawImplementation(osg::RenderInfo& renderInfo) const; + + /** Compute the bounding box around occluder geometry.*/ + virtual osg::BoundingBox computeBound() const; + + public: + + protected : + + virtual ~ShadowVolumeGeometry() {} + + DrawMode _drawMode; + Vec3List _vertices; + Vec3List _normals; + UIntList _indices; +}; + +} + +#endif diff --git a/libs/include/android/osgShadow/ParallelSplitShadowMap b/libs/include/android/osgShadow/ParallelSplitShadowMap new file mode 100755 index 0000000..631a9ad --- /dev/null +++ b/libs/include/android/osgShadow/ParallelSplitShadowMap @@ -0,0 +1,216 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +/* ParallelSplitShadowMap written by Adrian Egli + * + * this version has still a bug in mutli-thread application (flickering problem) + * to avoid the flickering problem try osgShadow --pssm --SingleThreaded your_scene.ive + * + * The Parallel Split Shadow Map only supports directional light for simulating the shadow. + * It's one of the most robust algorithm for huge terrain sun light's shadow simulation, if + * you need to shadow a terrain, or another huge scene, you should use Parallel Split Shadow Map + * or at least test it against your scene. Have fun. + * + */ + +#ifndef OSGSHADOW_ParallelSplitShadowMap +#define OSGSHADOW_ParallelSplitShadowMap 1 + +#include +#include +#include +#include + +#include + +namespace osgShadow { + +class OSGSHADOW_EXPORT ParallelSplitShadowMap : public ShadowTechnique +{ + public: + ParallelSplitShadowMap(osg::Geode** debugGroup=NULL, int icountplanes=3); + + ParallelSplitShadowMap(const ParallelSplitShadowMap& es, const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY); + + META_Object(osgShadow, ParallelSplitShadowMap); + + + /** Initialize the ShadowedScene and local cached data structures.*/ + virtual void init(); + + /** Run the update traversal of the ShadowedScene and update any loca chached data structures.*/ + virtual void update(osg::NodeVisitor& nv); + + /** Run the cull traversal of the ShadowedScene and set up the rendering for this ShadowTechnique.*/ + virtual void cull(osgUtil::CullVisitor& cv); + + /** Clean scene graph from any shadow technique specific nodes, state and drawables.*/ + virtual void cleanSceneGraph(); + + /** Switch on the debug coloring in GLSL (only the first 3 texture/splits showed for visualisation */ + inline void setDebugColorOn() { _debug_color_in_GLSL = true; } + + /** Set the polygon offset osg::Vec2f(factor,unit) */ + inline void setPolygonOffset(const osg::Vec2f& p) { _polgyonOffset = p;_user_polgyonOffset_set=true;} + + /** Get the polygon offset osg::Vec2f(factor,unit) */ + inline const osg::Vec2f& getPolygonOffset() const { return _polgyonOffset;} + + /** Set the texture resolution */ + inline void setTextureResolution(unsigned int resolution) { _resolution = resolution; } + + /** Get the texture resolution */ + inline unsigned int getTextureResolution() const { return _resolution; } + + /** Set the max far distance */ + inline void setMaxFarDistance(double farDist) { _setMaxFarDistance = farDist; _isSetMaxFarDistance = true; } + + /** Get the max far distance */ + inline double getMaxFarDistance() const { return _setMaxFarDistance; } + + /** Set the factor for moving the virtual camera behind the real camera*/ + inline void setMoveVCamBehindRCamFactor(double distFactor ) { _move_vcam_behind_rcam_factor = distFactor; } + + /** Get the factor for moving the virtual camera behind the real camera*/ + inline double getMoveVCamBehindRCamFactor() const { return _move_vcam_behind_rcam_factor; } + + /** Set min near distance for splits */ + inline void setMinNearDistanceForSplits(double nd){ _split_min_near_dist=nd; } + + /** Get min near distance for splits */ + inline double getMinNearDistanceForSplits() const { return _split_min_near_dist; } + + /** set a user defined light for shadow simulation (sun light, ... ) + * when this light get passed to pssm, the scene's light are no longer collected + * and simulated. just this user passed light, it needs to be a directional light. + */ + inline void setUserLight(osg::Light* light) { _userLight = light; } + + /** get the user defined light for shadow simulation */ + inline const osg::Light* getUserLight() const { return _userLight.get(); } + + /** Set the values for the ambient bias the shader will use.*/ + void setAmbientBias(const osg::Vec2& ambientBias ); + + /** Get the values for the ambient bias the shader will use.*/ + const osg::Vec2& getAmbientBias() const { return _ambientBias; } + + /** + * you can overwrite the fragment shader if you like to modify it yourself, own fragment shader can be used + */ + class OSGSHADOW_EXPORT FragmentShaderGenerator : public osg::Referenced { + public: + /** + * generate the GLSL fragement shader + */ + virtual std::string generateGLSL_FragmentShader_BaseTex(bool debug, unsigned int splitCount,double textureRes, bool filtered, unsigned int nbrSplits,unsigned int textureOffset); + }; + + /** set fragment shader generator */ + inline void setFragmentShaderGenerator(FragmentShaderGenerator* fsw) { _FragmentShaderGenerator = fsw;} + + /** enable / disable shadow filtering */ + inline void enableShadowGLSLFiltering(bool filtering = true) { _GLSL_shadow_filtered = filtering; } + + enum SplitCalcMode { + SPLIT_LINEAR, + SPLIT_EXP + }; + + /** set split calculation mode */ + inline void setSplitCalculationMode(SplitCalcMode scm=SPLIT_EXP) { _SplitCalcMode = scm; } + + /** get split calculation mode */ + inline SplitCalcMode getSplitCalculationMode() const { return _SplitCalcMode; } + + + protected : + + virtual ~ParallelSplitShadowMap() {} + + + struct PSSMShadowSplitTexture { + // RTT + osg::ref_ptr _camera; + osg::ref_ptr _texgen; + osg::ref_ptr _texture; + osg::ref_ptr _stateset; + unsigned int _textureUnit; + + + double _split_far; + + osg::ref_ptr _debug_camera; + osg::ref_ptr _debug_texture; + osg::ref_ptr _debug_stateset; + unsigned int _debug_textureUnit; + + // Light (SUN) + osg::Vec3d _lightCameraSource; + osg::Vec3d _lightCameraTarget; + osg::Vec3d _frustumSplitCenter; + osg::Vec3d _lightDirection; + double _lightNear; + double _lightFar; + + osg::Matrix _cameraView; + osg::Matrix _cameraProj; + + unsigned int _splitID; + unsigned int _resolution; + + osg::Uniform* _farDistanceSplit; + }; + + typedef std::map PSSMShadowSplitTextureMap; + PSSMShadowSplitTextureMap _PSSMShadowSplitTextureMap; + + + private: + void calculateFrustumCorners(PSSMShadowSplitTexture &pssmShadowSplitTexture,osg::Vec3d *frustumCorners); + void calculateLightInitialPosition(PSSMShadowSplitTexture &pssmShadowSplitTexture,osg::Vec3d *frustumCorners); + void calculateLightNearFarFormFrustum(PSSMShadowSplitTexture &pssmShadowSplitTexture,osg::Vec3d *frustumCorners); + void calculateLightViewProjectionFormFrustum(PSSMShadowSplitTexture &pssmShadowSplitTexture,osg::Vec3d *frustumCorners); + + osg::Geode** _displayTexturesGroupingNode; + + unsigned int _textureUnitOffset; + + unsigned int _number_of_splits; + + bool _debug_color_in_GLSL; + + osg::Vec2 _polgyonOffset; + bool _user_polgyonOffset_set; + + unsigned int _resolution; + + double _setMaxFarDistance; + bool _isSetMaxFarDistance; + + double _split_min_near_dist; + + double _move_vcam_behind_rcam_factor; + + osg::ref_ptr _userLight; + osg::ref_ptr _FragmentShaderGenerator; + + bool _GLSL_shadow_filtered; + SplitCalcMode _SplitCalcMode; + + osg::Uniform* _ambientBiasUniform; + osg::Vec2 _ambientBias; + +}; +} +#endif diff --git a/libs/include/android/osgShadow/ProjectionShadowMap b/libs/include/android/osgShadow/ProjectionShadowMap new file mode 100755 index 0000000..927dd33 --- /dev/null +++ b/libs/include/android/osgShadow/ProjectionShadowMap @@ -0,0 +1,85 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. + * + * ViewDependentShadow codes Copyright (C) 2008 Wojciech Lewandowski + * Thanks to to my company http://www.ai.com.pl for allowing me free this work. +*/ + +#ifndef OSGSHADOW_PROJECTIONSHADOWMAP +#define OSGSHADOW_PROJECTIONSHADOWMAP 1 + +#include + +namespace osgShadow { + +template< typename MinimalBoundsBaseClass, typename ShadowProjectionAlgorithmClass > +class OSGSHADOW_EXPORT ProjectionShadowMap : public MinimalBoundsBaseClass +{ + public : + /** Convenient typedef used in definition of ViewData struct and methods */ + typedef MinimalBoundsBaseClass BaseClass; + /** Convenient typedef used in definition of ViewData struct and methods */ + typedef ProjectionShadowMap ThisClass; + + /** Classic OSG constructor */ + ProjectionShadowMap() : BaseClass() + { + } + + /** Classic OSG cloning constructor */ + ProjectionShadowMap( + const ProjectionShadowMap& copy, + const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY) : BaseClass(copy,copyop) + { + } + + /** Declaration of standard OSG object methods */ + META_Object( osgShadow, ProjectionShadowMap ); + + protected: + + /** Classic protected OSG destructor */ + virtual ~ProjectionShadowMap(void) + { + } + + struct OSGSHADOW_EXPORT ViewData: public BaseClass::ViewData, + public ShadowProjectionAlgorithmClass + { + #if 0 + virtual void init( ThisClass * st, osgUtil::CullVisitor * cv ); + { + BaseClass::ViewData::init( st, cv ); + } + #endif + + virtual void frameShadowCastingCamera + ( const osg::Camera* cameraMain, osg::Camera* cameraShadow, int pass = 1 ) + { + if( pass == BaseClass::ViewData::_frameShadowCastingCameraPasses - 1 ) + { + // Force dependent name lookup + ShadowProjectionAlgorithmClass::operator() + ( &this->_sceneReceivingShadowPolytope, cameraMain, cameraShadow ); + } + + // DebugBoundingBox( computeScenePolytopeBounds(), "ProjectionShadowMap" ); + BaseClass::ViewData::frameShadowCastingCamera( cameraMain, cameraShadow, pass ); + } + }; + + META_ViewDependentShadowTechniqueData( ThisClass, typename ThisClass::ViewData ) +}; + +} // namespace osgShadow + +#endif diff --git a/libs/include/android/osgShadow/ShadowMap b/libs/include/android/osgShadow/ShadowMap new file mode 100755 index 0000000..9b16e97 --- /dev/null +++ b/libs/include/android/osgShadow/ShadowMap @@ -0,0 +1,123 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGSHADOW_SHADOWEMAP +#define OSGSHADOW_SHADOWEMAP 1 + +#include +#include +#include +#include + +#include + +namespace osgShadow { + +/** ShadowedTexture provides an implementation of shadow textures.*/ +class OSGSHADOW_EXPORT ShadowMap : public ShadowTechnique +{ + public : + ShadowMap(); + + ShadowMap(const ShadowMap& es, const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY); + + META_Object(osgShadow, ShadowMap); + + /** Set the texture unit that the shadow texture will be applied on.*/ + void setTextureUnit(unsigned int unit); + + /** Get the texture unit that the shadow texture will be applied on.*/ + unsigned int getTextureUnit() const { return _shadowTextureUnit; } + + /** set the polygon offset used initially */ + void setPolygonOffset(const osg::Vec2& polyOffset); + + /** get the used polygon offset */ + const osg::Vec2& getPolygonOffset() const { return _polyOffset; } + + /** Set the values for the ambient bias the shader will use.*/ + void setAmbientBias(const osg::Vec2& ambientBias ); + + /** Get the values that are used for the ambient bias in the shader.*/ + const osg::Vec2& getAmbientBias() const { return _ambientBias; } + + /** set the size in pixels x / y for the shadow texture.*/ + void setTextureSize(const osg::Vec2s& textureSize); + + /** Get the values that are used for the ambient bias in the shader.*/ + const osg::Vec2s& getTextureSize() const { return _textureSize; } + + /** Set the Light that will cast shadows */ + void setLight(osg::Light* light); + void setLight(osg::LightSource* ls); + + typedef std::vector< osg::ref_ptr > UniformList; + + typedef std::vector< osg::ref_ptr > ShaderList; + + /** Add a shader to internal list, will be used instead of the default ones */ + inline void addShader(osg::Shader* shader) { _shaderList.push_back(shader); } + + /** Reset internal shader list */ + inline void clearShaderList() { _shaderList.clear(); } + + /** initialize the ShadowedScene and local cached data structures.*/ + virtual void init(); + + /** run the update traversal of the ShadowedScene and update any loca chached data structures.*/ + virtual void update(osg::NodeVisitor& nv); + + /** run the cull traversal of the ShadowedScene and set up the rendering for this ShadowTechnique.*/ + virtual void cull(osgUtil::CullVisitor& cv); + + /** Clean scene graph from any shadow technique specific nodes, state and drawables.*/ + virtual void cleanSceneGraph(); + + // debug methods + + osg::ref_ptr makeDebugHUD(); + + protected: + virtual ~ShadowMap(void) {}; + + /** Create the managed Uniforms */ + virtual void createUniforms(); + + virtual void createShaders(); + + // forward declare, interface and implementation provided in ShadowMap.cpp + class DrawableDrawWithDepthShadowComparisonOffCallback; + + osg::ref_ptr _camera; + osg::ref_ptr _texgen; + osg::ref_ptr _texture; + osg::ref_ptr _stateset; + osg::ref_ptr _program; + osg::ref_ptr _light; + + osg::ref_ptr _ls; + + osg::ref_ptr _ambientBiasUniform; + UniformList _uniformList; + ShaderList _shaderList; + unsigned int _baseTextureUnit; + unsigned int _shadowTextureUnit; + osg::Vec2 _polyOffset; + osg::Vec2 _ambientBias; + osg::Vec2s _textureSize; + + }; + +} + +#endif diff --git a/libs/include/android/osgShadow/ShadowSettings b/libs/include/android/osgShadow/ShadowSettings new file mode 100755 index 0000000..58020dc --- /dev/null +++ b/libs/include/android/osgShadow/ShadowSettings @@ -0,0 +1,147 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-20 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGSHADOW_SHADOWSETTINGS +#define OSGSHADOW_SHADOWSETTINGS 1 + +#include +#include +#include + +namespace osgShadow { + +/** ShadowSettings provides the parameters that the ShadowTechnique should use as a guide for setting up shadowing.*/ +class OSGSHADOW_EXPORT ShadowSettings : public osg::Object +{ + public: + ShadowSettings(); + ShadowSettings(const ShadowSettings& ss, const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY); + + META_Object(osgShadow, ShadowSettings); + + void setReceivesShadowTraversalMask(unsigned int mask) { _receivesShadowTraversalMask = mask; } + unsigned int getReceivesShadowTraversalMask() const { return _receivesShadowTraversalMask; } + + void setCastsShadowTraversalMask(unsigned int mask) { _castsShadowTraversalMask = mask; } + unsigned int getCastsShadowTraversalMask() const { return _castsShadowTraversalMask; } + + void setComputeNearFarModeOverride(osg::CullSettings::ComputeNearFarMode cnfn) { _computeNearFearModeOverride = cnfn; } + osg::CullSettings::ComputeNearFarMode getComputeNearFarModeOverride() const { return _computeNearFearModeOverride; } + + + /** Set the LightNum of the light in the scene to assign a shadow for. + * Default value is -1, which signifies that shadow technique should automatically select an active light + * to assign a shadow, typically this will be the first active light found. */ + void setLightNum(int lightNum) { _lightNum = lightNum; } + int getLightNum() const { return _lightNum; } + + void setBaseShadowTextureUnit(unsigned int unit) { _baseShadowTextureUnit = unit; } + unsigned int getBaseShadowTextureUnit() const { return _baseShadowTextureUnit; } + + /** Set whether to use osg::StateAttribute::OVERRIDE for the shadow map texture. + * Enabling override will force the shadow map texture to override any texture set on the shadow maps texture unit.*/ + void setUseOverrideForShadowMapTexture(bool useOverride) { _useShadowMapTextureOverride = useOverride; } + + /** Get whether to use osg::StateAttribute::OVERRIDE for the shadow map texture. */ + bool getUseOverrideForShadowMapTexture() const { return _useShadowMapTextureOverride; } + + + /** Set the size of the shadow map textures.*/ + void setTextureSize(const osg::Vec2s& textureSize) { _textureSize = textureSize; } + + /** Get the size of the shadow map textures.*/ + const osg::Vec2s& getTextureSize() const { return _textureSize; } + + void setMinimumShadowMapNearFarRatio(double ratio) { _minimumShadowMapNearFarRatio = ratio; } + double getMinimumShadowMapNearFarRatio() const { return _minimumShadowMapNearFarRatio; } + + void setMaximumShadowMapDistance(double distance) { _maximumShadowMapDistance = distance; } + double getMaximumShadowMapDistance() const { return _maximumShadowMapDistance; } + + + enum ShadowMapProjectionHint + { + ORTHOGRAPHIC_SHADOW_MAP, + PERSPECTIVE_SHADOW_MAP + }; + + void setShadowMapProjectionHint(ShadowMapProjectionHint hint) { _shadowMapProjectionHint = hint; } + ShadowMapProjectionHint getShadowMapProjectionHint() const { return _shadowMapProjectionHint; } + + /** Set the cut off angle, in degrees, between the light direction and the view direction + * that determines whether perspective shadow mapping is appropriate, or thar orthographic shadow + * map should be used instead. Default is 2 degrees so that for any angle greater than 2 degrees + * perspective shadow map will be used, and any angle less than 2 degrees orthographic shadow map + * will be used. Note, if ShadowMapProjectionHint is set to ORTHOGRAPHIC_SHADOW_MAP then an + * orthographic shadow map will always be used.*/ + void setPerspectiveShadowMapCutOffAngle(double angle) { _perspectiveShadowMapCutOffAngle = angle; } + double getPerspectiveShadowMapCutOffAngle() const { return _perspectiveShadowMapCutOffAngle; } + + + void setNumShadowMapsPerLight(unsigned int numShadowMaps) { _numShadowMapsPerLight = numShadowMaps; } + unsigned int getNumShadowMapsPerLight() const { return _numShadowMapsPerLight; } + + enum MultipleShadowMapHint + { + PARALLEL_SPLIT, + CASCADED + }; + + void setMultipleShadowMapHint(MultipleShadowMapHint hint) { _multipleShadowMapHint = hint; } + MultipleShadowMapHint getMultipleShadowMapHint() const { return _multipleShadowMapHint; } + + + enum ShaderHint + { + NO_SHADERS, + PROVIDE_FRAGMENT_SHADER, + PROVIDE_VERTEX_AND_FRAGMENT_SHADER + }; + + void setShaderHint(ShaderHint shaderHint) { _shaderHint = shaderHint; } + ShaderHint getShaderHint() const { return _shaderHint; } + + void setDebugDraw(bool debugDraw) { _debugDraw = debugDraw; } + bool getDebugDraw() const { return _debugDraw; } + + protected: + + virtual ~ShadowSettings(); + + + unsigned int _receivesShadowTraversalMask; + unsigned int _castsShadowTraversalMask; + + osg::CullSettings::ComputeNearFarMode _computeNearFearModeOverride; + + int _lightNum; + unsigned int _baseShadowTextureUnit; + bool _useShadowMapTextureOverride; + osg::Vec2s _textureSize; + + double _minimumShadowMapNearFarRatio; + double _maximumShadowMapDistance; + ShadowMapProjectionHint _shadowMapProjectionHint; + double _perspectiveShadowMapCutOffAngle; + + unsigned int _numShadowMapsPerLight; + MultipleShadowMapHint _multipleShadowMapHint; + + ShaderHint _shaderHint; + bool _debugDraw; + +}; + +} + +#endif diff --git a/libs/include/android/osgShadow/ShadowTechnique b/libs/include/android/osgShadow/ShadowTechnique new file mode 100755 index 0000000..f9b3230 --- /dev/null +++ b/libs/include/android/osgShadow/ShadowTechnique @@ -0,0 +1,89 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGSHADOW_SHADOWEDTECHNIQUE +#define OSGSHADOW_SHADOWEDTECHNIQUE 1 + +#include +#include +#include +#include +#include + +#include + +namespace osgShadow { + +// forward declare ShadowedScene +class ShadowedScene; + +/** ShadowedScene provides a mechanism for decorating a scene that the needs to have shadows cast upon it.*/ +class OSGSHADOW_EXPORT ShadowTechnique : public osg::Object +{ + public : + ShadowTechnique(); + + ShadowTechnique(const ShadowTechnique& es, const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY); + + META_Object(osgShadow, ShadowTechnique); + + ShadowedScene* getShadowedScene() { return _shadowedScene; } + + const ShadowedScene* getShadowedScene() const { return _shadowedScene; } + + /** initialize the ShadowedScene and local cached data structures.*/ + virtual void init(); + + /** run the update traversal of the ShadowedScene and update any local cached data structures.*/ + virtual void update(osg::NodeVisitor& nv); + + /** run the cull traversal of the ShadowedScene and set up the rendering for this ShadowTechnique.*/ + virtual void cull(osgUtil::CullVisitor& cv); + + /** Clean scene graph from any shadow technique specific nodes, state and drawables.*/ + virtual void cleanSceneGraph(); + + virtual void traverse(osg::NodeVisitor& nv); + + /** Dirty so that cached data structures are updated.*/ + virtual void dirty() { _dirty = true; } + + protected : + + class OSGSHADOW_EXPORT CameraCullCallback : public osg::NodeCallback + { + public: + + CameraCullCallback(ShadowTechnique* st); + + virtual void operator()(osg::Node*, osg::NodeVisitor* nv); + + protected: + + ShadowTechnique* _shadowTechnique; + }; + + osg::Vec3 computeOrthogonalVector(const osg::Vec3& direction) const; + + virtual ~ShadowTechnique(); + + friend class ShadowedScene; + + ShadowedScene* _shadowedScene; + bool _dirty; + +}; + +} + +#endif diff --git a/libs/include/android/osgShadow/ShadowTexture b/libs/include/android/osgShadow/ShadowTexture new file mode 100755 index 0000000..b793803 --- /dev/null +++ b/libs/include/android/osgShadow/ShadowTexture @@ -0,0 +1,68 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGSHADOW_SHADOWETEXTURE +#define OSGSHADOW_SHADOWETEXTURE 1 + +#include +#include + +#include + +namespace osgShadow { + +/** ShadowedTexture provides an implementation of shadow textures.*/ +class OSGSHADOW_EXPORT ShadowTexture : public ShadowTechnique +{ + public : + ShadowTexture(); + + ShadowTexture(const ShadowTexture& es, const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY); + + META_Object(osgShadow, ShadowTexture); + + /** Set the texture unit that the shadow texture will be applied on.*/ + void setTextureUnit(unsigned int unit); + + /** Get the texture unit that the shadow texture will be applied on.*/ + unsigned int getTextureUnit() const { return _textureUnit; } + + + /** initialize the ShadowedScene and local cached data structures.*/ + virtual void init(); + + /** run the update traversal of the ShadowedScene and update any loca chached data structures.*/ + virtual void update(osg::NodeVisitor& nv); + + /** run the cull traversal of the ShadowedScene and set up the rendering for this ShadowTechnique.*/ + virtual void cull(osgUtil::CullVisitor& cv); + + /** Clean scene graph from any shadow technique specific nodes, state and drawables.*/ + virtual void cleanSceneGraph(); + + + protected : + + virtual ~ShadowTexture() {} + + osg::ref_ptr _camera; + osg::ref_ptr _texgen; + osg::ref_ptr _texture; + osg::ref_ptr _stateset; + osg::ref_ptr _material; + unsigned int _textureUnit; +}; + +} + +#endif diff --git a/libs/include/android/osgShadow/ShadowVolume b/libs/include/android/osgShadow/ShadowVolume new file mode 100755 index 0000000..73cb04e --- /dev/null +++ b/libs/include/android/osgShadow/ShadowVolume @@ -0,0 +1,83 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGSHADOW_SHADOWVOLUME +#define OSGSHADOW_SHADOWVOLUME 1 + +#include +#include +#include + +#include +#include + +namespace osgShadow { + +/** ShadowedTexture provides an implementation of shadow textures.*/ +class OSGSHADOW_EXPORT ShadowVolume : public ShadowTechnique +{ + public : + ShadowVolume(); + + ShadowVolume(const ShadowVolume& es, const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY); + + META_Object(osgShadow, ShadowVolume); + + + void setDrawMode(osgShadow::ShadowVolumeGeometry::DrawMode drawMode); + osgShadow::ShadowVolumeGeometry::DrawMode getDrawMode() const { return _drawMode; } + + void setDynamicShadowVolumes(bool dynamicShadowVolumes); + bool getDynamicShadowVolumes() const { return _dynamicShadowVolumes; } + + /** initialize the ShadowedScene and local cached data structures.*/ + virtual void init(); + + /** run the update traversal of the ShadowedScene and update any loca chached data structures.*/ + virtual void update(osg::NodeVisitor& nv); + + /** run the cull traversal of the ShadowedScene and set up the rendering for this ShadowTechnique.*/ + virtual void cull(osgUtil::CullVisitor& cv); + + /** Clean scene graph from any shadow technique specific nodes, state and drawables.*/ + virtual void cleanSceneGraph(); + + + protected : + + virtual ~ShadowVolume(); + + osgShadow::ShadowVolumeGeometry::DrawMode _drawMode; + bool _dynamicShadowVolumes; + + osg::ref_ptr _occluder; + + OpenThreads::Mutex _shadowVolumeMutex; + osg::ref_ptr _shadowVolume; + + osg::Vec4 _lightpos; + + osg::ref_ptr _ambientLight; + osg::ref_ptr _diffuseLight; + + osg::ref_ptr _ss1; + osg::ref_ptr _mainShadowStateSet; + osg::ref_ptr _shadowVolumeStateSet; + osg::ref_ptr _shadowedSceneStateSet; + + +}; + +} + +#endif diff --git a/libs/include/android/osgShadow/ShadowedScene b/libs/include/android/osgShadow/ShadowedScene new file mode 100755 index 0000000..ed401a2 --- /dev/null +++ b/libs/include/android/osgShadow/ShadowedScene @@ -0,0 +1,85 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGSHADOW_SHADOWEDSCENE +#define OSGSHADOW_SHADOWEDSCENE 1 + +#include +#include +#include +#include + +#include +#include + +namespace osgShadow { + +/** ShadowedScene provides a mechansim for decorating a scene that the needs to have shadows cast upon it.*/ +class OSGSHADOW_EXPORT ShadowedScene : public osg::Group +{ + public: + + ShadowedScene(ShadowTechnique* st=0); + + ShadowedScene(const ShadowedScene& es, const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY); + + META_Node(osgShadow, ShadowedScene); + + virtual void traverse(osg::NodeVisitor& nv); + + void setShadowSettings(ShadowSettings* ss); + ShadowSettings* getShadowSettings() { return _shadowSettings.get(); } + const ShadowSettings* getShadowSettings() const { return _shadowSettings.get(); } + + void setShadowTechnique(ShadowTechnique* technique); + ShadowTechnique* getShadowTechnique() { return _shadowTechnique.get(); } + const ShadowTechnique* getShadowTechnique() const { return _shadowTechnique.get(); } + + /** Clean scene graph from any shadow technique specific nodes, state and drawables.*/ + void cleanSceneGraph(); + + /** Dirty any cache data structures held in the attached ShadowTechnqiue.*/ + void dirty(); + + /** Resize any per context GLObject buffers to specified size. */ + virtual void resizeGLObjectBuffers(unsigned int maxSize); + + /** If State is non-zero, this function releases any associated OpenGL objects for + * the specified graphics context. Otherwise, releases OpenGL objects + * for all graphics contexts. */ + virtual void releaseGLObjects(osg::State* = 0) const; + + public: + + /** deprecated, moved to ShadowSettings.*/ + void setReceivesShadowTraversalMask(unsigned int mask) { if (_shadowSettings.valid()) _shadowSettings->setReceivesShadowTraversalMask(mask); } + /** deprecated, moved to ShadowSettings.*/ + unsigned int getReceivesShadowTraversalMask() const { return _shadowSettings.valid() ? _shadowSettings->getReceivesShadowTraversalMask() : 0xffffffff; } + + /** deprecated, moved to ShadowSettings.*/ + void setCastsShadowTraversalMask(unsigned int mask) { if (_shadowSettings.valid()) _shadowSettings->setCastsShadowTraversalMask(mask); } + /** deprecated, moved to ShadowSettings.*/ + unsigned int getCastsShadowTraversalMask() const { return _shadowSettings.valid() ? _shadowSettings->getCastsShadowTraversalMask() : 0xffffffff; } + +protected: + + virtual ~ShadowedScene(); + + osg::ref_ptr _shadowSettings; + osg::ref_ptr _shadowTechnique; + +}; + +} + +#endif diff --git a/libs/include/android/osgShadow/SoftShadowMap b/libs/include/android/osgShadow/SoftShadowMap new file mode 100755 index 0000000..0a2315a --- /dev/null +++ b/libs/include/android/osgShadow/SoftShadowMap @@ -0,0 +1,92 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGSHADOW_SOFTSHADOWMAP +#define OSGSHADOW_SOFTSHADOWMAP 1 + +#include +#include +#include +#include + +#include + +namespace osgShadow { + +/** SoftShadowMap provides an implementation of soft shadows with shadow maps.*/ +class OSGSHADOW_EXPORT SoftShadowMap : public ShadowMap +{ + public : + SoftShadowMap(); + + SoftShadowMap(const SoftShadowMap& es, const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY); + + META_Object(osgShadow, SoftShadowMap); + + /** Set the values for width of the soft penumbra the shader will use. + * Zero is for hard shadow (no penumbra). 0.01 is already very soft penumbra. + * Default is 0.005.*/ + void setSoftnessWidth(float softnessWidth); + + /** Get the value used for width of the soft penumbra in the shader.*/ + float getSoftnessWidth() const { return _softnessWidth; } + + /** Set the values for jittering scale the shader will use. + * Zero is no jittering (i.e. see the banding in penumbra) + * High values (>64) cause 'pixelization' of the penumbra. + * Usually but not necessarily power of two number. + * Default is 32. */ + void setJitteringScale(float jitteringScale); + + /** Get the value used for jittering scale in the shader.*/ + float getJitteringScale() const { return _jitteringScale; } + + /** Set the texture unit that the jitter texture will be applied on.*/ + void setJitterTextureUnit(unsigned int jitterTextureUnit); + + /** Get the texture unit that the jitter texture will be applied on.*/ + unsigned int getJitterTextureUnit() const { return _jitterTextureUnit; } + + + /** Add a small bias to the z-value, this can reduce + * shadow acne problem. + * This is the same as calling setPolygonOffset(osg::Vec2(bias,0)); + * Suitable values are 0-0.005 + * Default is 0. */ + void setBias(float bias) { setPolygonOffset(osg::Vec2(bias,0)); } + + /** Return the bias value */ + float getBias() const { return getPolygonOffset().x(); } + + + protected: + virtual ~SoftShadowMap(void) {}; + + /** Create the managed Uniforms */ + void createUniforms(); + void createShaders(); + void initJittering(osg::StateSet *ss); + + osg::ref_ptr _softnessWidthUniform; + osg::ref_ptr _jitteringScaleUniform; + float _softnessWidth; + float _jitteringScale; + unsigned int _jitterTextureUnit; + + + +}; + +} + +#endif diff --git a/libs/include/android/osgShadow/StandardShadowMap b/libs/include/android/osgShadow/StandardShadowMap new file mode 100755 index 0000000..edf38ee --- /dev/null +++ b/libs/include/android/osgShadow/StandardShadowMap @@ -0,0 +1,200 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. + * + * ViewDependentShadow codes Copyright (C) 2008 Wojciech Lewandowski + * Thanks to to my company http://www.ai.com.pl for allowing me free this work. +*/ + +#ifndef OSGSHADOW_STANDARDSHADOWMAP +#define OSGSHADOW_STANDARDSHADOWMAP 1 + +#include + +namespace osgShadow { + +class OSGSHADOW_EXPORT StandardShadowMap : public DebugShadowMap +{ + public : + /** Convenient typedef used in definition of ViewData struct and methods */ + typedef StandardShadowMap ThisClass; + /** Convenient typedef used in definition of ViewData struct and methods */ + typedef DebugShadowMap BaseClass; + + /** Classic OSG constructor */ + StandardShadowMap(); + + /** Classic OSG cloning constructor */ + StandardShadowMap(const StandardShadowMap& ssm, + const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY); + + /** Declaration of standard OSG object methods */ + META_Object( osgShadow, StandardShadowMap ); + + void setBaseTextureUnit( unsigned int unit ) + { _baseTextureUnit = unit; dirty(); } + + unsigned int getBaseTextureUnit( void ) const + { return _baseTextureUnit; } + + void setShadowTextureUnit( unsigned int unit ) + { _shadowTextureUnit = unit; dirty(); } + + unsigned int getShadowTextureUnit( void ) const + { return _shadowTextureUnit; } + + // Texture Indices are changed by search and replace on shader source + // Carefully order these calls when changing both base and shadow indices + // In worst case when intend to swap indices + // one will have to call these methods more than once + // with one extra pass to change index to unused value to avoid + // unwanted superfluous replace: + // + // Example: Imagine we want to swap base(0) and shadow(1) indices: + // We have to do an extra step to make sure both do not end up as 1 + // + // // initialy change base to something else than 1 + // setBaseTextureCoordIndex( 100 ); + // // now search and replace all gl_TexCord[1] to gl_TexCord[0] + // setShadowTextureCoordIndex( 0 ); + // // finally change base from 100 to 0 + // setBaseTextureCoordIndex( 1 ); + + void setBaseTextureCoordIndex( unsigned int index ) + { updateTextureCoordIndices( _baseTextureCoordIndex, index ); + _baseTextureCoordIndex = index; } + + unsigned int getBaseTextureCoordIndex( void ) const + { return _baseTextureCoordIndex; } + + // Texture Indices are changed by search and replace on shader source + // Look at the comment above setBaseTextureCoordIndex + + void setShadowTextureCoordIndex( unsigned int index ) + { updateTextureCoordIndices( _shadowTextureCoordIndex, index ); + _shadowTextureCoordIndex = index; } + + unsigned int getShadowTextureCoordIndex( void ) const + { return _shadowTextureCoordIndex; } + + void setTextureSize( const osg::Vec2s& textureSize ) + { _textureSize = textureSize; dirty(); } + + const osg::Vec2s& getTextureSize() const + { return _textureSize; } + + void setLight( osg::Light* light ) + { _light = light; } + + osg::Light* getLight( void ) + { return _light.get(); } + + const osg::Light* getLight( void ) const + { return _light.get(); } + + osg::Shader * getShadowVertexShader() + { return _shadowVertexShader.get(); } + + osg::Shader * getShadowFragmentShader() + { return _shadowFragmentShader.get(); } + + osg::Shader * getMainVertexShader( ) + { return _mainVertexShader.get(); } + + osg::Shader * getMainFragmentShader( ) + { return _mainFragmentShader.get(); } + + void setShadowVertexShader( osg::Shader * shader ) + { _shadowVertexShader = shader; } + + void setShadowFragmentShader( osg::Shader * shader ) + { _shadowFragmentShader = shader; } + + void setMainVertexShader( osg::Shader * shader ) + { _mainVertexShader = shader; } + + void setMainFragmentShader( osg::Shader * shader ) + { _mainFragmentShader = shader; } + + protected: + /** Classic protected OSG destructor */ + virtual ~StandardShadowMap(void); + + virtual void updateTextureCoordIndices + ( unsigned int baseTexCoordIndex, unsigned int shadowTexCoordIndex ); + + virtual void searchAndReplaceShaderSource + ( osg::Shader*, std::string fromString, std::string toString ); + + osg::ref_ptr< osg::Shader > _mainVertexShader; + osg::ref_ptr< osg::Shader > _mainFragmentShader; + osg::ref_ptr< osg::Shader > _shadowVertexShader; + osg::ref_ptr< osg::Shader > _shadowFragmentShader; + + osg::ref_ptr< osg::Light > _light; + float _polygonOffsetFactor; + float _polygonOffsetUnits; + osg::Vec2s _textureSize; + unsigned int _baseTextureUnit; + unsigned int _shadowTextureUnit; + unsigned int _baseTextureCoordIndex; + unsigned int _shadowTextureCoordIndex; + + struct OSGSHADOW_EXPORT ViewData: public BaseClass::ViewData + { + osg::ref_ptr< osg::Light > * _lightPtr; + unsigned int * _baseTextureUnitPtr; + unsigned int * _shadowTextureUnitPtr; + + // ShadowMap texture is defined by base DebugShadowMap + // osg::ref_ptr _texture; + + // ShadowMap camera is defined by base DebugShadowMap + // osg::ref_ptr _camera; + + osg::ref_ptr _texgen; + osg::ref_ptr _stateset; + + virtual void init( ThisClass * st, osgUtil::CullVisitor * cv ); + + virtual void cull( ); + + virtual void aimShadowCastingCamera( + const osg::BoundingSphere &bounds, + const osg::Light *light, + const osg::Vec4 &worldLightPos, + const osg::Vec3 &worldLightDir, + const osg::Vec3 &worldLightUp = osg::Vec3(0,1,0) ); + + virtual void cullShadowReceivingScene( ); + + virtual void cullShadowCastingScene( ); + + virtual void addShadowReceivingTexGen( ); + + virtual const osg::Light* selectLight( osg::Vec4 &viewLightPos, + osg::Vec3 &viewLightDir ); + + virtual void aimShadowCastingCamera( const osg::Light *light, + const osg::Vec4 &worldLightPos, + const osg::Vec3 &worldLightDir, + const osg::Vec3 &worldLightUp + = osg::Vec3(0,1,0) ); + }; + + friend struct ViewData; + + META_ViewDependentShadowTechniqueData( ThisClass, ThisClass::ViewData ) +}; + +} // namespace osgShadow + +#endif diff --git a/libs/include/android/osgShadow/Version b/libs/include/android/osgShadow/Version new file mode 100755 index 0000000..2910d51 --- /dev/null +++ b/libs/include/android/osgShadow/Version @@ -0,0 +1,46 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGSHADOW_VERSION +#define OSGSHADOW_VERSION 1 + +#include + +extern "C" { + +/** + * osgShadowGetVersion() returns the library version number. + * Numbering convention : OpenSceneGraph-1.0 will return 1.0 from osgShadowGetVersion. + * + * This C function can be also used to check for the existence of the OpenSceneGraph + * library using autoconf and its m4 macro AC_CHECK_LIB. + * + * Here is the code to add to your configure.in: + \verbatim + # + # Check for the OpenSceneGraph (OSG) Shadow library + # + AC_CHECK_LIB(osg, osgShadowGetVersion, , + [AC_MSG_ERROR(OpenSceneGraph Shadow library not found. See http://www.openscenegraph.org)],) + \endverbatim +*/ +extern OSGSHADOW_EXPORT const char* osgShadowGetVersion(); + +/** + * osgShadowGetLibraryName() returns the library name in human friendly form. +*/ +extern OSGSHADOW_EXPORT const char* osgShadowGetLibraryName(); + +} + +#endif diff --git a/libs/include/android/osgShadow/ViewDependentShadowMap b/libs/include/android/osgShadow/ViewDependentShadowMap new file mode 100755 index 0000000..4ede756 --- /dev/null +++ b/libs/include/android/osgShadow/ViewDependentShadowMap @@ -0,0 +1,197 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2011 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGSHADOW_VIEWDEPENDENTSHADOWMAP +#define OSGSHADOW_VIEWDEPENDENTSHADOWMAP 1 + +#include +#include +#include +#include +#include + +#include + +namespace osgShadow { + +/** ViewDependentShadowMap provides an base implementation of view dependent shadow mapping techniques.*/ +class OSGSHADOW_EXPORT ViewDependentShadowMap : public ShadowTechnique +{ + public : + ViewDependentShadowMap(); + + ViewDependentShadowMap(const ViewDependentShadowMap& vdsm, const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY); + + META_Object(osgShadow, ViewDependentShadowMap); + + /** initialize the ShadowedScene and local cached data structures.*/ + virtual void init(); + + /** run the update traversal of the ShadowedScene and update any loca chached data structures.*/ + virtual void update(osg::NodeVisitor& nv); + + /** run the cull traversal of the ShadowedScene and set up the rendering for this ShadowTechnique.*/ + virtual void cull(osgUtil::CullVisitor& cv); + + /** Resize any per context GLObject buffers to specified size. */ + virtual void resizeGLObjectBuffers(unsigned int maxSize); + + /** If State is non-zero, this function releases any associated OpenGL objects for + * the specified graphics context. Otherwise, releases OpenGL objects + * for all graphics contexts. */ + virtual void releaseGLObjects(osg::State* = 0) const; + + /** Clean scene graph from any shadow technique specific nodes, state and drawables.*/ + virtual void cleanSceneGraph(); + + + struct OSGSHADOW_EXPORT Frustum + { + Frustum(osgUtil::CullVisitor* cv, double minZNear, double maxZFar); + + osg::Matrixd projectionMatrix; + osg::Matrixd modelViewMatrix; + + typedef std::vector Vertices; + Vertices corners; + + typedef std::vector Indices; + typedef std::vector Faces; + Faces faces; + + typedef std::vector Edges; + Edges edges; + + osg::Vec3d eye; + osg::Vec3d centerNearPlane; + osg::Vec3d centerFarPlane; + osg::Vec3d center; + osg::Vec3d frustumCenterLine; + }; + + // forward declare + class ViewDependentData; + + struct OSGSHADOW_EXPORT LightData : public osg::Referenced + { + LightData(ViewDependentData* vdd); + + virtual void setLightData(osg::RefMatrix* lm, const osg::Light* l, const osg::Matrixd& modelViewMatrix); + + ViewDependentData* _viewDependentData; + + osg::ref_ptr lightMatrix; + osg::ref_ptr light; + + osg::Vec4d lightPos; + osg::Vec3d lightPos3; + osg::Vec3d lightDir; + bool directionalLight; + + typedef std::vector ActiveTextureUnits; + ActiveTextureUnits textureUnits; + }; + + typedef std::list< osg::ref_ptr > LightDataList; + + struct OSGSHADOW_EXPORT ShadowData : public osg::Referenced + { + ShadowData(ViewDependentData* vdd); + + virtual void releaseGLObjects(osg::State* = 0) const; + + ViewDependentData* _viewDependentData; + + unsigned int _textureUnit; + osg::ref_ptr _texture; + osg::ref_ptr _texgen; + osg::ref_ptr _camera; + }; + + typedef std::list< osg::ref_ptr > ShadowDataList; + + + class OSGSHADOW_EXPORT ViewDependentData : public osg::Referenced + { + public: + ViewDependentData(ViewDependentShadowMap* vdsm); + + const ViewDependentShadowMap* getViewDependentShadowMap() const { return _viewDependentShadowMap; } + + LightDataList& getLightDataList() { return _lightDataList; } + + ShadowDataList& getShadowDataList() { return _shadowDataList; } + + osg::StateSet* getStateSet() { return _stateset.get(); } + + virtual void releaseGLObjects(osg::State* = 0) const; + + protected: + virtual ~ViewDependentData() {} + + ViewDependentShadowMap* _viewDependentShadowMap; + + osg::ref_ptr _stateset; + + LightDataList _lightDataList; + ShadowDataList _shadowDataList; + }; + + virtual ViewDependentData* createViewDependentData(osgUtil::CullVisitor* cv); + + ViewDependentData* getViewDependentData(osgUtil::CullVisitor* cv); + + + + virtual void createShaders(); + + virtual bool selectActiveLights(osgUtil::CullVisitor* cv, ViewDependentData* vdd) const; + + virtual osg::Polytope computeLightViewFrustumPolytope(Frustum& frustum, LightData& positionedLight); + + virtual bool computeShadowCameraSettings(Frustum& frustum, LightData& positionedLight, osg::Matrixd& projectionMatrix, osg::Matrixd& viewMatrix); + + virtual bool adjustPerspectiveShadowMapCameraSettings(osgUtil::RenderStage* renderStage, Frustum& frustum, LightData& positionedLight, osg::Camera* camera); + + virtual bool assignTexGenSettings(osgUtil::CullVisitor* cv, osg::Camera* camera, unsigned int textureUnit, osg::TexGen* texgen); + + virtual void cullShadowReceivingScene(osgUtil::CullVisitor* cv) const; + + virtual void cullShadowCastingScene(osgUtil::CullVisitor* cv, osg::Camera* camera) const; + + virtual osg::StateSet* selectStateSetForRenderingShadow(ViewDependentData& vdd) const; + + +protected: + virtual ~ViewDependentShadowMap(); + + typedef std::map< osgUtil::CullVisitor*, osg::ref_ptr > ViewDependentDataMap; + mutable OpenThreads::Mutex _viewDependentDataMapMutex; + ViewDependentDataMap _viewDependentDataMap; + + osg::ref_ptr _shadowRecievingPlaceholderStateSet; + + osg::ref_ptr _shadowCastingStateSet; + osg::ref_ptr _polygonOffset; + osg::ref_ptr _fallbackBaseTexture; + osg::ref_ptr _fallbackShadowMapTexture; + + typedef std::vector< osg::ref_ptr > Uniforms; + mutable OpenThreads::Mutex _accessUnfiromsAndProgramMutex; + Uniforms _uniforms; + osg::ref_ptr _program; +}; + +} + +#endif diff --git a/libs/include/android/osgShadow/ViewDependentShadowTechnique b/libs/include/android/osgShadow/ViewDependentShadowTechnique new file mode 100755 index 0000000..6be80fe --- /dev/null +++ b/libs/include/android/osgShadow/ViewDependentShadowTechnique @@ -0,0 +1,232 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. + * + * ViewDependentShadow codes Copyright (C) 2008 Wojciech Lewandowski + * Thanks to to my company http://www.ai.com.pl for allowing me free this work. +*/ + +#ifndef OSGSHADOW_VIEWDEPENDENTSHADOWTECHINIQUE +#define OSGSHADOW_VIEWDEPENDENTSHADOWTECHINIQUE 1 + +#include +#include +#include + +namespace osgShadow { +/** + META_ViewDependentShadowTechniqueData macro defines initViewDependentData + method used by derived shadow techniques to initialize their specific + ViewData objects. initViewDependentData will be called from + ViewDependentShadowTechnique base class to init derived class +*/ +#define META_ViewDependentShadowTechniqueData( ShadowTechnique, TechniqueData )\ +virtual ViewDependentShadowTechnique::ViewData * initViewDependentData \ +( osgUtil::CullVisitor *cv, ViewDependentShadowTechnique::ViewData * vd ) \ +{ \ + TechniqueData* td = dynamic_cast( vd ); \ + if ( !td ) td = new TechniqueData; \ + td->init( this, cv ); \ + return td; \ +} + +/** + ViewDependentShadowTechnique is a base class for all + View Dependent Shadow techniques. It defines fundamental object structure + and methods to manage separate shadow resources for each view of the scene. + By view we understand osg::View or SceneView instance and their associated + Camera. Typical osg application has one or more such views. View Dependent + Shadow techniques manage shadow generation for them. + + View Dependent Shadow techniques are used to optimize shadow algorithms for + part of the scene seen on the view. If rest of the scene is behind view + frustum, there is no sense in computing shadows for it. Since in practice we + often use 3d databases extending far beyond current camera frustum View + Dependent Shadow approach may produce much better shadows. + + The other goal is to provide framework for thread safe rendering of + the shadows. It allows to use shadows with different OSG threading models. + + Conceptually ViewDependentShadowTechnique is similar to osgSim::OverlayNode. + Its a container class for number of ViewData (or ViewData derived) objects + doing actual shadow work for each of the scene views. + + But ViewDependentShadowTechnique is intended as foundation layer for all + derived classes so in some way it extends osgSim::OverlayNode approach a bit. + + HOW IT WORKS: + + ViewDependendentShadowTechnique is derived from osgShadow::ShadowTechnique + and as such overrides virtual methods of osgShadow::ShadowTechnique. + But most of the shadow dirty work is done by ViewData objects, + ViewDependendentShadowTechnique::cull is the only osgShadow::ShadowTechnique + method where ViewDependendentShadowTechnique does something significant: + + What ViewDependentShadowTechnique::cull( CullVisitor & cv ) does ? + It identifies View. CullVisitor ptr is used as View identificator. + In practice we do not check and interpret what are actual Views and SceneViews + set up by application. We focus on Camera and CullVisitors as a identificators + of views. We can safely do this because each such view will have associated + unique CullVisitor used to cull the scene in every frame. + + Based on CullVisitor ptr passed to cull method, associated Technique::ViewData + object is created (if neccessary) and then seleced. Then control is passed to + this ViewData object. So, each view has its associated unique ViewData + (or derived) object performing dirty work of shadow resources management and + shadow generation for the view. + + To support creation of classes derived from ViewDependentShadowTechnique it + was neccessary to provide mechanism to override ViewData and allow for + initialization of new derived ViewData objects. Creation and initialization + is performed when ViewDependendentShadowTechnique::cull gets called with + CullVistor ptr which does not yet have associated ViewData object. When it + happens, virtual initViewDependentData method is called to give + derived techniques a chance to allocate and iniitalize its specific + resources as new ViewData derived instance. In practice initViewDependentData + in derived techniques should look the same as in base class so as a convenience + it was defined as META_ViewDependentShadowTechnique macro. Derived techniques + use this macro to override initViewDependentData method for their usage. + + After ViewData derived object is construted and selected, control is passed + to this object by call to virtual ViewData::cull method. The rest of work + is the done by this object. ViewDependentShadowTechnique::ViewData is intended + as a base class so it does nothing. In practice the rest of dirty work will + do new ViewData classes implemented in derived techniques. +*/ +class OSGSHADOW_EXPORT ViewDependentShadowTechnique + : public osgShadow::ShadowTechnique +{ + public: + /** + osgShadow::ShadowTechnique equivalent methods for view dependent techniques + */ + + /** Classic OSG constructor */ + ViewDependentShadowTechnique( void ); + + /** Classic OSG cloning constructor */ + ViewDependentShadowTechnique( + const ViewDependentShadowTechnique& vdst, + const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY ); + + + /** Declaration of standard OSG object methods */ + META_Object( osgShadow, ViewDependentShadowTechnique ); + + /** Dirty view data bits and force update of view data resources */ + virtual void dirty(); + + /** Initialize the ShadowedScene and some data structures.*/ + virtual void init(); + + /** Run the update traversal of the ShadowedScene and update any local cached data structures.*/ + virtual void update(osg::NodeVisitor& nv); + + /** Run the cull traversal of the ShadowedScene and set up the rendering for this ShadowTechnique.*/ + virtual void cull(osgUtil::CullVisitor& cv); + + /** Clean scene graph from any shadow technique specific nodes, state and drawables.*/ + virtual void cleanSceneGraph(); + + /** Traverse shadow scene graph.*/ + virtual void traverse(osg::NodeVisitor& nv); + + protected: + /** Classic protected OSG destructor */ + ~ViewDependentShadowTechnique( void ); + + /** + Base container class for view dependent shadow resources. + Techniques based on ViewDependentShadowTechnique will usually define + similar struct and derive it from ViewData to contain their specufic resources. + */ + struct OSGSHADOW_EXPORT ViewData: public osg::Referenced + { + virtual const char* className() const { return "ViewData"; } + + /** + Method called upon ViewData instance to initialize internal variables + */ + virtual void init + ( ViewDependentShadowTechnique *st, osgUtil::CullVisitor *cv ); + + /** + Method called by ViewDependentShadowTechnique to allow ViewData + do the hard work computing shadows for its associated view + */ + virtual void cull(); + + /** + Dirty is called by parent ViewDependentShadowTechnique to force + update of resources after some of them were modified in parent technique + */ + virtual void dirty( bool flag ); + + /** + Simple constructor zeroing all variables. + */ + ViewData(): _dirty( true ), _cv( NULL ), _st( NULL ) { }; + + /** + Mutex used to guard _dirty flag from override in case when parent technique calls + dirty() simultaneously with ViewData while it is updating resources inside init method. + */ + OpenThreads::Mutex _mutex; + + /** + Dirty flag tells this instance to update its resources + */ + bool _dirty; + + /** + View's CullVisitor associated with this ViewData instance + */ + osg::observer_ptr< osgUtil::CullVisitor > _cv; + + /** + Parent ViewDependentShadowTechnique + */ + osg::observer_ptr< ViewDependentShadowTechnique > _st; + + }; + + /** + Map of view dependent data per view cull visitor (CVs are used as indices) + ViewDependentShadowTechnique uses this map to find VieData for each cull vitior + */ + + typedef std::map< osg::ref_ptr< osgUtil::CullVisitor >, + osg::ref_ptr< ViewData > > ViewDataMap; + + ViewDataMap _viewDataMap; + + + /** + Mutex used to serialize accesses to ViewDataMap + */ + OpenThreads::Mutex _viewDataMapMutex; + + /** Return view dependent data for the cull visitor */ + virtual ViewDependentShadowTechnique::ViewData * getViewDependentData( osgUtil::CullVisitor * cv ); + + /** Define view dependent data for the cull visitor */ + virtual void setViewDependentData( osgUtil::CullVisitor * cv, ViewDependentShadowTechnique::ViewData * data ); + + /** + Declare standard initViewDependentData method. + */ + META_ViewDependentShadowTechniqueData( ViewDependentShadowTechnique, ViewData ) +}; + + +} // namespace osgShadow + +#endif diff --git a/libs/include/android/osgSim/BlinkSequence b/libs/include/android/osgSim/BlinkSequence new file mode 100755 index 0000000..85b3c57 --- /dev/null +++ b/libs/include/android/osgSim/BlinkSequence @@ -0,0 +1,185 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGSIM_BLINKSQUENCE +#define OSGSIM_BLINKSQUENCE 1 + +#include + +#include +#include +#include +#include +#include + +#include + +namespace osgSim { + +/** sequence group which can be used to synchronize related blink sequences.*/ +class OSGSIM_EXPORT SequenceGroup : public osg::Object +{ + public: + + SequenceGroup(); + SequenceGroup(const SequenceGroup& bs, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY); + SequenceGroup(double baseTime); + + META_Object(osgSim,SequenceGroup); + + inline void setBaseTime( double t ) { _baseTime = t; } + inline double getBaseTime() const { return _baseTime; } + + double _baseTime; +}; + +class OSGSIM_EXPORT BlinkSequence : public osg::Object +{ + public: + + BlinkSequence(); + + BlinkSequence(const BlinkSequence& bs, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY); + + META_Object(osgSim,BlinkSequence); + + /** add a pulse of specified color and duration to the BlinkSequence.*/ + inline void addPulse(double length,const osg::Vec4& color); + + /** return the number of pulses. */ + inline int getNumPulses() const { return _pulseData.size(); } + + /** return the pulse data at position i. */ + inline void getPulse(unsigned int i, double& length,osg::Vec4& color) const; + + /** set pulse of specified color and duration to the BlinkSequence.*/ + inline void setPulse(unsigned int i,double length,const osg::Vec4& color); + + /** get the total pulse period of the blink sequence, which is equal to the sum of all the pulse periods.*/ + inline double getPulsePeriod() const { return _pulsePeriod; } + + /** set the sequence group which can be used to synchronize related blink sequences.*/ + inline void setSequenceGroup(SequenceGroup* sg) { _sequenceGroup = sg; } + + /** get the non const sequence group.*/ + inline SequenceGroup* getSequenceGroup() { return _sequenceGroup.get(); } + + /** get the const sequence group.*/ + inline const SequenceGroup* getSequenceGroup() const { return _sequenceGroup.get(); } + + /** set the phase shift of the blink sequence, this would be used to shift a sequence within a sequence group.*/ + inline void setPhaseShift(double ps) { _phaseShift = ps; } + + /** get the pahse shift.*/ + inline double getPhaseShift() const { return _phaseShift; } + + /** compute the local time clamped to this BlinkSequences period, and accounting for the phase shift and sequence group.*/ + inline double localTime(double time) const; + + /** compute the color for the time interval sepecifed. Averages the colors if the length is greater than the current pulse.*/ + inline osg::Vec4 color(double time,double length) const; + + + protected: + + + typedef std::pair IntervalColor; + typedef std::vector PulseData; + + double _pulsePeriod; + double _phaseShift; + PulseData _pulseData; + osg::ref_ptr _sequenceGroup; +}; + + +inline double BlinkSequence::localTime(double time) const +{ + if (_sequenceGroup.valid()) time -= _sequenceGroup->_baseTime; + time -= _phaseShift; + return time - floor(time/_pulsePeriod)*_pulsePeriod; +} + +inline void BlinkSequence::addPulse(double length,const osg::Vec4& color) +{ + _pulseData.push_back(IntervalColor(length,color)); + _pulsePeriod += length; +} + +inline void BlinkSequence::getPulse(unsigned int i, double& length, osg::Vec4& color) const +{ + const IntervalColor& ic = _pulseData[i]; + length = ic.first; + color = ic.second; +} + +inline void BlinkSequence::setPulse(unsigned int i,double length,const osg::Vec4& color) +{ + if( i >= _pulseData.size() ) return; + IntervalColor& ic = _pulseData[i]; + ic.first = length; + ic.second = color; +} + +inline osg::Vec4 BlinkSequence::color(double time,double length) const +{ + if (_pulseData.empty()) return osg::Vec4(1.0f,1.0f,1.0f,1.0f); + double lt = localTime(time); + PulseData::const_iterator itr = _pulseData.begin(); + + // find the first sample at this time point. + while (lt>itr->first) + { + lt -= itr->first; + ++itr; + if (itr==_pulseData.end()) itr = _pulseData.begin(); + } + + // if time interval fits inside the current pulse + // then simply return this pulses color value. + if (lt+length<=itr->first) + { + return itr->second; + } + + // time length exceeds the current pulse therefore + // we have to average out the pules to get the correct + // results... + + // accumulate final part of the first active pulses. + osg::Vec4 color(itr->second*(itr->first-lt)); + double len = length-(itr->first-lt); + ++itr; + if (itr==_pulseData.end()) itr = _pulseData.begin(); + + // accumulate all the whole pluses pulses. + while (len>itr->first) + { + len -= itr->first; + color += itr->second*itr->first; + ++itr; + if (itr==_pulseData.end()) itr = _pulseData.begin(); + } + + // add remaining part of the final pulse. + color += itr->second*len; + + // normalise the time waited color. + color /= length; + + return color; +} + +} + +#endif diff --git a/libs/include/android/osgSim/ColorRange b/libs/include/android/osgSim/ColorRange new file mode 100755 index 0000000..0f9fd2f --- /dev/null +++ b/libs/include/android/osgSim/ColorRange @@ -0,0 +1,66 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGSIM_COLORRANGE +#define OSGSIM_COLORRANGE 1 + +#include + +#include +#include + +namespace osgSim +{ +/** +ColorRange is a ScalarsToColors object to define a color spectrum +for a scalar range. An optional vector of colors may be passed in at +construction time. The range of colors will be mapped to the scalar range, +and interpolation between the colors will be performed as necessary. +By default, the color range will run Red-Yellow-Green-Cyan-Blue. +*/ +class OSGSIM_EXPORT ColorRange: public ScalarsToColors +{ +public: + + /** Constructor for a ColorRange with a default list of colors set to Red-Yellow-Green-Blue-Cyan + @param min minimum scalar value + @param max maximum scalar value + */ + ColorRange(float min, float max); + + /** Constructor for a ColorRange + @param min minimum scalar value + @param max maximum scalar value + @param colors optional range of colors, + */ + ColorRange(float min, float max, const std::vector& colors); + + /** Set the range of colors. */ + void setColors(const std::vector& colors); + + /** Get the range of colors */ + const std::vector& getColors() const { return _colors; } + + /** Get the color for a given scalar value. */ + osg::Vec4 getColor(float scalar) const; + +private: + + // Default assignment and copy construction are OK. + + std::vector _colors; +}; + +} + +#endif diff --git a/libs/include/android/osgSim/DOFTransform b/libs/include/android/osgSim/DOFTransform new file mode 100755 index 0000000..ece565c --- /dev/null +++ b/libs/include/android/osgSim/DOFTransform @@ -0,0 +1,175 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGSIM_DOFTRANSFORM +#define OSGSIM_DOFTRANSFORM 1 + +//base class: +#include + +#include + +namespace osgSim { + +/** DOFTransform - encapsulates Multigen DOF behavior*/ +class OSGSIM_EXPORT DOFTransform : public osg::Transform +{ + public: + /** constructor*/ + DOFTransform(); + + /**copy constructor*/ + DOFTransform(const DOFTransform& dof, const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY); + + META_Node(osgSim, DOFTransform); + + virtual void traverse(osg::NodeVisitor& nv); + + + void setMinHPR(const osg::Vec3& hpr) { _minHPR = hpr;} + const osg::Vec3& getMinHPR() const { return _minHPR;} + + void setMaxHPR(const osg::Vec3& hpr) {_maxHPR = hpr;} + const osg::Vec3& getMaxHPR() const { return _maxHPR;} + + void setIncrementHPR(const osg::Vec3& hpr) {_incrementHPR = hpr;} + const osg::Vec3& getIncrementHPR() const { return _incrementHPR;} + + void setCurrentHPR(const osg::Vec3& hpr) {_currentHPR = hpr; dirtyBound(); } + const osg::Vec3& getCurrentHPR() const {return _currentHPR;} + + void updateCurrentHPR(const osg::Vec3& hpr); + + + void setMinTranslate(const osg::Vec3& translate) {_minTranslate = translate; } + const osg::Vec3& getMinTranslate() const { return _minTranslate;} + + void setMaxTranslate(const osg::Vec3& translate) {_maxTranslate = translate; } + const osg::Vec3& getMaxTranslate() const { return _maxTranslate;} + + void setIncrementTranslate(const osg::Vec3& translate) { _incrementTranslate = translate; } + const osg::Vec3& getIncrementTranslate() const { return _incrementTranslate;} + + void setCurrentTranslate(const osg::Vec3& translate){ _currentTranslate = translate; dirtyBound(); } + inline const osg::Vec3& getCurrentTranslate() const { return _currentTranslate;} + + void updateCurrentTranslate(const osg::Vec3& translate); + + + void setMinScale(const osg::Vec3& scale) { _minScale = scale;} + const osg::Vec3& getMinScale() const { return _minScale;} + + void setMaxScale(const osg::Vec3& scale) { _maxScale = scale;} + const osg::Vec3& getMaxScale() const { return _maxScale;} + + void setIncrementScale(const osg::Vec3& scale) { _incrementScale = scale;} + const osg::Vec3& getIncrementScale() const { return _incrementScale;} + + void setCurrentScale(const osg::Vec3& scale) { _currentScale = scale; dirtyBound(); } + inline const osg::Vec3& getCurrentScale() const { return _currentScale;} + + void updateCurrentScale(const osg::Vec3& scale); + + + void setPutMatrix(const osg::Matrix& put) { _Put = put; dirtyBound(); } + inline const osg::Matrix& getPutMatrix() const {return _Put;} + + void setInversePutMatrix(const osg::Matrix& inversePut) { _inversePut = inversePut; dirtyBound(); } + inline const osg::Matrix& getInversePutMatrix() const {return _inversePut;} + + void setLimitationFlags(unsigned long flags) { _limitationFlags = flags;} + inline unsigned long getLimitationFlags() const {return _limitationFlags;} + + enum MultOrder + { + PRH, + PHR, + HPR, + HRP, + RPH, + RHP + }; + + void setHPRMultOrder(MultOrder order) { _multOrder = order; } + inline MultOrder getHPRMultOrder() const { return _multOrder;} + + void setAnimationOn(bool do_animate); + inline bool getAnimationOn() const { return _animationOn; } + + void animate(float deltaTime); + + virtual bool computeLocalToWorldMatrix(osg::Matrix& matrix,osg::NodeVisitor* nv) const; + + virtual bool computeWorldToLocalMatrix(osg::Matrix& matrix,osg::NodeVisitor* nv) const; + + protected: + + virtual ~DOFTransform() {} + + unsigned int _previousTraversalNumber; + double _previousTime; + + osg::Vec3 _minHPR; + osg::Vec3 _maxHPR; + osg::Vec3 _currentHPR; + osg::Vec3 _incrementHPR; + + osg::Vec3 _minTranslate; + osg::Vec3 _maxTranslate; + osg::Vec3 _currentTranslate; + osg::Vec3 _incrementTranslate; + + osg::Vec3 _minScale; + osg::Vec3 _maxScale; + osg::Vec3 _currentScale; + osg::Vec3 _incrementScale; + + osg::Matrix _Put; + osg::Matrix _inversePut; + + unsigned long _limitationFlags; + /* bits from left to right + 0 = x translation limited (2^31) + 1 = y translation limited (2^30) + 2 = z translation limited (2^29) + 3 = pitch limited (2^28) + 4 = roll limited (2^27) + 5 = yaw limited (2^26) + 6 = x scale limited (2^25) + 7 = y scale limited (2^24) + 8 = z scale limited (2^23) + + else reserved + */ + + bool _animationOn; + /** flags indicating whether value is incerasing or decreasing in animation + bits form right to left, 1 means increasing while 0 is decreasing + 0 = x translation + 1 = y translation + 2 = z translation + 3 = pitch + 4 = roll + 5 = yaw + 6 = x scale + 7 = y scale + 8 = z scale + */ + unsigned short _increasingFlags; + + MultOrder _multOrder; + + }; + +} +#endif diff --git a/libs/include/android/osgSim/ElevationSlice b/libs/include/android/osgSim/ElevationSlice new file mode 100755 index 0000000..0d634a7 --- /dev/null +++ b/libs/include/android/osgSim/ElevationSlice @@ -0,0 +1,101 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGSIM_ELEVATIONSLICE +#define OSGSIM_ELEVATIONSLICE 1 + +#include + +// include so we can get access to the DatabaseCacheReadCallback +#include + +namespace osgSim { + +/** Helper class for setting up and acquiring height above terrain intersections with terrain. + * By default assigns a osgSim::DatabaseCacheReadCallback that enables automatic loading + * of external PagedLOD tiles to ensure that the highest level of detail is used in intersections. + * This automatic loading of tiles is done by the intersection traversal that is done within + * the computeIntersections(..) method, so can result in long intersection times when external + * tiles have to be loaded. + * The external loading of tiles can be disabled by removing the read callback, this is done by + * calling the setDatabaseCacheReadCallback(DatabaseCacheReadCallback*) method with a value of 0.*/ +class OSGSIM_EXPORT ElevationSlice +{ + public : + + + ElevationSlice(); + + /** Set the start point of the slice.*/ + void setStartPoint(const osg::Vec3d& startPoint) { _startPoint = startPoint; } + + /** Get the start point of the slice.*/ + const osg::Vec3d& getStartPoint() const { return _startPoint; } + + /** Set the end point of the slice.*/ + void setEndPoint(const osg::Vec3d& endPoint) { _endPoint = endPoint; } + + /** Get the end point of the slice.*/ + const osg::Vec3d& getEndPoint() const { return _endPoint; } + + + typedef std::vector Vec3dList; + + /** Get the intersections in the form of a vector of Vec3d. */ + const Vec3dList& getIntersections() const { return _intersections; } + + typedef std::pair DistanceHeight; + typedef std::vector DistanceHeightList; + + /** Get the intersections in the form a vector of pair representing distance along the slice and height. */ + const DistanceHeightList& getDistanceHeightIntersections() const { return _distanceHeightIntersections; } + + + /** Compute the intersections with the specified scene graph, the results are stored in vectors of Vec3d. + * Note, if the topmost node is a CoordinateSystemNode then the input points are assumed to be geocentric, + * with the up vector defined by the EllipsoidModel attached to the CoordinateSystemNode. + * If the topmost node is not a CoordinateSystemNode then a local coordinates frame is assumed, with a local up vector. */ + void computeIntersections(osg::Node* scene, osg::Node::NodeMask traversalMask=0xffffffff); + + /** Compute the vertical distance between the specified scene graph and a single HAT point.*/ + static Vec3dList computeElevationSlice(osg::Node* scene, const osg::Vec3d& startPoint, const osg::Vec3d& endPoint, osg::Node::NodeMask traversalMask=0xffffffff); + + + /** Clear the database cache.*/ + void clearDatabaseCache() { if (_dcrc.valid()) _dcrc->clearDatabaseCache(); } + + /** Set the ReadCallback that does the reading of external PagedLOD models, and caching of loaded subgraphs. + * Note, if you have multiple LineOfSight or ElevationSlice objects in use at one time then you should share a single + * DatabaseCacheReadCallback between all of them. */ + void setDatabaseCacheReadCallback(DatabaseCacheReadCallback* dcrc); + + /** Get the ReadCallback that does the reading of external PagedLOD models, and caching of loaded subgraphs.*/ + DatabaseCacheReadCallback* getDatabaseCacheReadCallback() { return _dcrc.get(); } + + protected : + + + osg::Vec3d _startPoint; + osg::Vec3d _endPoint; + Vec3dList _intersections; + DistanceHeightList _distanceHeightIntersections; + + osg::ref_ptr _dcrc; + osgUtil::IntersectionVisitor _intersectionVisitor; + + +}; + +} + +#endif diff --git a/libs/include/android/osgSim/Export b/libs/include/android/osgSim/Export new file mode 100755 index 0000000..9732307 --- /dev/null +++ b/libs/include/android/osgSim/Export @@ -0,0 +1,59 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGSIM_EXPORT_ +#define OSGSIM_EXPORT_ 1 + +#include + +#if defined(_MSC_VER) && defined(OSG_DISABLE_MSVC_WARNINGS) + #pragma warning( disable : 4244 ) + #pragma warning( disable : 4251 ) + #pragma warning( disable : 4275 ) + #pragma warning( disable : 4786 ) + #pragma warning( disable : 4290 ) + #pragma warning( disable : 4305 ) + #pragma warning( disable : 4996 ) +#endif + +#if defined(_MSC_VER) || defined(__CYGWIN__) || defined(__MINGW32__) || defined( __BCPLUSPLUS__) || defined( __MWERKS__) + # if defined( OSG_LIBRARY_STATIC ) + # define OSGSIM_EXPORT + # elif defined( OSGSIM_LIBRARY ) + # define OSGSIM_EXPORT __declspec(dllexport) + # else + # define OSGSIM_EXPORT __declspec(dllimport) + # endif +#else + # define OSGSIM_EXPORT +#endif + +/* Define NULL pointer value */ + +#ifndef NULL +#ifdef __cplusplus +#define NULL 0 +#else +#define NULL ((void *)0) +#endif +#endif + +/** + +\namespace osgSim + +The osgSim library is a NodeKit that extends the core scene graph to support nodes and drawables that specific to the visual simulation, such +a navigational light point support and OpenFlight style degrees of freedom transform. +*/ + +#endif diff --git a/libs/include/android/osgSim/GeographicLocation b/libs/include/android/osgSim/GeographicLocation new file mode 100755 index 0000000..e53dd21 --- /dev/null +++ b/libs/include/android/osgSim/GeographicLocation @@ -0,0 +1,87 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2004 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGSIM_GEOGRAPHICLOCATION +#define OSGSIM_GEOGRAPHICLOCATION 1 + +#include +#include + +#include + +namespace osgSim { + +/** Stores a double precision geographic location, latitude and longitude. + Derived from Referenced so it can be used as an osg::Object userData. +*/ + +class GeographicLocation : public osg::Referenced +{ + public: + + GeographicLocation() { _v[0]=0.; _v[1]=0.; } + GeographicLocation( double lat, double lon ) { _v[0]=lat; _v[1]=lon; } + + inline bool operator == ( const GeographicLocation& v) const { return _v[0]==v._v[0] && _v[1]==v._v[1]; } + inline bool operator != ( const GeographicLocation& v) const { return _v[0]!=v._v[0] || _v[1]!=v._v[1]; } + inline bool operator < ( const GeographicLocation& v) const + { + if (_v[0]v._v[0]) return false; + else if (_v[1] + +// include so we can get access to the DatabaseCacheReadCallback +#include + +namespace osgSim { + +/** Helper class for setting up and acquiring height above terrain intersections with terrain. + * By default assigns a osgSim::DatabaseCacheReadCallback that enables automatic loading + * of external PagedLOD tiles to ensure that the highest level of detail is used in intersections. + * This automatic loading of tiles is done by the intersection traversal that is done within + * the computeIntersections(..) method, so can result in long intersection times when external + * tiles have to be loaded. + * The external loading of tiles can be disabled by removing the read callback, this is done by + * calling the setDatabaseCacheReadCallback(DatabaseCacheReadCallback*) method with a value of 0.*/ +class OSGSIM_EXPORT HeightAboveTerrain +{ + public : + + + HeightAboveTerrain(); + + + /** Clear the internal HAT List so it contains no height above terrain tests.*/ + void clear(); + + /** Add a height above terrain test point in the CoordinateFrame.*/ + unsigned int addPoint(const osg::Vec3d& point); + + /** Get the number of height above terrain tests.*/ + unsigned int getNumPoints() const { return _HATList.size(); } + + /** Set the source point of single height above terrain test.*/ + void setPoint(unsigned int i, const osg::Vec3d& point) { _HATList[i]._point = point; } + + /** Get the source point of single height above terrain test.*/ + const osg::Vec3d& getPoint(unsigned int i) const { return _HATList[i]._point; } + + /** Get the intersection height for a single height above terrain test. + * Note, you must call computeIntersections(..) before you can query the HeightAboveTerrain. + * If no intersections are found then height returned will be the height above mean sea level. */ + double getHeightAboveTerrain(unsigned int i) const { return _HATList[i]._hat; } + + /** Set the lowest height that the should be tested for. + * Defaults to -1000, i.e. 1000m below mean sea level. */ + void setLowestHeight(double lowestHeight) { _lowestHeight = lowestHeight; } + + /** Get the lowest height that the should be tested for.*/ + double getLowestHeight() const { return _lowestHeight; } + + /** Compute the HAT intersections with the specified scene graph. + * The results are all stored in the form of a single height above terrain value per HAT test. + * Note, if the topmost node is a CoordinateSystemNode then the input points are assumed to be geocentric, + * with the up vector defined by the EllipsoidModel attached to the CoordinateSystemNode. + * If the topmost node is not a CoordinateSystemNode then a local coordinates frame is assumed, with a local up vector. */ + void computeIntersections(osg::Node* scene, osg::Node::NodeMask traversalMask=0xffffffff); + + /** Compute the vertical distance between the specified scene graph and a single HAT point. */ + static double computeHeightAboveTerrain(osg::Node* scene, const osg::Vec3d& point, osg::Node::NodeMask traversalMask=0xffffffff); + + + /** Clear the database cache.*/ + void clearDatabaseCache() { if (_dcrc.valid()) _dcrc->clearDatabaseCache(); } + + /** Set the ReadCallback that does the reading of external PagedLOD models, and caching of loaded subgraphs. + * Note, if you have multiple LineOfSight or HeightAboveTerrain objects in use at one time then you should share a single + * DatabaseCacheReadCallback between all of them. */ + void setDatabaseCacheReadCallback(DatabaseCacheReadCallback* dcrc); + + /** Get the ReadCallback that does the reading of external PagedLOD models, and caching of loaded subgraphs.*/ + DatabaseCacheReadCallback* getDatabaseCacheReadCallback() { return _dcrc.get(); } + + protected : + + struct HAT + { + HAT(const osg::Vec3d& point): + _point(point), + _hat(0.0) {} + + osg::Vec3d _point; + double _hat; + }; + + typedef std::vector HATList; + + + double _lowestHeight; + HATList _HATList; + + + osg::ref_ptr _dcrc; + osgUtil::IntersectionVisitor _intersectionVisitor; + + +}; + +} + +#endif diff --git a/libs/include/android/osgSim/Impostor b/libs/include/android/osgSim/Impostor new file mode 100755 index 0000000..c6eb0ed --- /dev/null +++ b/libs/include/android/osgSim/Impostor @@ -0,0 +1,121 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGSIM_IMPOSTOR +#define OSGSIM_IMPOSTOR 1 + +#include +#include + +#include + +#include + +namespace osgSim { + +/** Impostor - is a form of Level Of Detail group node which allows both switching + * between children depending on distance from eye point and image caching. + * + * The principle behind Imposters is that they cache an image of real geometry and then the image is drawn + * in subsequent frames instead of the real geometry. It's a bit like a + * Billboard *but* is updated at runtime and w.r.t view point. By drawing + * just the texture mapped quad you can cut down scene complexity and + * improve performance. + * + * For more details have a look at: + * + * http://grail.cs.washington.edu/projects/hic/ + * + * The OSG doesn't implement exactly the same technique as above, but its + * should be a good starting place. The OSG's impostors are much less + * intrusive since you don't need to restructure your whole scene to use + * them. + * + * All you need to do to use Impostors is to set up the visible + * range values for each LOD child of the Impostor, as per osg::LOD, + * and set an Impostor threshold to tell the renderer at what distance + * the Impostor's image caching should cut in. The osg::CullVisitor + * automatically handles all the setting of pre-rendering stages to + * calculate the required ImpostorSprites (which encapsulates the image + * cache and quad), and updates them as the view point changes. If you + * use osg::SceneView/CullVisitor all the complexity of supporting + * Impostor will be nicely hidden away. + * + * TODO: + * Various improvements are planned for the Impostor- + * 1) Estimation of how many frames an ImpostorSprite will be reused, if + * it won't be used more often than a minimum threshold then do not create + * ImpostorSprite - use the real geometry. + * 2) Sharing of texture memory between ImpostorSprites. + * 3) Simple 3D geometry for ImpostorSprite's rather than Billboarding. + * 4) Shrinking of the ImpostorSprite size to more closely fit the underlying + * geometry. + */ +class OSGSIM_EXPORT Impostor : public osg::LOD +{ + public : + Impostor(); + + Impostor(const Impostor& es, const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY): + osg::LOD(es,copyop), + _impostorThreshold(es._impostorThreshold) {} + + META_Node(osgSim, Impostor); + + virtual void traverse(osg::NodeVisitor& nv); + + typedef std::vector< osg::ref_ptr > ImpostorSpriteList; + + /** Set the Impostor threshold distance. + * For eye points further than this threshold the Imposter is used if appropriate, + * otherwise the LOD children as chosen as per a standard LOD node. + */ + inline void setImpostorThreshold(float distance) { _impostorThreshold = distance; } + + /* Get the Impostor threshold distance. */ + inline float getImpostorThreshold() const { return _impostorThreshold; } + + /** Set the Impostor threshold distance relative to the node's bounding + * sphere's radius. + */ + inline void setImpostorThresholdToBound(float ratio=1.0f) { _impostorThreshold = getBound().radius()*ratio; } + + /** Find the ImposterSprite which fits the current eye point best. */ + ImpostorSprite* findBestImpostorSprite(unsigned int contextID, const osg::Vec3& currLocalEyePoint) const; + + /** Add an ImpostorSprite to the Impostor. */ + void addImpostorSprite(unsigned int contextID, ImpostorSprite* is); + + /** Get the list of ImpostorSprites attached to this Impostor. */ + inline ImpostorSpriteList& getImpostorSpriteList(unsigned int contexID) { return _impostorSpriteListBuffer[contexID]; } + + /** Get a const list of ImpostorSprites attached to this const Impostor. */ + inline const ImpostorSpriteList& getImpostorSpriteList(unsigned int contexID) const { return _impostorSpriteListBuffer[contexID]; } + + virtual osg::BoundingSphere computeBound() const; + + protected : + + virtual ~Impostor() {} + + mutable osg::buffered_object _impostorSpriteListBuffer; + + ImpostorSprite* createImpostorSprite(osgUtil::CullVisitor* cv); + + float _impostorThreshold; + +}; + +} + +#endif diff --git a/libs/include/android/osgSim/ImpostorSprite b/libs/include/android/osgSim/ImpostorSprite new file mode 100755 index 0000000..d086c7a --- /dev/null +++ b/libs/include/android/osgSim/ImpostorSprite @@ -0,0 +1,241 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_ImpostorSprite +#define OSG_ImpostorSprite 1 + +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace osgSim { + +class Impostor; +class ImpostorSpriteManager; + +/** An ImposterSprite is a textured quad which is rendered in place of + * 3D geometry. The ImposterSprite is generated by rendering the original + * 3D geometry to a texture as an image cache. The ImpostorSprite is + * automatically generated by the osgUtil::CullVisitor so it not + * necessary to deal with it directly. +*/ +class OSGSIM_EXPORT ImpostorSprite : public osg::Drawable +{ + public: + + ImpostorSprite(); + + /** Clone an object of the same type as an ImpostorSprite. */ + virtual osg::Object* cloneType() const { return new ImpostorSprite(); } + + /** Clone on ImpostorSprite just returns a clone of type, + * since it is not appropriate to share data of an ImpostorSprite. + */ + virtual osg::Object* clone(const osg::CopyOp&) const { return new ImpostorSprite(); } + virtual bool isSameKindAs(const osg::Object* obj) const { return dynamic_cast(obj)!=NULL; } + virtual const char* libraryName() const { return "osgSim"; } + virtual const char* className() const { return "ImpostorSprite"; } + + /** Set the parent, which must be an Impostor. + * Unlike conventional Drawables, ImpostorSprites can only ever have + * one parent. + */ + void setParent(Impostor* parent) { _parent = parent; } + + /** Get the parent, which is an Impostor. */ + Impostor* getParent() { return _parent; } + + /** Get the const parent, which is an Impostor. */ + const Impostor* getParent() const { return _parent; } + + /** Set the eye point for when the ImpostorSprite was snapped. */ + inline void setStoredLocalEyePoint(const osg::Vec3& v) { _storedLocalEyePoint=v; } + + /** Get the eye point for when the ImpostorSprite was snapped. */ + inline const osg::Vec3& getStoredLocalEyePoint() const { return _storedLocalEyePoint; } + + /** Set the frame number for when the ImpostorSprite was last used in rendering. */ + inline void setLastFrameUsed(unsigned int frameNumber) { _lastFrameUsed = frameNumber; } + + /** Get the frame number for when the ImpostorSprite was last used in rendering. */ + inline unsigned int getLastFrameUsed() const { return _lastFrameUsed; } + + + /** Get the coordinates of the corners of the quad. + * Stored in the order, [0] - top_left, [1] - bottom_left, [2] - bottom_right, [3] - top_left. + */ + inline osg::Vec3* getCoords() { return _coords; } + + /** Get the const coordinates of the corners of the quad. */ + inline const osg::Vec3* getCoords() const { return _coords; } + + + + /** Get the texture coordinates of the corners of the quad. + * Stored in the order, [0] - top_left, [1] - bottom_left, [2] - bottom_right, [3] - top_left. + */ + inline osg::Vec2* getTexCoords() { return _texcoords; } + + /** Get the const texture coordinates of the corners of the quad. */ + inline const osg::Vec2* getTexCoords() const { return _texcoords; } + + /** Get the control coordinates of the corners of the quad. + * The control coordinates are the corners of the quad projected + * out onto the front face of bounding box which enclosed the impostor + * geometry when it was pre-rendered into the impostor sprite's texture. + * At the point of creation/or update of the impostor sprite the control + * coords will lie on top of the corners of the quad in screen space - with a pixel error + * of zero. Once the camera moves relative to the impostor sprite the + * control coords will no longer lie on top of the corners of the quad in + * screen space - a pixel error will have accumulated. This pixel error + * can then be used to determine whether the impostor needs to be updated. + * Stored in the order, [0] - top_left, [1] - bottom_left, [2] - bottom_right, [3] - top_left. + */ + inline osg::Vec3* getControlCoords() { return _controlcoords; } + + /** Get the const control coordinates of the corners of the quad. */ + inline const osg::Vec3* getControlCoords() const { return _controlcoords; } + + + /** Calculate the pixel error value for passing in the ModelViewProjectionWindow transform, + * which transform local coords into screen space. + */ + float calcPixelError(const osg::Matrix& MVPW) const; + + void setTexture(osg::Texture2D* tex,int s,int t); + osg::Texture2D* getTexture() { return _texture; } + const osg::Texture2D* getTexture() const { return _texture; } + + int s() const { return _s; } + int t() const { return _t; } + + /** Draw ImpostorSprite directly. */ + virtual void drawImplementation(osg::RenderInfo& renderInfo) const; + + /** Return true, osg::ImpostorSprite does support accept(Drawable::AttributeFunctor&). */ + virtual bool supports(const Drawable::AttributeFunctor&) const { return true; } + + /** Accept an Drawable::AttributeFunctor and call its methods to tell it about the internal attributes that this Drawable has. */ + virtual void accept(Drawable::AttributeFunctor& af); + + /** Return true, osg::ImpostorSprite does support accept(Drawable::ConstAttributeFunctor&). */ + virtual bool supports(const Drawable::ConstAttributeFunctor&) const { return true; } + + /** Accept a Drawable::ConstAttributeFunctor and call its methods to tell it about the internal attributes that this Drawable has. */ + virtual void accept(Drawable::ConstAttributeFunctor& af) const; + + /** Return true, osg::ImpostorSprite does support accept(PrimitiveFunctor&). */ + virtual bool supports(const osg::PrimitiveFunctor&) const { return true; } + + /** Accept a PrimtiveFunctor and call its methods to tell it about the internal primitives that this Drawable has. */ + virtual void accept(osg::PrimitiveFunctor& pf) const; + + // for debugging purposes. + osg::Vec4 _color; + + virtual osg::BoundingBox computeBound() const; + + /** Set the camera node to use for pre rendering the impostor sprite's texture.*/ + void setCamera(osg::Camera* camera) { _camera = camera; } + + /** Get the camera node to use for pre rendering the impostor sprite's texture.*/ + osg::Camera* getCamera() { return _camera.get(); } + + /** Get the const camera node to use for pre rendering the impostor sprite's texture.*/ + const osg::Camera* getCamera() const { return _camera.get(); } + + protected: + + ImpostorSprite(const ImpostorSprite&); + ImpostorSprite& operator = (const ImpostorSprite&) { return *this;} + + virtual ~ImpostorSprite(); + + Impostor* _parent; + + friend class osgSim::ImpostorSpriteManager; + + // camera node for doing the pre rendering. + osg::ref_ptr _camera; + + // support for a double linked list managed by the + // ImposotorSpriteManager. + ImpostorSpriteManager* _ism; + ImpostorSprite* _previous; + ImpostorSprite* _next; + + unsigned int _lastFrameUsed; + + osg::Vec3 _storedLocalEyePoint; + + osg::Vec3 _coords[4]; + osg::Vec2 _texcoords[4]; + osg::Vec3 _controlcoords[4]; + + osg::Texture2D* _texture; + int _s; + int _t; + + +}; + +/** Helper class for managing the reuse of ImpostorSprite resources. */ +class OSGSIM_EXPORT ImpostorSpriteManager : public osg::Referenced +{ + public: + + ImpostorSpriteManager(); + + bool empty() const { return _first==0; } + + ImpostorSprite* first() { return _first; } + + ImpostorSprite* last() { return _last; } + + void push_back(ImpostorSprite* is); + + void remove(ImpostorSprite* is); + + ImpostorSprite* createOrReuseImpostorSprite(int s,int t,unsigned int frameNumber); + + osg::StateSet* createOrReuseStateSet(); + + void reset(); + + protected: + + + ~ImpostorSpriteManager(); + + osg::ref_ptr _texenv; + osg::ref_ptr _alphafunc; + + ImpostorSprite* _first; + ImpostorSprite* _last; + + typedef std::vector< osg::ref_ptr > StateSetList; + StateSetList _stateSetList; + unsigned int _reuseStateSetIndex; + + +}; + +} + +#endif diff --git a/libs/include/android/osgSim/InsertImpostorsVisitor b/libs/include/android/osgSim/InsertImpostorsVisitor new file mode 100755 index 0000000..dec84b4 --- /dev/null +++ b/libs/include/android/osgSim/InsertImpostorsVisitor @@ -0,0 +1,68 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGSIM_INSERTIMPOSTORSVISITOR +#define OSGSIM_INSERTIMPOSTORSVISITOR + +#include +#include + +namespace osgSim { + +/** Insert impostor nodes into scene graph. + * For example of usage see examples/osgimpostor. + */ +class OSGSIM_EXPORT InsertImpostorsVisitor : public osg::NodeVisitor +{ + public: + + /** Default to traversing all children. */ + InsertImpostorsVisitor(); + + META_NodeVisitor(osgSim, InsertImpostorsVisitor) + + void setImpostorThresholdRatio(float ratio) { _impostorThresholdRatio = ratio; } + float getImpostorThresholdRatio() const { return _impostorThresholdRatio; } + + void setMaximumNumberOfNestedImpostors(unsigned int num) { _maximumNumNestedImpostors = num; } + unsigned int getMaximumNumberOfNestedImpostors() const { return _maximumNumNestedImpostors; } + + /** Empty visitor, make it ready for next traversal. */ + void reset(); + + virtual void apply(osg::Node& node); + + virtual void apply(osg::Group& node); + + virtual void apply(osg::LOD& node); + + /* Insert the required impostors into the scene graph. */ + void insertImpostors(); + + protected: + + typedef std::vector< osg::Group* > GroupList; + typedef std::vector< osg::LOD* > LODList; + + GroupList _groupList; + LODList _lodList; + + float _impostorThresholdRatio; + unsigned int _maximumNumNestedImpostors; + unsigned int _numNestedImpostors; + +}; + +} + +#endif diff --git a/libs/include/android/osgSim/LightPoint b/libs/include/android/osgSim/LightPoint new file mode 100755 index 0000000..f1d1621 --- /dev/null +++ b/libs/include/android/osgSim/LightPoint @@ -0,0 +1,72 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGSIM_LIGHTPOINT +#define OSGSIM_LIGHTPOINT 1 + +#include +#include +#include + +#include +#include +#include + +namespace osgSim { + + +class OSGSIM_EXPORT LightPoint +{ + public: + + enum BlendingMode + { + ADDITIVE, + BLENDED + }; + + LightPoint(); + + LightPoint(const osg::Vec3& position, + const osg::Vec4& color); + + LightPoint(bool on, + const osg::Vec3& position, + const osg::Vec4& color, + float intensity=1.0f, + float radius=1.0f, + Sector* sector=0, + BlinkSequence* blinkSequence=0, + BlendingMode blendingMode=BLENDED); + + + LightPoint(const LightPoint& lp); + + LightPoint& operator = (const LightPoint& lp); + + + bool _on; + osg::Vec3 _position; + osg::Vec4 _color; + float _intensity; + float _radius; + + osg::ref_ptr _sector; + osg::ref_ptr _blinkSequence; + + BlendingMode _blendingMode; +}; + +} + +#endif diff --git a/libs/include/android/osgSim/LightPointNode b/libs/include/android/osgSim/LightPointNode new file mode 100755 index 0000000..ca7cb88 --- /dev/null +++ b/libs/include/android/osgSim/LightPointNode @@ -0,0 +1,114 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGSIM_LIGHTPOINTNODE +#define OSGSIM_LIGHTPOINTNODE 1 + +#include +#include +#include + +#include +#include +#include +#include +#include + +#include +#include + +namespace osgSim { + + +class OSGSIM_EXPORT LightPointNode : public osg::Node +{ + public : + + typedef std::vector< LightPoint > LightPointList; + + LightPointNode(); + + /** Copy constructor using CopyOp to manage deep vs shallow copy.*/ + LightPointNode(const LightPointNode&,const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY); + + META_Node(osgSim,LightPointNode); + + virtual void traverse(osg::NodeVisitor& nv); + + + unsigned int getNumLightPoints() const { return _lightPointList.size(); } + + + unsigned int addLightPoint(const LightPoint& lp); + + void removeLightPoint(unsigned int pos); + + + LightPoint& getLightPoint(unsigned int pos) { return _lightPointList[pos]; } + + const LightPoint& getLightPoint(unsigned int pos) const { return _lightPointList[pos]; } + + + void setLightPointList(const LightPointList& lpl) { _lightPointList=lpl; } + + LightPointList& getLightPointList() { return _lightPointList; } + + const LightPointList& getLightPointList() const { return _lightPointList; } + + + void setMinPixelSize(float minPixelSize) { _minPixelSize = minPixelSize; } + + float getMinPixelSize() const { return _minPixelSize; } + + void setMaxPixelSize(float maxPixelSize) { _maxPixelSize = maxPixelSize; } + + float getMaxPixelSize() const { return _maxPixelSize; } + + void setMaxVisibleDistance2(float maxVisibleDistance2) { _maxVisibleDistance2 = maxVisibleDistance2; } + + float getMaxVisibleDistance2() const { return _maxVisibleDistance2; } + + void setLightPointSystem( osgSim::LightPointSystem* lps) { _lightSystem = lps; } + + osgSim::LightPointSystem* getLightPointSystem() { return _lightSystem.get(); } + const osgSim::LightPointSystem* getLightPointSystem() const { return _lightSystem.get(); } + + void setPointSprite(bool enable=true) { _pointSprites = enable; } + + bool getPointSprite() const { return _pointSprites; } + + virtual osg::BoundingSphere computeBound() const; + + protected: + + ~LightPointNode() {} + + // used to cache the bouding box of the lightpoints as a tighter + // view frustum check. + mutable osg::BoundingBox _bbox; + + LightPointList _lightPointList; + + float _minPixelSize; + float _maxPixelSize; + float _maxVisibleDistance2; + + osg::ref_ptr _lightSystem; + + bool _pointSprites; + +}; + +} + +#endif diff --git a/libs/include/android/osgSim/LightPointSystem b/libs/include/android/osgSim/LightPointSystem new file mode 100755 index 0000000..92bfbf4 --- /dev/null +++ b/libs/include/android/osgSim/LightPointSystem @@ -0,0 +1,63 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2004 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGSIM_LIGHTPOINTSYSTEM +#define OSGSIM_LIGHTPOINTSYSTEM 1 + +#include + + +namespace osgSim { + + +/* + * LightPointSYSTEM encapsulates animation and intensity state in a single object + * that can be shared by several osgSim::LightPointNodes, thereby allowing an + * application to efficiently control the animation/intensity state of + * several LightPointNodes. + */ +class LightPointSystem : public osg::Object +{ + public : + LightPointSystem() : _intensity( 1.f ), _animationState( ANIMATION_ON ) + { } + + /** Copy constructor using CopyOp to manage deep vs shallow copy.*/ + LightPointSystem( const LightPointSystem& lps, const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY ) : + osg::Object( lps, copyop ), _intensity( lps._intensity ), _animationState( lps._animationState ) + { } + + META_Object( osgSim, LightPointSystem ); + + typedef enum { + ANIMATION_ON, + ANIMATION_OFF, + ANIMATION_RANDOM + } AnimationState; + + void setIntensity( float intensity ) { _intensity = intensity; } + float getIntensity() const { return _intensity; } + + void setAnimationState( LightPointSystem::AnimationState state ) { _animationState = state; } + LightPointSystem::AnimationState getAnimationState() const { return _animationState; } + + protected: + ~LightPointSystem() {} + + float _intensity; + AnimationState _animationState; +}; + +} + +#endif diff --git a/libs/include/android/osgSim/LineOfSight b/libs/include/android/osgSim/LineOfSight new file mode 100755 index 0000000..c64a412 --- /dev/null +++ b/libs/include/android/osgSim/LineOfSight @@ -0,0 +1,129 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGSIM_LINEOFSIGHT +#define OSGSIM_LINEOFSIGHT 1 + +#include + +#include + +namespace osgSim { + +class OSGSIM_EXPORT DatabaseCacheReadCallback : public osgUtil::IntersectionVisitor::ReadCallback +{ + public: + DatabaseCacheReadCallback(); + + void setMaximumNumOfFilesToCache(unsigned int maxNumFilesToCache) { _maxNumFilesToCache = maxNumFilesToCache; } + unsigned int getMaximumNumOfFilesToCache() const { return _maxNumFilesToCache; } + + void clearDatabaseCache(); + + void pruneUnusedDatabaseCache(); + + virtual osg::Node* readNodeFile(const std::string& filename); + + protected: + + typedef std::map > FileNameSceneMap; + + unsigned int _maxNumFilesToCache; + OpenThreads::Mutex _mutex; + FileNameSceneMap _filenameSceneMap; +}; + +/** Helper class for setting up and acquiring line of sight intersections with terrain. + * By default assigns a osgSim::DatabaseCacheReadCallback that enables automatic loading + * of external PagedLOD tiles to ensure that the highest level of detail is used in intersections. + * This automatic loading of tiles is done by the intersection traversal that is done within + * the computeIntersections(..) method, so can result in long intersection times when external + * tiles have to be loaded. + * The external loading of tiles can be disabled by removing the read callback, this is done by + * calling the setDatabaseCacheReadCallback(DatabaseCacheReadCallback*) method with a value of 0.*/ +class OSGSIM_EXPORT LineOfSight +{ + public : + + LineOfSight(); + + /** Clear the internal LOS List so it contains no line of sight tests.*/ + void clear(); + + /** Add a line of sight test, consisting of start and end point. Returns the index number of the newly adding LOS test.*/ + unsigned int addLOS(const osg::Vec3d& start, const osg::Vec3d& end); + + /** Get the number of line of sight tests.*/ + unsigned int getNumLOS() const { return _LOSList.size(); } + + /** Set the start point of single line of sight test.*/ + void setStartPoint(unsigned int i, const osg::Vec3d& start) { _LOSList[i]._start = start; } + + /** Get the start point of single line of sight test.*/ + const osg::Vec3d& getStartPoint(unsigned int i) const { return _LOSList[i]._start; } + + /** Set the end point of single line of sight test.*/ + void setEndPoint(unsigned int i, const osg::Vec3d& end) { _LOSList[i]._end = end; } + + /** Get the end point of single line of sight test.*/ + const osg::Vec3d& getEndPoint(unsigned int i) const { return _LOSList[i]._end; } + + typedef std::vector Intersections; + + /** Get the intersection points for a single line of sight test.*/ + const Intersections& getIntersections(unsigned int i) const { return _LOSList[i]._intersections; } + + /** Compute the LOS intersections with the specified scene graph. + * The results are all stored in the form of Intersections list, one per LOS test.*/ + void computeIntersections(osg::Node* scene, osg::Node::NodeMask traversalMask=0xffffffff); + + /** Compute the intersection between the specified scene graph and a single LOS start,end pair. Returns an IntersectionList, of all the points intersected.*/ + static Intersections computeIntersections(osg::Node* scene, const osg::Vec3d& start, const osg::Vec3d& end, osg::Node::NodeMask traversalMask=0xffffffff); + + + /** Clear the database cache.*/ + void clearDatabaseCache() { if (_dcrc.valid()) _dcrc->clearDatabaseCache(); } + + /** Set the ReadCallback that does the reading of external PagedLOD models, and caching of loaded subgraphs. + * Note, if you have multiple LineOfSight or HeightAboveTerrain objects in use at one time then you should share a single + * DatabaseCacheReadCallback between all of them. */ + void setDatabaseCacheReadCallback(DatabaseCacheReadCallback* dcrc); + + /** Get the ReadCallback that does the reading of external PagedLOD models, and caching of loaded subgraphs.*/ + DatabaseCacheReadCallback* getDatabaseCacheReadCallback() { return _dcrc.get(); } + + protected : + + struct LOS + { + LOS(const osg::Vec3d& start, const osg::Vec3d& end): + _start(start), + _end(end) {} + + + osg::Vec3d _start; + osg::Vec3d _end; + Intersections _intersections; + }; + + typedef std::vector LOSList; + LOSList _LOSList; + + osg::ref_ptr _dcrc; + osgUtil::IntersectionVisitor _intersectionVisitor; + +}; + +} + +#endif diff --git a/libs/include/android/osgSim/MultiSwitch b/libs/include/android/osgSim/MultiSwitch new file mode 100755 index 0000000..fc4a8e1 --- /dev/null +++ b/libs/include/android/osgSim/MultiSwitch @@ -0,0 +1,107 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSG_MULTISWITCH +#define OSG_MULTISWITCH 1 + +#include +#include + +namespace osgSim { + +/** MultiSwitch is a Group node which allows switching between sets of selected children. + MultiSwitch is based on the OpenFlight switch behaviour. +*/ +class OSGSIM_EXPORT MultiSwitch : public osg::Group +{ + public : + + + MultiSwitch(); + + /** Copy constructor using CopyOp to manage deep vs shallow copy.*/ + MultiSwitch(const MultiSwitch&,const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY); + + META_Node(osgSim, MultiSwitch); + + virtual void traverse(osg::NodeVisitor& nv); + + void setNewChildDefaultValue(bool value) { _newChildDefaultValue = value; } + + bool getNewChildDefaultValue() const { return _newChildDefaultValue; } + + virtual bool addChild( osg::Node *child ); + + virtual bool insertChild( unsigned int index, osg::Node *child ); + + virtual bool removeChild( osg::Node *child ); + + void setValue(unsigned int switchSet, unsigned int pos,bool value); + + bool getValue(unsigned int switchSet, unsigned int pos) const; + + void setChildValue(const osg::Node* child,unsigned int switchSet, bool value); + + bool getChildValue(const osg::Node* child,unsigned int switchSet) const; + + /** Set all the children off (false), and set the new default child value to off (false).*/ + bool setAllChildrenOff(unsigned int switchSet); + + /** Set all the children on (true), and set the new default child value to on (true).*/ + bool setAllChildrenOn(unsigned int switchSet); + + /** Set a single child to be on, MultiSwitch off all other children.*/ + bool setSingleChildOn(unsigned int switchSet, unsigned int pos); + + /** Set which of the available switch set lists to use.*/ + void setActiveSwitchSet(unsigned int switchSet) { _activeSwitchSet = switchSet; } + + /** Get which of the available switch set lists to use.*/ + unsigned int getActiveSwitchSet() const { return _activeSwitchSet; } + + typedef std::vector ValueList; + typedef std::vector SwitchSetList; + typedef std::vector SwitchSetNameList; + + /** Set the compile set of different values.*/ + void setSwitchSetList(const SwitchSetList& switchSetList); + + /** Get the compile set of different values.*/ + const SwitchSetList& getSwitchSetList() const { return _values; } + + /** Set the a single set of different values for a particular switch set.*/ + void setValueList(unsigned int switchSet, const ValueList& values); + + /** Get the a single set of different values for a particular switch set.*/ + const ValueList& getValueList(unsigned int switchSet) const { return _values[switchSet]; } + + void setValueName(unsigned int switchSet, const std::string& name); + + const std::string& getValueName(unsigned int switchSet) const { return _valueNames[switchSet]; } + + protected : + + virtual ~MultiSwitch() {} + + void expandToEncompassSwitchSet(unsigned int switchSet); + + // this is effectively a list of bit mask. + bool _newChildDefaultValue; + unsigned int _activeSwitchSet; + SwitchSetList _values; + SwitchSetNameList _valueNames; +}; + +} + +#endif diff --git a/libs/include/android/osgSim/ObjectRecordData b/libs/include/android/osgSim/ObjectRecordData new file mode 100755 index 0000000..ea4c923 --- /dev/null +++ b/libs/include/android/osgSim/ObjectRecordData @@ -0,0 +1,73 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2004 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGSIM_OBJECTRECORDDATA +#define OSGSIM_OBJECTRECORDDATA 1 + +#include + +#include + +namespace osgSim { + +/** When the OpenFlight importer encounters an Object record, it stores + the data in one of these classes, and attaches the instance of the + class as UserData to the corresponding osgLLGroup node. +*/ + +class ObjectRecordData : public osg::Object +{ + public: + + ObjectRecordData() + : _flags( 0 ), + _relativePriority( 0 ), + _transparency( 0 ), + _effectID1( 0 ), + _effectID2( 0 ), + + _significance( 0 ) + {} + + ObjectRecordData( const ObjectRecordData& copy, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY ): + osg::Object(copy, copyop) + { + _flags = copy._flags; + _relativePriority = copy._relativePriority; + _transparency = copy._transparency; + _effectID1 = copy._effectID1; + _effectID2 = copy._effectID2; + _significance = copy._significance; + } + + META_Object( osgSim, ObjectRecordData ); + + static const unsigned int DONT_DISPLAY_IN_DAYLIGHT = 0x80000000u >> 0; + static const unsigned int DONT_DISPLAY_AT_DUSK = 0x80000000u >> 1; + static const unsigned int DONT_DISPLAY_AT_NIGHT = 0x80000000u >> 2; + static const unsigned int DONT_ILLUMINATE = 0x80000000u >> 3; + static const unsigned int FLAT_SHADED = 0x80000000u >> 4; + static const unsigned int GROUPS_SHADOW_OBJECT = 0x80000000u >> 5; + + unsigned int _flags; + short _relativePriority; + unsigned short _transparency; // 0=opaque, 65535=totally clear + short _effectID1; + short _effectID2; + short _significance; + +}; // end of class ObjectRecordData + +} // end of namespace osgSim + +#endif diff --git a/libs/include/android/osgSim/OverlayNode b/libs/include/android/osgSim/OverlayNode new file mode 100755 index 0000000..ff13fe3 --- /dev/null +++ b/libs/include/android/osgSim/OverlayNode @@ -0,0 +1,195 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGSIM_OVERLAYNODE +#define OSGSIM_OVERLAYNODE 1 + +#include +#include +#include +#include +#include + +#include + +#include + +namespace osgSim { + +/** OverlayNode is for creating texture overlays on scenes, with the overlay texture being generated + * by pre rendering an Overlay Subgraph to a texture, then projecting this resulting texture on the scene.*/ +class OSGSIM_EXPORT OverlayNode : public osg::Group +{ + public : + + enum OverlayTechnique + { + OBJECT_DEPENDENT_WITH_ORTHOGRAPHIC_OVERLAY, + VIEW_DEPENDENT_WITH_ORTHOGRAPHIC_OVERLAY, + VIEW_DEPENDENT_WITH_PERSPECTIVE_OVERLAY + }; + + OverlayNode(OverlayTechnique technique=OBJECT_DEPENDENT_WITH_ORTHOGRAPHIC_OVERLAY); + + OverlayNode(const OverlayNode& es, const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY); + + META_Node(osgSim, OverlayNode); + + virtual void traverse(osg::NodeVisitor& nv); + + + void setOverlayTechnique(OverlayTechnique technique); + OverlayTechnique getOverlayTechnique() const { return _overlayTechnique; } + + /** Set the implementation to be used when creating the overlay texture. */ + void setRenderTargetImplementation(osg::Camera::RenderTargetImplementation impl); + + /** Set the overlay subgraph which will be rendered to texture.*/ + void setOverlaySubgraph(osg::Node* node); + + /** Get the overlay subgraph which will be rendered to texture.*/ + osg::Node* getOverlaySubgraph() { return _overlaySubgraph.get(); } + + /** Get the const overlay subgraph which will be render to texture.*/ + const osg::Node* getOverlaySubgraph() const { return _overlaySubgraph.get(); } + + + /** Inform the OverlayNode that the overlay texture needs to be updated.*/ + void dirtyOverlayTexture(); + + /** Set whether the OverlayNode should update the overlay texture on every frame.*/ + void setContinuousUpdate(bool update) { _continuousUpdate = update; } + + /** Get whether the OverlayNode should update the overlay texture on every frame.*/ + bool getContinuousUpdate() const { return _continuousUpdate; } + + /** Set the base height that the overlay subgraph will be projected down to. + * Normally you'll set this to just below ground level, if you set it too high + * then the overlay texture can end up being clipped in certain viewing directions, + * while if its too low then there will be a limit to how close you can get to the + * terrain before pixaltion becomes an issue.*/ + void setOverlayBaseHeight(double baseHeight) { _overlayBaseHeight = baseHeight; } + + /** Get the base height that the overlay subgraph will be projected down to.*/ + double getOverlayBaseHeight() const { return _overlayBaseHeight; } + + /** Set the clear color to use when rendering the overlay subgraph.*/ + void setOverlayClearColor(const osg::Vec4& color) { _overlayClearColor = color; } + + /** Get the clear color to use when rendering the overlay subgraph.*/ + const osg::Vec4& getOverlayClearColor() const { return _overlayClearColor; } + + /** Set the TexEnv mode used to combine the overlay texture with the base color/texture of the OverlayNode's decorate subgraph.*/ + void setTexEnvMode(GLenum mode); + + /** Get the TexEnv mode used to combine the overlay texture with the base color/texture of the OverlayNode's decorate subgraph.*/ + GLenum getTexEnvMode() const { return _texEnvMode; } + + /** Set the texture unit that the texture should be assigned to.*/ + void setOverlayTextureUnit(unsigned int unit); + + /** Get the texture unit that the texture should be assigned to.*/ + unsigned int getOverlayTextureUnit() const { return _textureUnit; } + + /** Set the texture size hint. The size hint is used to request a texture of specified size.*/ + void setOverlayTextureSizeHint(unsigned int size); + + /** Get the texture size hint.*/ + unsigned int getOverlayTextureSizeHint() const { return _textureSizeHint; } + + + /** Set whether to use a mutex to ensure ref() and unref() are thread safe.*/ + virtual void setThreadSafeRefUnref(bool threadSafe); + + /** Resize any per context GLObject buffers to specified size. */ + virtual void resizeGLObjectBuffers(unsigned int /*maxSize*/); + + /** If State is non-zero, this function releases any associated OpenGL objects for + * the specified graphics context. Otherwise, releases OpenGL objexts + * for all graphics contexts. */ + virtual void releaseGLObjects(osg::State* = 0) const; + + protected : + + virtual ~OverlayNode() {} + + void init(); + void init_OBJECT_DEPENDENT_WITH_ORTHOGRAPHIC_OVERLAY(); + void init_VIEW_DEPENDENT_WITH_ORTHOGRAPHIC_OVERLAY(); + void init_VIEW_DEPENDENT_WITH_PERSPECTIVE_OVERLAY(); + + void traverse_OBJECT_DEPENDENT_WITH_ORTHOGRAPHIC_OVERLAY(osg::NodeVisitor& nv); + void traverse_VIEW_DEPENDENT_WITH_ORTHOGRAPHIC_OVERLAY(osg::NodeVisitor& nv); + void traverse_VIEW_DEPENDENT_WITH_PERSPECTIVE_OVERLAY(osg::NodeVisitor& nv); + + + void updateMainSubgraphStateSet(); + + typedef osg::buffered_value< int > TextureObjectValidList; + + mutable TextureObjectValidList _textureObjectValidList; + + OverlayTechnique _overlayTechnique; + + + // overlay subgraph is render to a texture + osg::ref_ptr _overlaySubgraph; + + osg::ref_ptr _overlayStateSet; + osg::ref_ptr _mainStateSet; + + // texture to render to, and to read from. + GLenum _texEnvMode; + unsigned int _textureUnit; + unsigned int _textureSizeHint; + osg::Vec4 _overlayClearColor; + + bool _continuousUpdate; + double _overlayBaseHeight; + bool _updateCamera; + + osg::Camera::RenderTargetImplementation _renderTargetImpl; + + struct OverlayData : public osg::Referenced + { + + void setThreadSafeRefUnref(bool threadSafe); + void resizeGLObjectBuffers(unsigned int maxSize); + void releaseGLObjects(osg::State* state= 0) const; + + osg::ref_ptr _camera; + osg::ref_ptr _overlayStateSet; + osg::ref_ptr _mainSubgraphStateSet; + osg::ref_ptr _texgenNode; + osg::ref_ptr _texture; + osg::Polytope _textureFrustum; + osg::ref_ptr _geode; + + osg::ref_ptr _mainSubgraphProgram; + + osg::ref_ptr _y0; + osg::ref_ptr _lightingEnabled; + }; + + typedef std::map > OverlayDataMap; + + OpenThreads::Mutex _overlayDataMapMutex; + OverlayDataMap _overlayDataMap; + + OverlayNode::OverlayData* getOverlayData(osgUtil::CullVisitor* cv); + +}; + +} + +#endif diff --git a/libs/include/android/osgSim/ScalarBar b/libs/include/android/osgSim/ScalarBar new file mode 100755 index 0000000..6d25d27 --- /dev/null +++ b/libs/include/android/osgSim/ScalarBar @@ -0,0 +1,248 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGSIM_SCALARBAR +#define OSGSIM_SCALARBAR 1 + +#include +#include // The default ScalarsToColors is a ColorRange +#include +#include + +namespace osgSim +{ +/** +A ScalarBar is an osg::Geode to render a colored bar representing a range +of scalars. The scalar/color ranges are specified by an instance of +ScalarsToColors. There are a number of configurable properties on the +ScalarBar, such as the orientation, the number of labels to be displayed +across the range, the number of distinct colors to use when rendering the +bar, text details etc. + +In summary, the main configurables on the ScalarBar are: + + -# The range of scalars represented by the bar, and the colors + corresponding to this range - these are specified by the + ScalarsToColors object. + -# The number of colors used when rendering the bar geometry - + this may be thought of as the bar 'density'. + -# The number of text labels to be used when displaying the bar. + +The other configurables should be self-explanatory. +*/ +class OSGSIM_EXPORT ScalarBar: public osg::Geode +{ + +public: + + /** ScalarBar orientation specification. */ + enum Orientation{ + HORIZONTAL, ///< a horizontally ascending scalar bar (x-axis) + VERTICAL ///< a vertically ascending scalar bar (y-axis) + }; + + /** + Users may provide their own ScalarPrinter by deriving from this base class and + overriding the printScalar() method. Users may map the scalar float passed in + to any string they wish. + */ + struct OSGSIM_EXPORT ScalarPrinter: public osg::Referenced + { + virtual std::string printScalar(float scalar); + }; + + /** + TextProperties allows users to specify a number of properties for the + text used to display the labels & title on the ScalarBar. Specifiying a character + size of 0 will cause the ScalarBar to estimate an appropriate size. Note that + the attributes are public, and may be set directly. + */ + struct TextProperties + { + std::string _fontFile; + std::pair _fontResolution; + float _characterSize; + osg::Vec4 _color; + + TextProperties(): + _fontFile("fonts/arial.ttf"), + _fontResolution(40,40), + _characterSize(0.0f), + _color(1.0f,1.0f,1.0f,1.0f) + { + } + }; + + /** Default constructor. */ + ScalarBar(): osg::Geode(), + _numColors(256), + _numLabels(11), + _stc(new ColorRange(0.0f,1.0f)), + _title("Scalar Bar"), + _position(0.0f,0.0f,0.0f), + _width(1.0f), + _aspectRatio(0.03), + _orientation(HORIZONTAL), + _sp(new ScalarPrinter) + { + createDrawables(); + } + + /** + Construct a ScalarBar with the supplied parameters. + @param numColors Specify the number of colors in the scalar bar. Color + interpolation occurs where necessary. + @param numLabels Specify the number of labels in the scalar bar. + @param stc The ScalarsToColors defining the range of scalars + and the colors they map to. + @param title The title to be used when displaying the ScalarBar. + Specify "" for no title. + @param orientation The orientation of the ScalarBar. @see Orientation. + @param aspectRatio The aspect ration (y/x) for the displayed bar. Bear in mind you + may want to change this if you change the orientation. + @param sp A ScalarPrinter object for the ScalarBar. For every displayed + ScalarBar label, the scalar value will be passed to the + ScalarPrinter object to turn it into a string. Users may + override the default ScalarPrinter object to map scalars to + whatever strings they wish. @see ScalarPrinter + */ + ScalarBar(int numColors, int numLabels, ScalarsToColors* stc, + const std::string& title, + Orientation orientation = HORIZONTAL, + float aspectRatio=0.25, + ScalarPrinter* sp=new ScalarPrinter): + osg::Geode(), + _numColors(numColors), + _numLabels(numLabels), + _stc(stc), + _title(title), + _position(0.0f,0.0f,0.0f), + _width(1.0f), + _aspectRatio(aspectRatio), + _orientation(orientation), + _sp(sp) + { + createDrawables(); + } + + /** Copy constructor */ + ScalarBar(const ScalarBar& rhs, const osg::CopyOp& co): osg::Geode(rhs,co), + _numColors(rhs._numColors), + _numLabels(rhs._numLabels), + _stc(rhs._stc), // Consider clone for deep copy? + _title(rhs._title), + _position(rhs._position), + _width(rhs._width), + _aspectRatio(rhs._aspectRatio), + _orientation(rhs._orientation), + _sp(rhs._sp), // Consider clone for deep copy? + _textProperties(rhs._textProperties) + { + } + + + META_Node(osgSim, ScalarBar); + + /** Set the number of distinct colours on the ScalarBar. */ + void setNumColors(int numColors); + + /** Get the number of distinct colours on the ScalarBar. */ + int getNumColors() const; + + /** Set the number of labels to display along the ScalarBar. There + will be one label at each end point, and evenly distributed labels + in between. */ + void setNumLabels(int numLabels); + + /** Get the number of labels displayed along the ScalarBar. */ + int getNumLabels() const; + + /** Set the ScalarsToColors mapping object for the ScalarBar. */ + void setScalarsToColors(ScalarsToColors* stc); + + /** Get the ScalarsToColors mapping object from the ScalarBar. */ + const ScalarsToColors* getScalarsToColors() const; + + /** Set the title for the ScalarBar, set "" for no title. */ + void setTitle(const std::string& title); + + /** Get the title for the ScalarBar. */ + const std::string& getTitle() const; + + + /** Set the position of scalar bar's lower left corner.*/ + void setPosition(const osg::Vec3& pos); + + /** Get the position of scalar bar.*/ + const osg::Vec3& getPosition() const { return _position; } + + /** Set the width of the scalar bar.*/ + void setWidth(float width); + + /** Get the width of the scalar bar.*/ + float getWidth() const { return _width; } + + /** Set the aspect ration (y/x) for the displayed bar. Bear in mind you + may want to change this if you change the orientation. */ + void setAspectRatio(float aspectRatio); + + /** Get the aspect ration (y/x) for the displayed bar. */ + float getAspectRatio() const; + + + /** Set the orientation of the ScalarBar. @see Orientation */ + void setOrientation(ScalarBar::Orientation orientation); + + /** Get the orientation of the ScalarBar. @see Orientation */ + ScalarBar::Orientation getOrientation() const; + + + /** Set a ScalarPrinter object for the ScalarBar. For every displayed + ScalarBar label, the scalar value will be passed to the ScalarPrinter + object to turn it into a string. Users may override the default ScalarPrinter + object to map scalars to whatever strings they wish. @see ScalarPrinter */ + void setScalarPrinter(ScalarPrinter* sp); + + /** Get the ScalarPrinter object */ + const ScalarPrinter* getScalarPrinter() const; + + /** Set the TextProperties for the labels & title. @see TextProperties */ + void setTextProperties(const TextProperties& tp); + + /** Get the TextProperties for the labels & title. @see TextProperties */ + const TextProperties& getTextProperties() const; + + /** force update the drawables used to render the scalar bar.*/ + void update() { createDrawables(); } + +protected: + virtual ~ScalarBar(); + + int _numColors; + int _numLabels; + osg::ref_ptr _stc; + std::string _title; + osg::Vec3 _position; + float _width; + float _aspectRatio; + Orientation _orientation; + osg::ref_ptr _sp; + TextProperties _textProperties; + + void createDrawables(); + +}; + +} + +#endif diff --git a/libs/include/android/osgSim/ScalarsToColors b/libs/include/android/osgSim/ScalarsToColors new file mode 100755 index 0000000..4b1716f --- /dev/null +++ b/libs/include/android/osgSim/ScalarsToColors @@ -0,0 +1,53 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGSIM_SCALARSTCOLORS +#define OSGSIM_SCALARSTCOLORS 1 + +#include + +#include +#include + +namespace osgSim +{ +/** +ScalarsToColors defines the interface to map a scalar value to a color, +and provides a default implementation of the mapping functionaltity, +with colors ranging from black to white across the min - max scalar +range. +*/ +class OSGSIM_EXPORT ScalarsToColors: public osg::Referenced +{ +public: + + ScalarsToColors(float scalarMin, float scalarMax); + virtual ~ScalarsToColors() {} + + /** Get the color for a given scalar value. */ + virtual osg::Vec4 getColor(float scalar) const; + + /** Get the minimum scalar value. */ + float getMin() const; + + /** Get the maximum scalar value. */ + float getMax() const; + +private: + + float _min, _max; +}; + +} + +#endif diff --git a/libs/include/android/osgSim/Sector b/libs/include/android/osgSim/Sector new file mode 100755 index 0000000..bbc50bc --- /dev/null +++ b/libs/include/android/osgSim/Sector @@ -0,0 +1,314 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGSIM_SECTOR +#define OSGSIM_SECTOR 1 + +#include + +#include +#include +#include +#include +#include +#include + +namespace osgSim { + +class Sector : public osg::Object +{ + public: + + Sector() {} + + Sector(const Sector& copy, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY): + osg::Object(copy,copyop) {} + + virtual const char *libraryName() const { return "osgSim"; } + virtual const char *className() const { return "Sector"; } + virtual bool isSameKindAs(const osg::Object *obj) const { return dynamic_cast(obj) != 0; } + + virtual float operator() (const osg::Vec3& /*eyeLocal*/) const = 0; + + protected: + + virtual ~Sector() {} +}; + +class OSGSIM_EXPORT AzimRange +{ + public: + + AzimRange(): + _cosAzim(1.0f), + _sinAzim(0.0f), + _cosAngle(-1.0f), + _cosFadeAngle(-1.0f) {} + + void setAzimuthRange(float minAzimuth,float maxAzimuth,float fadeAngle=0.0f); + void getAzimuthRange(float& minAzimuth, float& maxAzimuth, float& fadeAngle) const; + + + inline float azimSector(const osg::Vec3& eyeLocal) const + { + float dotproduct = eyeLocal.x()*_sinAzim+eyeLocal.y()*_cosAzim; + float length = sqrt(osg::square(eyeLocal.x())+osg::square(eyeLocal.y())); + if (dotproduct<_cosFadeAngle*length) return 0.0f; // out of sector. + if (dotproduct>=_cosAngle*length) return 1.0f; // fully in sector. + return (dotproduct-_cosFadeAngle*length)/((_cosAngle-_cosFadeAngle)*length); + } + + protected: + + float _cosAzim; + float _sinAzim; + float _cosAngle; + float _cosFadeAngle; +}; + + +class OSGSIM_EXPORT ElevationRange +{ + public: + + + ElevationRange(): + _cosMinElevation(-1.0f), + _cosMinFadeElevation(-1.0f), + _cosMaxElevation(1.0), + _cosMaxFadeElevation(1.0) {} + + void setElevationRange(float minElevation,float maxElevation,float fadeAngle=0.0f); + + float getMinElevation() const; + + float getMaxElevation() const; + + float getFadeAngle() const; + + inline float elevationSector(const osg::Vec3& eyeLocal) const + { + float dotproduct = eyeLocal.z(); // against z axis - eyeLocal*(0,0,1). + float length = eyeLocal.length(); + if (dotproduct>_cosMaxFadeElevation*length) return 0.0f; // out of sector + if (dotproduct<_cosMinFadeElevation*length) return 0.0f; // out of sector + if (dotproduct>_cosMaxElevation*length) + { + // in uppoer fade band. + return (dotproduct-_cosMaxFadeElevation*length)/((_cosMaxElevation-_cosMaxFadeElevation)*length); + } + if (dotproduct<_cosMinElevation*length) + { + // in lower fade band. + return (dotproduct-_cosMinFadeElevation*length)/((_cosMinElevation-_cosMinFadeElevation)*length); + } + return 1.0f; // fully in sector + } + + protected: + + float _cosMinElevation; + float _cosMinFadeElevation; + float _cosMaxElevation; + float _cosMaxFadeElevation; +}; + +class OSGSIM_EXPORT AzimSector : public Sector, public AzimRange +{ + public: + + AzimSector(): + Sector(), + AzimRange() {} + + AzimSector(const AzimSector& copy, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY): + Sector(copy,copyop), + AzimRange(copy) {} + + AzimSector(float minAzimuth,float maxAzimuth,float fadeAngle=0.0f); + + META_Object(osgSim,AzimSector); + + virtual float operator() (const osg::Vec3& eyeLocal) const; + + protected: + + virtual ~AzimSector() {} + +}; + +class OSGSIM_EXPORT ElevationSector : public Sector, public ElevationRange +{ + public: + + + ElevationSector(): + Sector(), + ElevationRange() {} + + ElevationSector(const ElevationSector& copy, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY): + Sector(copy,copyop), + ElevationRange(copy) {} + + ElevationSector(float minElevation,float maxElevation,float fadeAngle=0.0f); + + META_Object(osgSim,ElevationSector); + + virtual float operator() (const osg::Vec3& eyeLocal) const; + + protected: + + virtual ~ElevationSector() {} +}; + + +class OSGSIM_EXPORT AzimElevationSector : public Sector, public AzimRange, public ElevationRange +{ + public: + + AzimElevationSector(): + Sector(), + AzimRange(), + ElevationRange() {} + + AzimElevationSector(const AzimElevationSector& copy, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY): + Sector(copy,copyop), + AzimRange(copy), + ElevationRange(copy) {} + + AzimElevationSector(float minAzimuth,float maxAzimuth,float minElevation,float maxElevation,float fadeAngle=0.0f); + + META_Object(osgSim,AzimElevationSector); + + virtual float operator() (const osg::Vec3& eyeLocal) const; + + protected: + + virtual ~AzimElevationSector() {} +}; + + +class OSGSIM_EXPORT ConeSector : public Sector +{ + public: + + ConeSector(): + Sector(), + _axis(0.0f,0.0f,1.0f), + _cosAngle(-1.0f), + _cosAngleFade(-1.0f) {} + + ConeSector(const ConeSector& copy, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY): + Sector(copy,copyop), + _axis(copy._axis), + _cosAngle(copy._cosAngle), + _cosAngleFade(copy._cosAngleFade) {} + + ConeSector(const osg::Vec3& axis,float angle,float fadeangle=0.0f); + + META_Object(osgSim,ConeSector); + + void setAxis(const osg::Vec3& axis); + + const osg::Vec3& getAxis() const; + + void setAngle(float angle,float fadeangle=0.0f); + + float getAngle() const; + + float getFadeAngle() const; + + virtual float operator() (const osg::Vec3& eyeLocal) const; + + protected: + + virtual ~ConeSector() {} + + osg::Vec3 _axis; + float _cosAngle; + float _cosAngleFade; +}; + + +/* The DirectionalSector class was created to better handle OpenFlight directional + lightpoints. The Elevation and Azimuth Sectors above impose invalid limits on + the elevation range which cause lightpoints whose direction vectors are not + on the XY plane to be displayed incorrectly. Corbin Holtz 4/04 */ + +class OSGSIM_EXPORT DirectionalSector : public Sector +{ + public: + + DirectionalSector(): + Sector(), + _direction(0.0f, 0.0f, 1.0f), + _rollAngle(0.0f), + _cosHorizAngle(-1.0f), + _cosVertAngle(-1.0f), + _cosHorizFadeAngle(-1.0f), + _cosVertFadeAngle(-1.0f) {computeMatrix();} + + DirectionalSector(const DirectionalSector& copy, const osg::CopyOp& copyop = osg::CopyOp::SHALLOW_COPY): + Sector(copy,copyop), + _direction(copy._direction), + _rollAngle(copy._rollAngle), + _local_to_LP(copy._local_to_LP), + _cosHorizAngle(copy._cosHorizAngle), + _cosVertAngle(copy._cosVertAngle), + _cosHorizFadeAngle(copy._cosHorizFadeAngle), + _cosVertFadeAngle(copy._cosVertFadeAngle) {} + + DirectionalSector(const osg::Vec3& direction,float horizLobeAngle, float vertLobeAngle, float lobeRollAngle, float fadeAngle=0.0f); + + META_Object(osgSim,DirectionalSector); + + void setDirection(const osg::Vec3& direction); + + const osg::Vec3& getDirection() const; + + void setHorizLobeAngle(float angle); + + float getHorizLobeAngle() const; + + void setLobeRollAngle(float angle); + + float getLobeRollAngle() const; + + void setVertLobeAngle(float angle); + + float getVertLobeAngle() const; + + void setFadeAngle(float angle); + + float getFadeAngle() const; + + virtual float operator() (const osg::Vec3& eyeLocal) const; + + void computeMatrix() ; + + protected: + + virtual ~DirectionalSector() {} + + osg::Vec3 _direction ; + float _rollAngle ; + osg::Matrix _local_to_LP ; + float _cosHorizAngle; + float _cosVertAngle; + float _cosHorizFadeAngle; + float _cosVertFadeAngle; +}; + +} + +#endif diff --git a/libs/include/android/osgSim/ShapeAttribute b/libs/include/android/osgSim/ShapeAttribute new file mode 100755 index 0000000..2561d07 --- /dev/null +++ b/libs/include/android/osgSim/ShapeAttribute @@ -0,0 +1,128 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2007 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGSIM_SHAPEATTRIBUTE +#define OSGSIM_SHAPEATTRIBUTE 1 + +#include +#include + +#include + +namespace osgSim +{ + +class OSGSIM_EXPORT ShapeAttribute +{ + public: + /// ShapeAttribute data type. + enum Type + { + UNKNOWN, + INTEGER, + DOUBLE, + STRING + }; + + ShapeAttribute(); + ShapeAttribute(const char * name); + ShapeAttribute(const char * name, int value); + ShapeAttribute(const char * name, double value); + + /** Note, ShapeAttribute takes a copy of both name and value, the calling code should manage its own clean up of the original strings.*/ + ShapeAttribute(const char * name, const char * value); + + ShapeAttribute(const ShapeAttribute & sa); + + ~ShapeAttribute(); + + ShapeAttribute& operator = (const ShapeAttribute& sa); + + /** return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs.*/ + int compare(const osgSim::ShapeAttribute& sa) const; + + inline bool operator == (const osgSim::ShapeAttribute& sa) const { return compare(sa)==0; } + inline bool operator != (const osgSim::ShapeAttribute& sa) const { return compare(sa)!=0; } + inline bool operator < (const osgSim::ShapeAttribute& sa) const { return compare(sa)<0; } + + /// Get the attribute name. + const std::string & getName() const { return _name; } + + /// Set the attribute name. + void setName(const std::string& name) { _name = name; } + + /// Get the attribute data type. + Type getType() const { return _type; } + + /// Get the attribute data as an int. + int getInt() const { return _integer; } + + /// Get the attribute data as a double. + double getDouble() const { return _double; } + + /// Get the attribute data as a string. + const char * getString() const { return _string; } + + /// Set an integer attribute data. + void setValue(int value) { free(); _type = INTEGER; _integer = value; } + + /// Set a double attribute data. + void setValue(double value) { free(); _type = DOUBLE; _double = value; } + + /// Set a string attribute data. + void setValue(const char * value); + + + private: + + void free(); + void copy(const ShapeAttribute& sa); + + std::string _name; + Type _type; + + union + { + int _integer; + double _double; + char* _string; + }; +}; + +class OSGSIM_EXPORT ShapeAttributeList : public osg::Object, public osg::MixinVector +{ + public: + META_Object(osgSim, ShapeAttributeList) + + ShapeAttributeList(): + Object() + {} + + /** Copy constructor, optional CopyOp object can be used to control + * shallow vs deep copying of dynamic data.*/ + ShapeAttributeList(const ShapeAttributeList& sal,const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY): + osg::Object(sal, copyop), + osg::MixinVector(sal) + { + } + + /** return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs.*/ + virtual int compare(const osgSim::ShapeAttributeList& sal) const; + + protected: + virtual ~ShapeAttributeList() {} +}; + +} + +#endif // ** SHAPEATTRIBUTE_ ** // diff --git a/libs/include/android/osgSim/SphereSegment b/libs/include/android/osgSim/SphereSegment new file mode 100755 index 0000000..d41f41f --- /dev/null +++ b/libs/include/android/osgSim/SphereSegment @@ -0,0 +1,317 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGSIM_SPHERESEGMENT +#define OSGSIM_SPHERESEGMENT 1 + +#include + +#include +#include +#include +#include +#include + +namespace osgSim{ + +/** +A SphereSegment is a Geode to represent an portion of a sphere (potentially +the whole sphere). The sphere is aligned such that the line through the +sphere's poles is parallel to the z axis. The sphere segment +may be rendered various components switched on or off: + + - The specified area of the sphere surface. + + - An edge line around the boundary of the specified area + of the sphere surface. + + - Four spokes, where a spoke is the line from + the sphere's centre to a corner of the rendered area. + + - Four planar areas, where the planar areas are formed + between the spokes. + +Caveats: + + - It's worth noting that the line through the sphere's poles is + parallel to the z axis. This has implications when specifying the + area to be rendered, and specifying areas where the centre of + the rendered area is the Z axis may lead to unexpected + geometry. + + - It's possible to render the whole sphere by specifying elevation + and azimuth ranges round the full 360 degrees. When doing + so you may consider switching the planes, spokes, and edge lines + off, to avoid rendering artefacts, e.g. the upper and lower + planes will be coincident. + +*/ +class OSGSIM_EXPORT SphereSegment: public osg::Geode +{ +public: + + /** + DrawMask represents a bit field, the values of which may be OR'ed together + to specify which parts of the sphere segment should be drawn. E.g. + \code + sphereSegment->setDrawMask(SphereSegment::DrawMask(SphereSegment::SURFACE|SphereSegment::SPOKES)); + \endcode + */ + enum DrawMask{ + SURFACE = 0x00000001, ///< Draw the specified area on the sphere's surface + SPOKES = 0x00000002, ///< Draw the spokes from the sphere's centre to the surface's corners + EDGELINE = 0x00000008, ///< Draw the line round the edge of the area on the sphere's surface + SIDES = 0x00000010, ///< Draw the planes from the sphere's centre to the edge of the sphere's surface + ALL = 0x7fffffff ///< Draw every part of the sphere segment + }; + + + /** Default constructor. */ + SphereSegment():osg::Geode(), + _centre(0.0f,0.0f,0.0f), _radius(1.0f), + _azMin(0.0f), _azMax(osg::PI/2.0f), + _elevMin(0.0f), _elevMax(osg::PI/2.0f), + _density(10), + _drawMask(DrawMask(ALL)) + { + init(); + } + + /** + Construct by angle ranges. Note that the azimuth 'zero' is the Y axis; specifying + an azimuth range from azMin -osg::PI/2.0f to azMax osg::PI/2.0f will cover the + 'top half' of the circle in the XY plane. The elev angles are 'out' of the 'zero' + XY plane with +ve angles above the plane, and -ve angles below. + @param centre sphere centre + @param radius radius of sphere + @param azMin azimuth minimum + @param azMax azimuth maximum + @param elevMin elevation minimum + @param elevMax elevation maximum + @param density number of units to divide the azimuth and elevation ranges into + */ + SphereSegment(const osg::Vec3& centre, float radius, float azMin, float azMax, + float elevMin, float elevMax, int density): + osg::Geode(), + _centre(centre), _radius(radius), + _azMin(azMin), _azMax(azMax), + _elevMin(elevMin), _elevMax(elevMax), + _density(density), + _drawMask(DrawMask(ALL)) + { + init(); + } + + /** + Construct by vector. + @param centre sphere centre + @param radius radius of sphere + @param vec vector pointing from sphere centre to centre point + of rendered area on sphere surface + @param azRange azimuth range in radians (with centre along vec) + @param elevRange elevation range in radians (with centre along vec) + @param density number of units to divide the azimuth and elevation ranges into + */ + SphereSegment(const osg::Vec3& centre, float radius, const osg::Vec3& vec, float azRange, + float elevRange, int density); + + /** Copy constructor */ + SphereSegment(const SphereSegment& rhs, const osg::CopyOp& co): + osg::Geode(rhs,co), + _centre(rhs._centre), _radius(rhs._radius), + _azMin(rhs._azMin), _azMax(rhs._azMax), + _elevMin(rhs._elevMin), _elevMax(rhs._elevMax), + _density(rhs._density), + _drawMask(rhs._drawMask) + { + init(); + } + + /** Set the centre point of the SphereSegment */ + void setCentre(const osg::Vec3& c); + + /** Get the centre point of the SphereSegment */ + const osg::Vec3& getCentre() const; + + /** Set the radius of the SphereSegment */ + void setRadius(float r); + + /** Get the radius of the SphereSegment */ + float getRadius() const; + + /** Set the area of the sphere segment + + @param vec vector pointing from sphere centre to centre point + of rendered area on sphere surface + @param azRange azimuth range in radians (with centre along vec) + @param elevRange elevation range in radians (with centre along vec) + */ + void setArea(const osg::Vec3& vec, float azRange, float elevRange); + + /** Get the area of the sphere segment + + @param vec vector pointing from sphere centre to centre point + of rendered area on sphere surface (normalized) + @param azRange azimuth range in radians (with centre along vec) + @param elevRange elevation range in radians (with centre along vec) + */ + void getArea(osg::Vec3& vec, float& azRange, float& elevRange) const; + + /** Set the area of the sphere segment + @param azMin azimuth minimum + @param azMax azimuth maximum + @param elevMin elevation minimum + @param elevMax elevation maximum + */ + void setArea(float azMin, float azMax, float elevMin, float elevMax); + + /** Get the area of the sphere segment + @param azMin azimuth minimum + @param azMax azimuth maximum + @param elevMin elevation minimum + @param elevMax elevation maximum + */ + void getArea(float &azMin, float &azMax, float &elevMin, float &elevMax) const; + + /** Set the density of the sphere segment */ + void setDensity(int d); + + /** Get the density of the sphere segment */ + int getDensity() const; + + /** + Specify the DrawMask. + @param dm Bitmask specifying which parts of the sphere segment should be drawn. + @see DrawMask + */ + void setDrawMask(int dm); + + /** Get the DrawMask */ + int getDrawMask() const { return _drawMask; } + + /** Set the color of the surface. */ + void setSurfaceColor(const osg::Vec4& c); + + /** Get the color of the surface. */ + const osg::Vec4& getSurfaceColor() const { return _surfaceColor; } + + /** Set the color of the spokes. */ + void setSpokeColor(const osg::Vec4& c); + + /** Get the color of the spokes. */ + const osg::Vec4& getSpokeColor() const { return _spokeColor; } + + /** Set the color of the edge line. */ + void setEdgeLineColor(const osg::Vec4& c); + + /** Get the color of the edge line. */ + const osg::Vec4& getEdgeLineColor() const { return _edgeLineColor; } + + /** Set the color of the planes. */ + void setSideColor(const osg::Vec4& c); + + /** Get the color of the planes. */ + const osg::Vec4& getSideColor() const { return _planeColor; } + + /** Set color of all components. */ + void setAllColors(const osg::Vec4& c); + + META_Node(osgSim, SphereSegment); + + /** A list of vertex arrays representing a list of lines.*/ + typedef std::vector< osg::ref_ptr > LineList; + + /** Compute the interesection lines between subgraph and this sphere segment. + * The matrix is the transform that takes the subgraph into the same coordiante frame as the sphere segment. + * The resulting intersections are in the coordinate frame of the sphere segment. */ + LineList computeIntersection(const osg::Matrixd& matrix, osg::Node* subgraph); + + /** Compute the interesection lines between specified drawable and this sphere segment. + * The matrix is the transform that takes the subgraph into the same coordiante frame as the sphere segment. + * The resulting intersections are in the coordinate frame of the sphere segment. */ + LineList computeIntersection(const osg::Matrixd& matrix, osg::Drawable* drawable); + + /** Compute the interesection lines between subgraph and this sphere segment. + * The matrix is the transform that takes the subgraph into the same coordiante frame as the sphere segment. + * The resulting intersections are in the coordinate frame of the sphere segment. */ + osg::Node* computeIntersectionSubgraph(const osg::Matrixd& matrix, osg::Node* subgraph); + + /** Compute the interesection lines between specified drawable and this sphere segment. + * The matrix is the transform that takes the subgraph into the same coordiante frame as the sphere segment. + * The resulting intersections are in the coordinate frame of the sphere segment. */ + osg::Node* computeIntersectionSubgraph(const osg::Matrixd& matrix, osg::Drawable* drawable); + + +private: + + void init(); // Shared constructor code, generates the drawables + + void dirtyAllDrawableDisplayLists(); // Force re-calling of gl functions + void dirtyAllDrawableBounds(); // Force recalculation of bound geometry + + // SphereSegment is actually made up of a number of Drawable classes, + // all of which are nested private classes, as declared below. These + // classes are defined in the .cpp for minimum visibility and physical + // coupling. (Reduces time spent compiling! :-) + // + // Each of the nested classes holds a pointer to the SphereSegment + // 'parent', which stores the geometry details, and performs any + // work required. The nested classes are lightweight objects which + // just pass the work on. + // + // Why are things done with these sub-Drawables? Alpha-blended + // Drawables need to be drawn last, depth sorted, and the various + // components of a SphereSegment also need to be depth sorted + // against one another (they may all be drawn with alpha blending). + // Making these Drawables allows us to get the OSG to depth sort + // for us. + + class Surface; + friend class Surface; + bool Surface_computeBound(osg::BoundingBox&) const; + void Surface_drawImplementation(osg::State&) const; + + class EdgeLine; + friend class EdgeLine; + bool EdgeLine_computeBound(osg::BoundingBox&) const; + void EdgeLine_drawImplementation(osg::State&) const; + + enum BoundaryAngle{MIN,MAX}; // Why here and not in Side class? Because we can't forward + enum SideOrientation{AZIM,ELEV}; // declare enums, Side is in the .cpp, and this is tidier... + class Side; + friend class Side; + bool Side_computeBound(osg::BoundingBox&, SideOrientation, BoundaryAngle) const; + void Side_drawImplementation(osg::State&, SideOrientation, BoundaryAngle) const; + + class Spoke; + friend class Spoke; + bool Spoke_computeBound(osg::BoundingBox&, BoundaryAngle, BoundaryAngle) const; + void Spoke_drawImplementation(osg::State&, BoundaryAngle, BoundaryAngle) const; + + // Sphere segment geometry details + osg::Vec3 _centre; + float _radius; + float _azMin, _azMax, _elevMin, _elevMax; + int _density; + + // Draw details + int _drawMask; + osg::Vec4 _surfaceColor; + osg::Vec4 _spokeColor; + osg::Vec4 _edgeLineColor; + osg::Vec4 _planeColor; +}; + +} + +#endif diff --git a/libs/include/android/osgSim/Version b/libs/include/android/osgSim/Version new file mode 100755 index 0000000..1204bc6 --- /dev/null +++ b/libs/include/android/osgSim/Version @@ -0,0 +1,46 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGSIM_VERSION +#define OSGSIM_VERSION 1 + +#include + +extern "C" { + +/** + * osgSimGetVersion() returns the library version number. + * Numbering convention : OpenSceneGraph-1.0 will return 1.0 from osgSimGetVersion. + * + * This C function can be also used to check for the existence of the OpenSceneGraph + * library using autoconf and its m4 macro AC_CHECK_LIB. + * + * Here is the code to add to your configure.in: + \verbatim + # + # Check for the OpenSceneGraph (OSG) Sim library + # + AC_CHECK_LIB(osg, osgSimGetVersion, , + [AC_MSG_ERROR(OpenSceneGraph Sim library not found. See http://www.openscenegraph.org)],) + \endverbatim +*/ +extern OSGSIM_EXPORT const char* osgSimGetVersion(); + +/** + * osgSimGetLibraryName() returns the library name in human friendly form. +*/ +extern OSGSIM_EXPORT const char* osgSimGetLibraryName(); + +} + +#endif diff --git a/libs/include/android/osgSim/VisibilityGroup b/libs/include/android/osgSim/VisibilityGroup new file mode 100755 index 0000000..8a9e0df --- /dev/null +++ b/libs/include/android/osgSim/VisibilityGroup @@ -0,0 +1,76 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGSIM_VISIBILITYGROUP +#define OSGSIM_VISIBILITYGROUP 1 + +#include +#include +#include + +#include + +namespace osgSim { + +/** VisibilityGroup renders (traverses) it's children only when the camera is inside a specified visibility volume. + * The visibility volume is intersected with a line segment that extends from + * the current camera's eye-point along the view vector for a given segment length. + * If an intersection is detected then the node's children are traversed. + */ +class OSGSIM_EXPORT VisibilityGroup : public osg::Group +{ + public : + + VisibilityGroup(); + + /** Copy constructor using CopyOp to manage deep vs shallow copy.*/ + VisibilityGroup(const VisibilityGroup&,const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY); + + META_Node(osgSim, VisibilityGroup); + + virtual void traverse(osg::NodeVisitor& nv); + + /** Set the subgraph that is intersected for the visibility determination.*/ + void setVisibilityVolume(osg::Node* node) { _visibilityVolume = node; } + + /** Get the subgraph that is intersected for the visibility determination.*/ + osg::Node* getVisibilityVolume() { return _visibilityVolume.get(); } + + /** Get the const subgraph that is intersected for the visibility determination.*/ + const osg::Node* getVisibilityVolume() const { return _visibilityVolume.get(); } + + /** Set the traversal mask for the intersection testing.*/ + void setVolumeIntersectionMask(osg::Node::NodeMask mask) { _volumeIntersectionMask = mask; } + + /** Get the traversal mask for the intersection testing.*/ + osg::Node::NodeMask getVolumeIntersectionMask() const { return _volumeIntersectionMask; } + + /** Set the length of the intersection segment. + * The segments extends this many database units from the camera eye-point along the look vector. + * If this is left at zero then the diameter of the bounding sphere of the visibility volume is used.*/ + void setSegmentLength(float length) { _segmentLength = length; } + + /** Get the length of the intersection segment.*/ + float getSegmentLength() const { return _segmentLength; } + + protected : + + virtual ~VisibilityGroup() {} + + osg::ref_ptr _visibilityVolume; + osg::Node::NodeMask _volumeIntersectionMask; + float _segmentLength; +}; + +} +#endif diff --git a/libs/include/android/osgTerrain/Export b/libs/include/android/osgTerrain/Export new file mode 100755 index 0000000..9dc77a1 --- /dev/null +++ b/libs/include/android/osgTerrain/Export @@ -0,0 +1,49 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGTERRAIN_EXPORT_ +#define OSGTERRAIN_EXPORT_ 1 + +#include + +#if defined(_MSC_VER) && defined(OSG_DISABLE_MSVC_WARNINGS) + #pragma warning( disable : 4244 ) + #pragma warning( disable : 4251 ) + #pragma warning( disable : 4267 ) + #pragma warning( disable : 4275 ) + #pragma warning( disable : 4290 ) + #pragma warning( disable : 4786 ) + #pragma warning( disable : 4305 ) + #pragma warning( disable : 4996 ) +#endif + +#if defined(_MSC_VER) || defined(__CYGWIN__) || defined(__MINGW32__) || defined( __BCPLUSPLUS__) + # if defined( OSG_LIBRARY_STATIC ) + # define OSGTERRAIN_EXPORT + # elif defined( OSGTERRAIN_LIBRARY ) + # define OSGTERRAIN_EXPORT __declspec(dllexport) + # else + # define OSGTERRAIN_EXPORT __declspec(dllimport) + # endif +#else + # define OSGTERRAIN_EXPORT +#endif + +/** + +\namespace osgTerrain + +The osgTerrain library is a NodeKit that provides geospecifc terrain rendering support. +*/ + +#endif diff --git a/libs/include/android/osgTerrain/GeometryTechnique b/libs/include/android/osgTerrain/GeometryTechnique new file mode 100755 index 0000000..fdb0df4 --- /dev/null +++ b/libs/include/android/osgTerrain/GeometryTechnique @@ -0,0 +1,116 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGTERRAIN_GEOMETRYTECHNIQUE +#define OSGTERRAIN_GEOMETRYTECHNIQUE 1 + +#include +#include +#include + +#include +#include + +namespace osgTerrain { + +class OSGTERRAIN_EXPORT GeometryTechnique : public TerrainTechnique +{ + public: + + GeometryTechnique(); + + /** Copy constructor using CopyOp to manage deep vs shallow copy.*/ + GeometryTechnique(const GeometryTechnique&,const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY); + + META_Object(osgTerrain, GeometryTechnique); + + virtual void init(int dirtyMask, bool assumeMultiThreaded); + + virtual Locator* computeMasterLocator(); + + + virtual void update(osgUtil::UpdateVisitor* nv); + + virtual void cull(osgUtil::CullVisitor* nv); + + /** Traverse the terain subgraph.*/ + virtual void traverse(osg::NodeVisitor& nv); + + virtual void cleanSceneGraph(); + + void setFilterBias(float filterBias); + float getFilterBias() const { return _filterBias; } + + void setFilterWidth(float filterWidth); + float getFilterWidth() const { return _filterWidth; } + + void setFilterMatrix(const osg::Matrix3& matrix); + osg::Matrix3& getFilterMatrix() { return _filterMatrix; } + const osg::Matrix3& getFilterMatrix() const { return _filterMatrix; } + + enum FilterType + { + GAUSSIAN, + SMOOTH, + SHARPEN + }; + + void setFilterMatrixAs(FilterType filterType); + + /** If State is non-zero, this function releases any associated OpenGL objects for + * the specified graphics context. Otherwise, releases OpenGL objects + * for all graphics contexts. */ + virtual void releaseGLObjects(osg::State* = 0) const; + + + protected: + + virtual ~GeometryTechnique(); + + class BufferData : public osg::Referenced + { + public: + BufferData() {} + + osg::ref_ptr _transform; + osg::ref_ptr _geode; + osg::ref_ptr _geometry; + + protected: + ~BufferData() {} + }; + + virtual osg::Vec3d computeCenterModel(BufferData& buffer, Locator* masterLocator); + + virtual void generateGeometry(BufferData& buffer, Locator* masterLocator, const osg::Vec3d& centerModel); + + virtual void applyColorLayers(BufferData& buffer); + + virtual void applyTransparency(BufferData& buffer); + + + OpenThreads::Mutex _writeBufferMutex; + osg::ref_ptr _currentBufferData; + osg::ref_ptr _newBufferData; + + float _filterBias; + osg::ref_ptr _filterBiasUniform; + float _filterWidth; + osg::ref_ptr _filterWidthUniform; + osg::Matrix3 _filterMatrix; + osg::ref_ptr _filterMatrixUniform; +}; + +} + +#endif diff --git a/libs/include/android/osgTerrain/Layer b/libs/include/android/osgTerrain/Layer new file mode 100755 index 0000000..9835a69 --- /dev/null +++ b/libs/include/android/osgTerrain/Layer @@ -0,0 +1,611 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGTERRAIN_LAYER +#define OSGTERRAIN_LAYER 1 + +#include +#include +#include +#include + +#include +#include + +namespace osgTerrain { + +#define MAXIMUM_NUMBER_OF_LEVELS 30 + +/** Extact the setname and filename from a compound string in the from set:setname:filename". + * Returns a setname of "" when non set:setname: entry is present.*/ +extern OSGTERRAIN_EXPORT void extractSetNameAndFileName(const std::string& compoundstring, std::string& setname, std::string& filename); + +/** Create a compound string in the form set:setname:filename, or just filename if setname is "".*/ +extern OSGTERRAIN_EXPORT std::string createCompoundSetNameAndFileName(const std::string& setname, const std::string& filename); + +class OSGTERRAIN_EXPORT Layer : public osg::Object +{ + public: + + Layer(); + + /** Copy constructor using CopyOp to manage deep vs shallow copy.*/ + Layer(const Layer&,const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY); + + META_Object(osgTerrain, Layer); + + /** Set the name of this layer. */ + void setSetName(const std::string& setname) { setName(setname); } + + /** Get the name of this layer. */ + const std::string& getSetName() const { return getName(); } + + /** Set the file name of the data associated with this layer. */ + virtual void setFileName(const std::string& filename) { _filename = filename; } + + /** Get the file name of the layer. */ + virtual const std::string& getFileName() const { return _filename; } + + /** Return the compound name of the layer in the form set::name::filename string.*/ + std::string getCompoundName() const { return createCompoundSetNameAndFileName(getName(), getFileName()); } + + void setLocator(Locator* locator) { _locator = locator; } + Locator* getLocator() { return _locator.get(); } + const Locator* getLocator() const { return _locator.get(); } + + void setMinLevel(unsigned int minLevel) { _minLevel = minLevel; } + unsigned int getMinLevel() const { return _minLevel; } + + void setMaxLevel(unsigned int maxLevel) { _maxLevel = maxLevel; } + unsigned int getMaxLevel() const { return _maxLevel; } + + /** Set the data validation operator. */ + void setValidDataOperator(ValidDataOperator* validDataOp) { _validDataOperator = validDataOp; } + + /** Get the data validation operator. */ + ValidDataOperator* getValidDataOperator() { return _validDataOperator.get(); } + + /** Get the const data validation operator. */ + const ValidDataOperator* getValidDataOperator() const { return _validDataOperator.get(); } + + + /** Get the number of columns. */ + virtual unsigned int getNumColumns() const { return 0; } + + /** Get the number of rows. */ + virtual unsigned int getNumRows() const { return 0; } + + void setDefaultValue(const osg::Vec4& value) { _defaultValue = value; } + const osg::Vec4& getDefaultValue() const { return _defaultValue; } + + + /** Set the minification texture filter to use when a texture is associated with this layer.*/ + void setMinFilter(osg::Texture::FilterMode filter) { _minFilter = filter; } + + /** Get the minification texture filter to use when a texture is associated with this layer.*/ + osg::Texture::FilterMode getMinFilter() const { return _minFilter; } + + + /** Set the magnification texture filter to use when a texture is associated with this layer.*/ + void setMagFilter(osg::Texture::FilterMode filter) { _magFilter = filter; } + + /** Get the magnification texture filter to use when a texture is associated with this layer.*/ + osg::Texture::FilterMode getMagFilter() const { return _magFilter; } + + + + /** Return image associated with layer if supported. */ + virtual osg::Image* getImage() { return 0; } + + /** Return const image associated with layer if supported. */ + virtual const osg::Image* getImage() const { return 0; } + + + virtual bool transform(float /*offset*/, float /*scale*/) { return false; } + + /** + * Get the layer value at position i,j. + * @param[in] i X-axis (or column) index. + * @param[in] j Y-axis (or row) index. + * @param[out] value Returned layer value. + * @return true if value is valid, else false + */ + virtual bool getValue(unsigned int /*i*/, unsigned int /*j*/, float& /*value*/) const { return false; } + virtual bool getValue(unsigned int /*i*/, unsigned int /*j*/, osg::Vec2& /*value*/) const { return false; } + virtual bool getValue(unsigned int /*i*/, unsigned int /*j*/, osg::Vec3& /*value*/) const { return false; } + virtual bool getValue(unsigned int /*i*/, unsigned int /*j*/, osg::Vec4& /*value*/) const { return false; } + + inline bool getValidValue(unsigned int i, unsigned int j, float& value) const + { + if (getValue(i,j,value)) return _validDataOperator.valid() ? (*_validDataOperator)(value) : true; + return false; + } + + inline bool getValidValue(unsigned int i, unsigned int j, osg::Vec2& value) const + { + if (getValue(i,j,value)) return _validDataOperator.valid() ? (*_validDataOperator)(value) : true; + return false; + } + + inline bool getValidValue(unsigned int i, unsigned int j, osg::Vec3& value) const + { + if (getValue(i,j,value)) return _validDataOperator.valid() ? (*_validDataOperator)(value) : true; + return false; + } + + inline bool getValidValue(unsigned int i, unsigned int j, osg::Vec4& value) const + { + if (getValue(i,j,value)) return _validDataOperator.valid() ? (*_validDataOperator)(value) : true; + return false; + } + + + /** + * Compute column,row indices from normalized coordinates. + * @param[in] ndc_x Normalized X-axis coordinate. + * @param[in] ndc_y Normalized Y-axis coordinate. + * @param[out] i Returned X-axis (or column) index. + * @param[out] j Returned Y-axis (or row) index. + * @param[out] ir Returned X-axis fraction. + * @param[out] jr Returned Y-axis fraction. + */ + inline void computeIndices(double ndc_x, double ndc_y, unsigned int& i, unsigned int& j, double& ir, double& jr) + { + ndc_x *= double(getNumColumns()-1); + ndc_y *= double(getNumRows()-1); + i = (unsigned int)(ndc_x); + j = (unsigned int)(ndc_y); + ir = ndc_x - double(i); + jr = ndc_y - double(j); + } + + /** + * Calculate the interpolated layer value at the given normalized coordinates. + * @param[in] ndc_x Normalized X-axis coordinate. + * @param[in] ndc_y Normalized Y-axis coordinate. + * @param[out] value Returned layer value. + * @return true if value is valid, else false + */ + inline bool getInterpolatedValue(double ndc_x, double ndc_y, float& value) + { + unsigned int i,j; + double ir, jr; + computeIndices(ndc_x, ndc_y, i, j, ir, jr); + value = 0.0f; + double div = 0.0f; + float v,r; + + r = (1.0f-ir)*(1.0f-jr); + if (r>0.0 && getValue(i,j,v)) + { + value += v*r; + div += r; + } + + r = (ir)*(1.0f-jr); + if (r>0.0 && getValue(i+1,j,v)) + { + value += v*r; + div += r; + } + + r = (ir)*(jr); + if (r>0.0 && getValue(i+1,j+1,v)) + { + value += v*r; + div += r; + } + + r = (1.0f-ir)*(jr); + if (r>0.0 && getValue(i,j+1,v)) + { + value += v*r; + div += r; + } + + if (div != 0.0) + { + value /= div; + return true; + } + + value = 0.0; + return false; + } + + inline bool getInterpolatedValidValue(double ndc_x, double ndc_y, float& value) + { + unsigned int i,j; + double ir, jr; + computeIndices(ndc_x, ndc_y, i, j, ir, jr); + value = 0.0f; + double div = 0.0f; + float v,r; + + r = (1.0f-ir)*(1.0f-jr); + if (r>0.0 && getValidValue(i,j,v)) + { + value += v*r; + div += r; + } + + r = (ir)*(1.0f-jr); + if (r>0.0 && getValidValue(i+1,j,v)) + { + value += v*r; + div += r; + } + + r = (ir)*(jr); + if (r>0.0 && getValidValue(i+1,j+1,v)) + { + value += v*r; + div += r; + } + + r = (1.0f-ir)*(jr); + if (r>0.0 && getValidValue(i,j+1,v)) + { + value += v*r; + div += r; + } + + if (div != 0.0) + { + value /= div; + return true; + } + + value = 0.0; + return false; + } + + /** increment the modified count."*/ + virtual void dirty() {} + + /** Set the modified count value. */ + virtual void setModifiedCount(unsigned int /*value*/) {} + + /** Get modified count value. */ + virtual unsigned int getModifiedCount() const { return 0; } + + virtual osg::BoundingSphere computeBound(bool treatAsElevationLayer) const; + + protected: + + virtual ~Layer(); + + std::string _filename; + osg::ref_ptr _locator; + unsigned int _minLevel; + unsigned int _maxLevel; + osg::ref_ptr _validDataOperator; + osg::Vec4 _defaultValue; + osg::Texture::FilterMode _minFilter; + osg::Texture::FilterMode _magFilter; + +}; + +class OSGTERRAIN_EXPORT ImageLayer : public Layer +{ + public: + + ImageLayer(osg::Image* image=0); + + /** Copy constructor using CopyOp to manage deep vs shallow copy.*/ + ImageLayer(const ImageLayer& imageLayer,const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY); + + META_Object(osgTerrain, ImageLayer); + + void setFileName(const std::string& filename) { _filename = filename; if (_image.valid()) _image->setFileName(filename); } + virtual const std::string& getFileName() const { return _image.get() ? _image->getFileName() : _filename; } + + virtual bool transform(float offset, float scale); + + void setImage(osg::Image* image); + + /** Return image associated with layer. */ + virtual osg::Image* getImage() { return _image.get(); } + + /** Return const image associated with layer. */ + virtual const osg::Image* getImage() const { return _image.get(); } + + virtual unsigned int getNumColumns() const { return _image.valid() ? _image->s() : 0; } + virtual unsigned int getNumRows() const { return _image.valid() ? _image->t() : 0; } + + virtual bool getValue(unsigned int i, unsigned int j, float& value) const; + virtual bool getValue(unsigned int i, unsigned int j, osg::Vec2& value) const; + virtual bool getValue(unsigned int i, unsigned int j, osg::Vec3& value) const; + virtual bool getValue(unsigned int i, unsigned int j, osg::Vec4& value) const; + + virtual void dirty(); + virtual void setModifiedCount(unsigned int value); + virtual unsigned int getModifiedCount() const; + + protected: + + virtual ~ImageLayer() {} + + osg::ref_ptr _image; + +}; + +class OSGTERRAIN_EXPORT ContourLayer : public Layer +{ + public: + + ContourLayer(osg::TransferFunction1D* tf=0); + + /** Copy constructor using CopyOp to manage deep vs shallow copy.*/ + ContourLayer(const ContourLayer& tfLayer,const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY); + + META_Object(osgTerrain, ContourLayer); + + virtual bool transform(float offset, float scale); + + void setTransferFunction(osg::TransferFunction1D* tf); + osg::TransferFunction1D* getTransferFunction() { return _tf.get(); } + const osg::TransferFunction1D* getTransferFunction() const { return _tf.get(); } + + /** Return image associated with layer. */ + virtual osg::Image* getImage() { return _tf.valid() ? _tf->getImage() : 0; } + + /** Return const image associated with layer. */ + virtual const osg::Image* getImage() const { return _tf.valid() ? _tf->getImage() : 0; } + + + virtual unsigned int getNumColumns() const { return _tf.valid() ? _tf->getNumberImageCells() : 0; } + virtual unsigned int getNumRows() const { return _tf.valid() ? 1 : 0; } + + virtual bool getValue(unsigned int i, unsigned int j, float& value) const; + virtual bool getValue(unsigned int i, unsigned int j, osg::Vec2& value) const; + virtual bool getValue(unsigned int i, unsigned int j, osg::Vec3& value) const; + virtual bool getValue(unsigned int i, unsigned int j, osg::Vec4& value) const; + + virtual void dirty(); + virtual void setModifiedCount(unsigned int value); + virtual unsigned int getModifiedCount() const; + + protected: + + virtual ~ContourLayer() {} + + osg::ref_ptr _tf; + +}; + +class OSGTERRAIN_EXPORT HeightFieldLayer : public Layer +{ + public: + + HeightFieldLayer(osg::HeightField* hf=0); + + /** Copy constructor using CopyOp to manage deep vs shallow copy.*/ + HeightFieldLayer(const HeightFieldLayer& hfLayer,const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY); + + META_Object(osgTerrain, HeightFieldLayer); + + void setFileName(const std::string& filename) { _filename = filename; } + virtual const std::string& getFileName() const { return _filename; } + + virtual bool transform(float offset, float scale); + + void setHeightField(osg::HeightField* hf); + osg::HeightField* getHeightField() { return _heightField.get(); } + const osg::HeightField* getHeightField() const { return _heightField.get(); } + + virtual unsigned int getNumColumns() const { return _heightField.valid() ? _heightField->getNumColumns() : 0; } + virtual unsigned int getNumRows() const { return _heightField.valid() ? _heightField->getNumRows() : 0; } + + virtual bool getValue(unsigned int i, unsigned int j, float& value) const; + virtual bool getValue(unsigned int i, unsigned int j, osg::Vec2& value) const; + virtual bool getValue(unsigned int i, unsigned int j, osg::Vec3& value) const; + virtual bool getValue(unsigned int i, unsigned int j, osg::Vec4& value) const; + + virtual void dirty(); + virtual void setModifiedCount(unsigned int value); + virtual unsigned int getModifiedCount() const; + + protected: + + virtual ~HeightFieldLayer() {} + + unsigned int _modifiedCount; + osg::ref_ptr _heightField; + +}; + + +class OSGTERRAIN_EXPORT ProxyLayer : public Layer +{ + public: + + ProxyLayer(); + + /** Copy constructor using CopyOp to manage deep vs shallow copy.*/ + ProxyLayer(const ProxyLayer& proxyLayer,const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY); + + META_Object(osgTerrain, ProxyLayer); + + /** Return image associated with layer if supported. */ + virtual osg::Image* getImage() + { + return _implementation.valid() ? _implementation->getImage() : 0; + } + + /** Return const image associated with layer if supported. */ + virtual const osg::Image* getImage() const + { + return _implementation.valid() ? _implementation->getImage() : 0; + } + + /** Set the implementation layer that does the actual work.*/ + void setImplementation(Layer* layer) { _implementation = layer; } + + /** Get the implementation layer that does the actual work.*/ + Layer* getImplementation() { return _implementation.get(); } + + /** Get the const implementation layer that does the actual work.*/ + const Layer* getImplementation() const { return _implementation.get(); } + + virtual void setFileName(const std::string& filename); + virtual const std::string& getFileName() const { return _filename; } + + virtual unsigned int getNumColumns() const; + virtual unsigned int getNumRows() const; + + virtual bool transform(float offset, float scale); + + virtual bool getValue(unsigned int i, unsigned int j, float& value) const; + virtual bool getValue(unsigned int i, unsigned int j, osg::Vec2& value) const; + virtual bool getValue(unsigned int i, unsigned int j, osg::Vec3& value) const; + virtual bool getValue(unsigned int i, unsigned int j, osg::Vec4& value) const; + + virtual void dirty(); + virtual void setModifiedCount(unsigned int value); + virtual unsigned int getModifiedCount() const; + + virtual osg::BoundingSphere computeBound(bool treatAsElevationLayer) const; + + protected: + + virtual ~ProxyLayer(); + + osg::ref_ptr _implementation; + + +}; + +class OSGTERRAIN_EXPORT CompositeLayer : public Layer +{ + public: + + CompositeLayer(); + + /** Copy constructor using CopyOp to manage deep vs shallow copy.*/ + CompositeLayer(const CompositeLayer& compositeLayer,const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY); + + META_Object(osgTerrain, CompositeLayer); + + void clear(); + + /** Set the set name of layer 'i'. */ + void setSetName(unsigned int i, const std::string& setname) { _layers[i].setname = setname; if (_layers[i].layer.valid()) _layers[i].layer->setName(setname); } + + /** Get the set name of layer 'i'. */ + const std::string& getSetName(unsigned int i) const { return _layers[i].layer.valid() ? _layers[i].layer->getName() : _layers[i].setname; } + + /** Set the file name of the data associated with layer 'i'. */ + void setFileName(unsigned int i, const std::string& filename) { _layers[i].filename = filename; if (_layers[i].layer.valid()) _layers[i].layer->setFileName(filename); } + + /** Get the file name of the data associated with layer 'i'. */ + const std::string& getFileName(unsigned int i) const { return _layers[i].layer.valid() ? _layers[i].layer->getFileName() : _layers[i].filename; } + + void setCompoundName(unsigned int i, const std::string& compoundname); + std::string getCompoundName(unsigned int i) const; + + + void setLayer(unsigned int i, Layer* layer) { if (i>=_layers.size()) _layers.resize(i+1); _layers[i].layer = layer; } + Layer* getLayer(unsigned int i) { return i<_layers.size() ? _layers[i].layer.get() : 0; } + const Layer* getLayer(unsigned int i) const { return i<_layers.size() ? _layers[i].layer.get() : 0; } + + void addLayer(const std::string& compoundname); + void addLayer(const std::string& setname, const std::string& filename); + + void addLayer(Layer* layer) { _layers.push_back(CompoundNameLayer(layer->getName(),layer->getFileName(),layer)); } + + void removeLayer(unsigned int i) { _layers.erase(_layers.begin()+i); } + + unsigned int getNumLayers() const { return static_cast(_layers.size()); } + + protected: + + virtual ~CompositeLayer() {} + + struct CompoundNameLayer + { + CompoundNameLayer() {} + + CompoundNameLayer(const CompoundNameLayer& cnl): + setname(cnl.setname), + filename(cnl.filename), + layer(cnl.layer) {} + + CompoundNameLayer(const std::string& sn, const std::string& fn, Layer* l): + setname(sn), + filename(fn), + layer(l) {} + + CompoundNameLayer& operator = (const CompoundNameLayer& cnl) + { + if (&cnl==this) return *this; + + setname = cnl.setname; + filename = cnl.filename; + layer = cnl.layer; + return *this; + } + + std::string setname; + std::string filename; + osg::ref_ptr layer; + }; + + typedef std::vector< CompoundNameLayer > Layers; + + Layers _layers; +}; + + +class OSGTERRAIN_EXPORT SwitchLayer : public CompositeLayer +{ + public: + + SwitchLayer(); + + /** Copy constructor using CopyOp to manage deep vs shallow copy.*/ + SwitchLayer(const SwitchLayer& switchLayer,const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY); + + META_Object(osgTerrain, SwitchLayer); + + void setActiveLayer(int i) { _activeLayer = i; } + int getActiveLayer() const { return _activeLayer; } + + /** Return image associated with layer if supported. */ + virtual osg::Image* getImage() + { + if (_activeLayer < 0) return 0; + if (_activeLayer >= static_cast(getNumLayers())) return 0; + return _layers[_activeLayer].layer->getImage(); + } + + /** Return const image associated with layer if supported. */ + virtual const osg::Image* getImage() const + { + if (_activeLayer < 0) return 0; + if (_activeLayer >= static_cast(getNumLayers())) return 0; + return _layers[_activeLayer].layer->getImage(); + } + + protected: + + virtual ~SwitchLayer() {} + + int _activeLayer; +}; + + + +} + +#endif diff --git a/libs/include/android/osgTerrain/Locator b/libs/include/android/osgTerrain/Locator new file mode 100755 index 0000000..16f6546 --- /dev/null +++ b/libs/include/android/osgTerrain/Locator @@ -0,0 +1,132 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGTERRAIN_LOCATOR +#define OSGTERRAIN_LOCATOR 1 + +#include +#include +#include + +#include + +namespace osgTerrain { + +class OSGTERRAIN_EXPORT Locator : public osg::Object +{ + public: + + Locator(); + + /** Copy constructor using CopyOp to manage deep vs shallow copy.*/ + Locator(const Locator&,const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY); + + META_Object(osgTerrain, Locator); + + /** CoordinateSystemType provides the classification of the type coordinate system represented.*/ + enum CoordinateSystemType + { + /** GEOCENTRIC coordinate systems are ones mapped to the around the ellipsoid, i.e. whole earth.*/ + GEOCENTRIC, + + /** GEOGRAPHIC coordinate systems are ones mapped to latitude and longitude.*/ + GEOGRAPHIC, + + /** PROJECTED coordinate systems are ones projected to a local projected coordinate system i.e. UTMs.*/ + PROJECTED + }; + + /** Set the CoordinatesSyetemType. + * Note, the user must keep the CoordinateSystemString consistent with the type of the CoordinateSystem.*/ + void setCoordinateSystemType(CoordinateSystemType type) { _coordinateSystemType = type; } + + /** Get the CoordinatesSyetemType.*/ + CoordinateSystemType getCoordinateSystemType() const { return _coordinateSystemType; } + + /** Set the coordinate system format string. Typical values would be WKT, PROJ4, USGS etc.*/ + void setFormat(const std::string& format) { _format = format; } + + /** Get the coordinate system format string.*/ + const std::string& getFormat() const { return _format; } + + /** Set the CoordinateSystem reference string, should be stored in a form consistent with the Format.*/ + void setCoordinateSystem(const std::string& cs) { _cs = cs; } + + /** Get the CoordinateSystem reference string.*/ + const std::string& getCoordinateSystem() const { return _cs; } + + + /** Set EllipsoidModel to describe the model used to map lat, long and height into geocentric XYZ and back. */ + void setEllipsoidModel(osg::EllipsoidModel* ellipsode) { _ellipsoidModel = ellipsode; } + + /** Get the EllipsoidModel.*/ + osg::EllipsoidModel* getEllipsoidModel() { return _ellipsoidModel.get(); } + + /** Get the const EllipsoidModel.*/ + const osg::EllipsoidModel* getEllipsoidModel() const { return _ellipsoidModel.get(); } + + + /** Set the transformation from local coordinates to model coordinates.*/ + void setTransform(const osg::Matrixd& transform) { _transform = transform; _inverse.invert(_transform); } + + /** Set the transformation from local coordinates to model coordinates.*/ + const osg::Matrixd& getTransform() const { return _transform; } + + /** Set the extents of the local coords.*/ + void setTransformAsExtents(double minX, double minY, double maxX, double maxY); + + + virtual bool orientationOpenGL() const; + + virtual bool convertLocalToModel(const osg::Vec3d& local, osg::Vec3d& world) const; + + virtual bool convertModelToLocal(const osg::Vec3d& world, osg::Vec3d& local) const; + + static bool convertLocalCoordBetween(const Locator& source, const osg::Vec3d& sourceNDC, + const Locator& destination, osg::Vec3d& destinationNDC) + { + osg::Vec3d model; + if (!source.convertLocalToModel(sourceNDC, model)) return false; + if (!destination.convertModelToLocal(model, destinationNDC)) return false; + return true; + } + + bool computeLocalBounds(Locator& source, osg::Vec3d& bottomLeft, osg::Vec3d& topRight) const; + + void setDefinedInFile(bool flag) { _definedInFile = flag; } + bool getDefinedInFile() const { return _definedInFile; } + + void setTransformScaledByResolution(bool scaledByResolution) { _transformScaledByResolution = scaledByResolution; } + bool getTransformScaledByResolution() const { return _transformScaledByResolution; } + + protected: + + virtual ~Locator(); + + CoordinateSystemType _coordinateSystemType; + + std::string _format; + std::string _cs; + osg::ref_ptr _ellipsoidModel; + + osg::Matrixd _transform; + osg::Matrixd _inverse; + + bool _definedInFile; + bool _transformScaledByResolution; + +}; + +} + +#endif diff --git a/libs/include/android/osgTerrain/Terrain b/libs/include/android/osgTerrain/Terrain new file mode 100755 index 0000000..230cf9b --- /dev/null +++ b/libs/include/android/osgTerrain/Terrain @@ -0,0 +1,123 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGTerrain +#define OSGTerrain 1 + +#include +#include + +#include + +namespace osgTerrain { + +/** Terrain provides a framework for loosely coupling height field data with height rendering algorithms. + * This allows TerrainTechniques to be plugged in at runtime.*/ +class OSGTERRAIN_EXPORT Terrain : public osg::CoordinateSystemNode +{ + public: + + Terrain(); + + /** Copy constructor using CopyOp to manage deep vs shallow copy.*/ + Terrain(const Terrain&,const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY); + + META_Node(osgTerrain, Terrain); + + virtual void traverse(osg::NodeVisitor& nv); + + virtual osgTerrain::Terrain* asTerrain() { return this; } + virtual const osgTerrain::Terrain* asTerrain() const { return this; } + + + /** Set the sample ratio hint that TerrainTile should use when building geometry. + * Defaults to 1.0, which means use all original sample points.*/ + void setSampleRatio(float ratio); + + /** Get the sample ratio hint.*/ + float getSampleRatio() const { return _sampleRatio; } + + + /** Set the vertical scale hint.*/ + void setVerticalScale(float scale); + + /** Get the vertical scale hint.*/ + float getVerticalScale() const { return _verticalScale; } + + /** If set to true the boundaries between adjacent tiles should be equalized. + * Note, it is only possible to equalizae boundaries when the TerrainTile's contain properly assigned TileID's, + * databases built with VirtualPlanetBuilder-0.9.11 and older do not set the TileID, so databases must be + * built with later versions of VirtualPlanetBuilder to take advantage of boundary equalization. */ + void setEqualizeBoundaries(bool equalizeBoundaries); + + /** If true the boundaries between adjacent tiles will be equalized. */ + bool getEqualizeBoundaries() const { return _equalizeBoundaries; } + + /** Set the default policy to use when deciding whether to enable/disable blending and use of transparent bin. + * Note, the Terrain::BlendingPolicy value only sets the value for the TerrainTiles it encloses for the + * TerrainTile's that have their policy set to INHERIT. INHERIT is the default BlendingPolicy for both + * Terrain and TerrainTile, and if both are left to INERHIT then the policy used is ENABLE_BLENDING_WHEN_ALPHA_PRESENT. */ + void setBlendingPolicy(TerrainTile::BlendingPolicy policy); + + /** Get the default policy to use when deciding whether to enable/disable blending and use of transparent bin.*/ + TerrainTile::BlendingPolicy getBlendingPolicy() const { return _blendingPolicy; } + + + /** Get the TerrainTile for a given TileID.*/ + TerrainTile* getTile(const TileID& tileID); + + /** Get the const TerrainTile for a given TileID.*/ + const TerrainTile* getTile(const TileID& tileID) const; + + /** Set the TerrainTechnique prototype from which TerrainTiles can clone the techniques from.*/ + void setTerrainTechniquePrototype(TerrainTechnique* technique) { _terrainTechnique = technique; } + + /** Get the TerrainTechnique prototype */ + TerrainTechnique* getTerrainTechniquePrototype() { return _terrainTechnique.get(); } + + /** Get the const TerrainTechnique protype*/ + const TerrainTechnique* getTerrainTechniquePrototype() const { return _terrainTechnique.get(); } + + /** Tell the Terrain node to call the terrainTile's TerrainTechnique on the next update traversal.*/ + void updateTerrainTileOnNextFrame(TerrainTile* terrainTile); + + protected: + + virtual ~Terrain(); + + friend class TerrainTile; + + void dirtyRegisteredTiles(int dirtyMask = TerrainTile::ALL_DIRTY); + + void registerTerrainTile(TerrainTile* tile); + void unregisterTerrainTile(TerrainTile* tile); + + typedef std::map< TileID, TerrainTile* > TerrainTileMap; + typedef std::set< TerrainTile* > TerrainTileSet; + + float _sampleRatio; + float _verticalScale; + TerrainTile::BlendingPolicy _blendingPolicy; + bool _equalizeBoundaries; + + mutable OpenThreads::ReentrantMutex _mutex; + TerrainTileSet _terrainTileSet; + TerrainTileMap _terrainTileMap; + TerrainTileSet _updateTerrainTileSet; + + osg::ref_ptr _terrainTechnique; +}; + +} + +#endif diff --git a/libs/include/android/osgTerrain/TerrainTechnique b/libs/include/android/osgTerrain/TerrainTechnique new file mode 100755 index 0000000..8c3d789 --- /dev/null +++ b/libs/include/android/osgTerrain/TerrainTechnique @@ -0,0 +1,105 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGTERRAIN_TERRAINTECHNIQUE +#define OSGTERRAIN_TERRAINTECHNIQUE 1 + +#include + +#include +#include + +#include + +namespace osgTerrain { + +class TerrainTile; + +class OSGTERRAIN_EXPORT TerrainNeighbours +{ + public: + + TerrainNeighbours(); + ~TerrainNeighbours(); + + void clear(); + void addNeighbour(TerrainTile* tile); + void removeNeighbour(TerrainTile* tile); + bool containsNeighbour(TerrainTile* tile) const; + + protected: + + TerrainNeighbours(const TerrainNeighbours& /*tn*/) {} + TerrainNeighbours& operator = (const TerrainNeighbours& /*rhs*/) { return *this; } + + typedef std::set Neighbours; + + mutable OpenThreads::Mutex _neighboursMutex; + Neighbours _neighbours; +}; + + +class OSGTERRAIN_EXPORT TerrainTechnique : public osg::Object, public osg::Observer +{ + public: + + TerrainTechnique(); + + /** Copy constructor using CopyOp to manage deep vs shallow copy.*/ + TerrainTechnique(const TerrainTechnique&,const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY); + + META_Object(osgTerrain, TerrainTechnique); + + TerrainTile* getTerrainTile() { return _terrainTile; } + const TerrainTile* getTerrainTile() const { return _terrainTile; } + + virtual void init(int dirtyMask, bool assumeMultiThreaded); + + virtual void update(osgUtil::UpdateVisitor* nv); + + virtual void cull(osgUtil::CullVisitor* nv); + + /** Clean scene graph from any terrain technique specific nodes.*/ + virtual void cleanSceneGraph(); + + /** Traverse the terrain subgraph.*/ + virtual void traverse(osg::NodeVisitor& nv); + + /** If State is non-zero, this function releases any associated OpenGL objects for + * the specified graphics context. Otherwise, releases OpenGL objects + * for all graphics contexts. */ + virtual void releaseGLObjects(osg::State* = 0) const {} + + void addNeighbour(TerrainTile* tile) { _neighbours.addNeighbour(tile); } + void removeNeighbour(TerrainTile* tile) { _neighbours.removeNeighbour(tile); } + bool containsNeighbour(TerrainTile* tile) { return _neighbours.containsNeighbour(tile); } + + protected: + + virtual ~TerrainTechnique(); + + void setTerrainTile(TerrainTile* tile); + void setDirty(bool dirty); + + friend class osgTerrain::TerrainTile; + + TerrainTile* _terrainTile; + + + TerrainNeighbours _neighbours; + +}; + +} + +#endif diff --git a/libs/include/android/osgTerrain/TerrainTile b/libs/include/android/osgTerrain/TerrainTile new file mode 100755 index 0000000..f32fd40 --- /dev/null +++ b/libs/include/android/osgTerrain/TerrainTile @@ -0,0 +1,293 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGTERRAIN_TERRAINTILE +#define OSGTERRAIN_TERRAINTILE 1 + +#include +#include + +#include + +#include +#include +#include + +namespace osgTerrain { + +class Terrain; + +class OSGTERRAIN_EXPORT TileID +{ + public: + + TileID(); + + TileID(int in_level, int in_x, int in_y); + + bool operator == (const TileID& rhs) const + { + return (level==rhs.level) && (x==rhs.x) && (y==rhs.y); + } + + bool operator != (const TileID& rhs) const + { + return (level!=rhs.level) || (x!=rhs.x) || (y!=rhs.y); + } + + bool operator < (const TileID& rhs) const + { + if (levelrhs.level) return false; + if (xrhs.x) return false; + return y=0; } + + int level; + int x; + int y; +}; + + +/** Terrain provides a framework for loosely coupling height field data with height rendering algorithms. + * This allows TerrainTechnique's to be plugged in at runtime.*/ +class OSGTERRAIN_EXPORT TerrainTile : public osg::Group +{ + public: + + TerrainTile(); + + /** Copy constructor using CopyOp to manage deep vs shallow copy.*/ + TerrainTile(const TerrainTile&,const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY); + + META_Node(osgTerrain, TerrainTile); + + virtual void traverse(osg::NodeVisitor& nv); + + /** Call init on any attached TerrainTechnique.*/ + void init(int dirtyMask, bool assumeMultiThreaded); + + /** Set the Terrain that this Terrain tile is a member of.*/ + void setTerrain(Terrain* ts); + + /** Get the Terrain that this Terrain tile is a member of.*/ + Terrain* getTerrain() { return _terrain; } + + /** Get the const Terrain that this Terrain tile is a member of.*/ + const Terrain* getTerrain() const { return _terrain; } + + + /** Set the TileID (layer, x,y) of the TerrainTile. + * The TileID is used so it can be located by its neighbours + * via the enclosing Terrain node that manages a map of TileID to TerraiTiles.*/ + void setTileID(const TileID& tileID); + + /** Get the TileID (layer, x,y) of the TerrainTile.*/ + const TileID& getTileID() const { return _tileID; } + + + /** Set the TerrainTechnique*/ + void setTerrainTechnique(TerrainTechnique* terrainTechnique); + + /** Get the TerrainTechnique*/ + TerrainTechnique* getTerrainTechnique() { return _terrainTechnique.get(); } + + /** Get the const TerrainTechnique*/ + const TerrainTechnique* getTerrainTechnique() const { return _terrainTechnique.get(); } + + + /** Set the coordinate frame locator of the terrain node. + * The locator takes non-dimensional s,t coordinates into the X,Y,Z world coords and back.*/ + void setLocator(Locator* locator) { _locator = locator; } + + /** Get the coordinate frame locator of the terrain node.*/ + Locator* getLocator() { return _locator.get(); } + + /** Get the const coordinate frame locator of the terrain node.*/ + const Locator* getLocator() const { return _locator.get(); } + + /** Set the layer to use to define the elevations of the terrain.*/ + void setElevationLayer(Layer* layer); + + /** Get the layer to use to define the elevations of the terrain.*/ + Layer* getElevationLayer() { return _elevationLayer.get(); } + + /** Get the const layer to use to define the elevations of the terrain.*/ + const Layer* getElevationLayer() const { return _elevationLayer.get(); } + + + /** Set a color layer with specified layer number.*/ + void setColorLayer(unsigned int i, Layer* layer); + + /** Get color layer with specified layer number.*/ + Layer* getColorLayer(unsigned int i) { return i<_colorLayers.size() ? _colorLayers[i].get() : 0; } + + /** Set const color layer with specified layer number.*/ + const Layer* getColorLayer(unsigned int i) const { return i<_colorLayers.size() ? _colorLayers[i].get() : 0; } + + /** Get the number of colour layers.*/ + unsigned int getNumColorLayers() const { return static_cast(_colorLayers.size()); } + + + /** Set hint to whether the TerrainTechnique should create per vertex normals for lighting purposes.*/ + void setRequiresNormals(bool flag) { _requiresNormals = flag; } + + /** Get whether the TerrainTechnique should create per vertex normals for lighting purposes.*/ + bool getRequiresNormals() const { return _requiresNormals; } + + + /** Set the hint to whether the TerrainTechnique should treat the invalid Layer entries that at are neigbours to valid entries with the default value.*/ + void setTreatBoundariesToValidDataAsDefaultValue(bool flag) { _treatBoundariesToValidDataAsDefaultValue = flag; } + + /** Get whether the TeatBoundariesToValidDataAsDefaultValue hint.*/ + bool getTreatBoundariesToValidDataAsDefaultValue() const { return _treatBoundariesToValidDataAsDefaultValue; } + + + enum BlendingPolicy + { + INHERIT, /** Default - check for the any BlendingPolicy set on the enclosing osgTerrain::Terrain node, and if it's also INHERIT then assume ENABLE_BLENDING_WHEN_ALPHA_PRESENT. */ + DO_NOT_SET_BLENDING, + ENABLE_BLENDING, + ENABLE_BLENDING_WHEN_ALPHA_PRESENT /** check colour layers for alpha value and if present enable blending. */ + }; + + /** Set the policy to use when deciding whether to enable/disable blending and use of transparent bin.*/ + void setBlendingPolicy(BlendingPolicy policy) { _blendingPolicy = policy; } + + /** Get the policy to use when deciding whether to enable/disable blending and use of transparent bin.*/ + BlendingPolicy getBlendingPolicy() const { return _blendingPolicy; } + + + enum DirtyMask + { + NOT_DIRTY = 0, + IMAGERY_DIRTY = 1<<0, + ELEVATION_DIRTY = 1<<1, + LEFT_EDGE_DIRTY = 1<<2, + RIGHT_EDGE_DIRTY = 1<<3, + TOP_EDGE_DIRTY = 1<<4, + TOP_LEFT_CORNER_DIRTY = 1<<5, + TOP_RIGHT_CORNER_DIRTY = 1<<6, + BOTTOM_EDGE_DIRTY = 1<<7, + BOTTOM_LEFT_CORNER_DIRTY = 1<<8, + BOTTOM_RIGHT_CORNER_DIRTY = 1<<9, + EDGES_DIRTY = LEFT_EDGE_DIRTY | RIGHT_EDGE_DIRTY | TOP_EDGE_DIRTY | BOTTOM_EDGE_DIRTY | + TOP_LEFT_CORNER_DIRTY | TOP_RIGHT_CORNER_DIRTY | BOTTOM_LEFT_CORNER_DIRTY | BOTTOM_RIGHT_CORNER_DIRTY, + ALL_DIRTY = IMAGERY_DIRTY | ELEVATION_DIRTY | EDGES_DIRTY + }; + + /** Set the dirty flag on/off.*/ + void setDirty(bool dirty) { setDirtyMask(dirty ? ALL_DIRTY : NOT_DIRTY); } + + /** return true if the any of the DirtyMask are set.*/ + int getDirty() const { return _dirtyMask!=NOT_DIRTY; } + + + /** Set the dirty flag on/off.*/ + void setDirtyMask(int dirtyMask); + + /** return true if the tile is dirty and needs to be updated,*/ + int getDirtyMask() const { return _dirtyMask; } + + + /** Compute the bounding volume of the terrain by computing the union of the bounding volumes of all layers.*/ + virtual osg::BoundingSphere computeBound() const; + + /** Callback for post processing loaded TerrainTile, and for filling in missing elements such as external external imagery.*/ + struct TileLoadedCallback : public osg::Referenced + { + virtual bool deferExternalLayerLoading() const = 0; + virtual void loaded(osgTerrain::TerrainTile* tile, const osgDB::ReaderWriter::Options* options) const = 0; + }; + + static void setTileLoadedCallback(TileLoadedCallback* lc); + static osg::ref_ptr& getTileLoadedCallback(); + + /** If State is non-zero, this function releases any associated OpenGL objects for + * the specified graphics context. Otherwise, releases OpenGL objects + * for all graphics contexts. */ + virtual void releaseGLObjects(osg::State* = 0) const; + + + protected: + + virtual ~TerrainTile(); + + typedef std::vector< osg::ref_ptr > Layers; + + friend class Terrain; + + Terrain* _terrain; + + int _dirtyMask; + bool _hasBeenTraversal; + + TileID _tileID; + + osg::ref_ptr _terrainTechnique; + osg::ref_ptr _locator; + + osg::ref_ptr _elevationLayer; + + Layers _colorLayers; + + bool _requiresNormals; + bool _treatBoundariesToValidDataAsDefaultValue; + BlendingPolicy _blendingPolicy; +}; + +/** Helper callback for managing optional sets of layers, that loading of is deffered to this callback, + * with this callback working out which layers to load, and how to create fallback versions of the layers. +*/ +class OSGTERRAIN_EXPORT WhiteListTileLoadedCallback : public TerrainTile::TileLoadedCallback +{ + public: + + WhiteListTileLoadedCallback(); + + void allow(const std::string& setname) { _setWhiteList.insert(setname); } + + void setMinimumNumOfLayers(unsigned int numLayers) { _minumumNumberOfLayers = numLayers; } + unsigned int getMinimumNumOfLayers() const { return _minumumNumberOfLayers; } + + void setReplaceSwitchLayer(bool replaceSwitchLayer) { _replaceSwitchLayer = replaceSwitchLayer; } + bool getReplaceSwitchLayer() const { return _replaceSwitchLayer; } + + void setAllowAll(bool allowAll) { _allowAll = allowAll; } + bool getAllowAll() const { return _allowAll; } + + bool layerAcceptable(const std::string& setname) const; + bool readImageLayer(osgTerrain::ImageLayer* imageLayer, const osgDB::ReaderWriter::Options* options) const; + + virtual bool deferExternalLayerLoading() const; + + virtual void loaded(osgTerrain::TerrainTile* tile, const osgDB::ReaderWriter::Options* options) const; + + protected: + + virtual ~WhiteListTileLoadedCallback(); + + typedef std::set SetWhiteList; + SetWhiteList _setWhiteList; + unsigned int _minumumNumberOfLayers; + bool _replaceSwitchLayer; + bool _allowAll; + +}; + +} + +#endif diff --git a/libs/include/android/osgTerrain/ValidDataOperator b/libs/include/android/osgTerrain/ValidDataOperator new file mode 100755 index 0000000..3a0be30 --- /dev/null +++ b/libs/include/android/osgTerrain/ValidDataOperator @@ -0,0 +1,74 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGTERRAIN_VALIDDATAOPERATOR +#define OSGTERRAIN_VALIDDATAOPERATOR 1 + +#include +#include +#include +#include +#include + +namespace osgTerrain { + +struct ValidDataOperator : public osg::Referenced +{ + virtual bool operator() (float /*value*/) const { return true; } + virtual bool operator() (const osg::Vec2& value) const { return operator()(value.x()) && operator()(value.y()) ; } + virtual bool operator() (const osg::Vec3& value) const { return operator()(value.x()) && operator()(value.y()) && operator()(value.z()); } + virtual bool operator() (const osg::Vec4& value) const { return operator()(value.x()) && operator()(value.y()) && operator()(value.z()) && operator()(value.w()); } +}; + +struct ValidRange : public ValidDataOperator +{ + ValidRange(float minValue, float maxValue): + _minValue(minValue), + _maxValue(maxValue) {} + + void setRange(float minValue, float maxValue) + { + _minValue = minValue; + _maxValue = maxValue; + } + + void setMinValue(float minValue) { _minValue = minValue; } + float getMinValue() const { return _minValue; } + + void setMaxValue(float maxValue) { _maxValue = maxValue; } + float getMaxValue() const { return _maxValue; } + + virtual bool operator() (float value) const { return value>=_minValue && value<=_maxValue; } + + float _minValue, _maxValue; +}; + + +struct NoDataValue : public ValidDataOperator +{ + NoDataValue(float value): + _value(value) {} + + void setNoDataValue(float value) { _value = value; } + float getValue() const { return _value; } + + virtual bool operator() (float value) const { return value!=_value; } + + float _value; +}; + +} + +#endif + + diff --git a/libs/include/android/osgTerrain/Version b/libs/include/android/osgTerrain/Version new file mode 100755 index 0000000..8fc391e --- /dev/null +++ b/libs/include/android/osgTerrain/Version @@ -0,0 +1,46 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGTERRAIN_VERSION +#define OSGTERRAIN_VERSION 1 + +#include + +extern "C" { + +/** + * osgTerrainGetVersion() returns the library version number. + * Numbering convention : OpenSceneGraph-1.0 will return 1.0 from osgTerrainGetVersion. + * + * This C function can be also used to check for the existence of the OpenSceneGraph + * library using autoconf and its m4 macro AC_CHECK_LIB. + * + * Here is the code to add to your configure.in: + \verbatim + # + # Check for the OpenSceneGraph (OSG) Terrain library + # + AC_CHECK_LIB(osg, osgTerrainGetVersion, , + [AC_MSG_ERROR(OpenSceneGraph Terrain library not found. See http://www.openscenegraph.org)],) + \endverbatim +*/ +extern OSGTERRAIN_EXPORT const char* osgTerrainGetVersion(); + +/** + * osgTerrainGetLibraryName() returns the library name in human friendly form. +*/ +extern OSGTERRAIN_EXPORT const char* osgTerrainGetLibraryName(); + +} + +#endif diff --git a/libs/include/android/osgText/Export b/libs/include/android/osgText/Export new file mode 100755 index 0000000..06ecf3f --- /dev/null +++ b/libs/include/android/osgText/Export @@ -0,0 +1,49 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGTEXT_EXPORT_ +#define OSGTEXT_EXPORT_ 1 + +#include + +#if defined(_MSC_VER) && defined(OSG_DISABLE_MSVC_WARNINGS) + #pragma warning( disable : 4244 ) + #pragma warning( disable : 4251 ) + #pragma warning( disable : 4267 ) + #pragma warning( disable : 4275 ) + #pragma warning( disable : 4290 ) + #pragma warning( disable : 4786 ) + #pragma warning( disable : 4305 ) + #pragma warning( disable : 4996 ) +#endif + +#if defined(_MSC_VER) || defined(__CYGWIN__) || defined(__MINGW32__) || defined( __BCPLUSPLUS__) + # if defined( OSG_LIBRARY_STATIC ) + # define OSGTEXT_EXPORT + # elif defined( OSGTEXT_LIBRARY ) + # define OSGTEXT_EXPORT __declspec(dllexport) + # else + # define OSGTEXT_EXPORT __declspec(dllimport) + # endif +#else + # define OSGTEXT_EXPORT +#endif + +/** + +\namespace osgText + +The osgText library is a NodeKit that extends the core scene graph to support high quality text. +*/ + +#endif diff --git a/libs/include/android/osgText/FadeText b/libs/include/android/osgText/FadeText new file mode 100755 index 0000000..f3dc87b --- /dev/null +++ b/libs/include/android/osgText/FadeText @@ -0,0 +1,63 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGTEXT_FADETEXT +#define OSGTEXT_FADETEXT 1 + +#include + +namespace osgText { + + +class OSGTEXT_EXPORT FadeText : public osgText::Text +{ +public: + + FadeText(); + FadeText(const Text& text,const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY); + + META_Object(osgText,FadeText) + + + /** Set the speed that the alpha value changes as the text is occluded or becomes visible.*/ + void setFadeSpeed(float fadeSpeed) { _fadeSpeed = fadeSpeed; } + + /** Get the speed that the alpha value changes.*/ + float getFadeSpeed() const { return _fadeSpeed; } + + /** Draw the text.*/ + virtual void drawImplementation(osg::RenderInfo& renderInfo) const; + +protected: + + virtual ~FadeText() {} + + void init(); + + struct FadeTextUpdateCallback; + friend struct FadeTextUpdateCallback; + + typedef std::map ViewBlendColourMap; + + ViewBlendColourMap& getViewBlendColourMap() { return _viewBlendColourMap; } + const ViewBlendColourMap& getViewBlendColourMap() const { return _viewBlendColourMap; } + + float _fadeSpeed; + + mutable ViewBlendColourMap _viewBlendColourMap; +}; + +} + + +#endif diff --git a/libs/include/android/osgText/Font b/libs/include/android/osgText/Font new file mode 100755 index 0000000..6ca7707 --- /dev/null +++ b/libs/include/android/osgText/Font @@ -0,0 +1,253 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGTEXT_FONT +#define OSGTEXT_FONT 1 + +#include +#include + +#include +#include +#include + +#include + +namespace osgText { + +// forward declare Font +class Font; + +/** Read a font from specified file. The filename may contain a path. + * It will search for the font file in the following places in this order: + * - In the current directory + * - All paths defined in OSG_FILE_PATH or OSGFILEPATH environment variable + * - Filename with path stripped: In the current directory + * - Filename with path stripped: All paths defined in OSG_FILE_PATH or OSGFILEPATH + * + * Then the file will be searched in OS specific directories in the following order: + * - Again in the current directory + * - Windows: In C:/winnt/fonts + * - Windows: In C:/windows/fonts + * - Windows: In the fonts directory of the windows install directory + * - Other OS: In /usr/share/fonts/ttf + * - Other OS: In /usr/share/fonts/ttf/western + * - Other OS: In /usr/share/fonts/ttf/decoratives + * + * If the given file could not be found, the path part will be stripped and + * the file will be searched again in the OS specific directories. + */ +extern OSGTEXT_EXPORT Font* readFontFile(const std::string& filename, const osgDB::Options* userOptions = 0); + +/** read a font from specified stream.*/ +extern OSGTEXT_EXPORT Font* readFontStream(std::istream& stream, const osgDB::Options* userOptions = 0); + +extern OSGTEXT_EXPORT osg::ref_ptr readRefFontFile(const std::string& filename, const osgDB::Options* userOptions = 0); + +extern OSGTEXT_EXPORT osg::ref_ptr readRefFontStream(std::istream& stream, const osgDB::Options* userOptions = 0); + +extern OSGTEXT_EXPORT std::string findFontFile(const std::string& str); + +/** Pure virtual base class for fonts. + * Concrete implementation are the DefaultFont found in src/osgText/DefaultFont.cpp + * and FreeTypeFont found in src/osgPlugins/freetype/FreeTypeFont.cpp*/ +class OSGTEXT_EXPORT Font : public osg::Object +{ +// declare the interface to a font. +public: + + // forward declare nested classes. + class FontImplementation; + +public: + Font(FontImplementation* implementation=0); + + virtual osg::Object* cloneType() const { return 0; } // cloneType() not appropriate + virtual osg::Object* clone(const osg::CopyOp&) const { return 0; } // clone() not appropriate + virtual bool isSameKindAs(const osg::Object* obj) const { return dynamic_cast(obj)!=NULL; } + virtual const char* className() const { return "Font"; } + virtual const char* libraryName() const { return "osgText"; } + + virtual std::string getFileName() const; + + static osg::ref_ptr& getDefaultFont(); + + void setTexEnv(osg::TexEnv* texenv) { if (texenv) _texenv = texenv; } + inline osg::TexEnv* getTexEnv() { return _texenv.get(); } + inline const osg::TexEnv* getTexEnv() const { return _texenv.get(); } + + void setStateSet(osg::StateSet* stateset) { _stateset = stateset; } + osg::StateSet* getStateSet() { return _stateset.get(); } + const osg::StateSet* getStateSet() const { return _stateset.get(); } + + + /** Get a kerning (adjustment of spacing of two adjacent character) for specified charcodes, w.r.t the current font size hint.*/ + virtual osg::Vec2 getKerning(unsigned int leftcharcode,unsigned int rightcharcode, KerningType kerningType); + + /** Get a Glyph for specified charcode, and the font size nearest to the current font size hint.*/ + virtual Glyph* getGlyph(const FontResolution& fontSize, unsigned int charcode); + + + /** Get a Glyph3D for specified charcode.*/ + virtual Glyph3D* getGlyph3D(unsigned int charcode); + + /** Return true if this font provides vertical alignments and spacing or glyphs.*/ + virtual bool hasVertical() const; + + /** Get the ascender and descender sizes of the font where supported by the FontImplementation, + * return true on success, return false when not supported.*/ + virtual bool getVerticalSize(float& ascender, float& descender) const { return _implementation ? _implementation->getVerticalSize(ascender, descender) : false; } + + /** Set the margin around each glyph, + * to ensure that texture filtering doesn't bleed adjacent glyph's into each other. + * Default margin is 1 texels.*/ + void setGlyphImageMargin(unsigned int margin); + unsigned int getGlyphImageMargin() const; + + /** Set the margin ratio around each glyph, relative to the glyph's size. + * to ensure that texture filtering doesn't bleed adjacent glyph's into each other. + * Default margin is 0.05.*/ + void setGlyphImageMarginRatio(float margin); + float getGlyphImageMarginRatio() const; + + + /** Set the size of texture to create to store the glyph images when rendering. + * Note, this doesn't affect already created Texture Glhph's.*/ + void setTextureSizeHint(unsigned int width,unsigned int height); + + unsigned int getTextureWidthHint() const; + unsigned int getTextureHeightHint() const; + + /** Set the minification texture filter to use when creating the texture to store the glyph images when rendering. + * Note, this doesn't affect already created Texture Glhph's.*/ + void setMinFilterHint(osg::Texture::FilterMode mode); + osg::Texture::FilterMode getMinFilterHint() const; + + /** Set the magnification texture filter to use when creating the texture to store the glyph images when rendering. + * Note, this doesn't affect already created Texture Glhph's.*/ + void setMagFilterHint(osg::Texture::FilterMode mode); + osg::Texture::FilterMode getMagFilterHint() const; + + unsigned int getFontDepth() const { return _depth; } + + void setNumberCurveSamples(unsigned int numSamples) { _numCurveSamples = numSamples; } + unsigned int getNumberCurveSamples() const { return _numCurveSamples; } + + + // make Text a friend to allow it add and remove its entry in the Font's _textList. + friend class FontImplementation; + + void setImplementation(FontImplementation* implementation); + + FontImplementation* getImplementation(); + const FontImplementation* getImplementation() const; + + /** Set whether to use a mutex to ensure ref() and unref() are thread safe.*/ + virtual void setThreadSafeRefUnref(bool threadSafe); + + /** Resize any per context GLObject buffers to specified size. */ + virtual void resizeGLObjectBuffers(unsigned int maxSize); + + /** If State is non-zero, this function releases OpenGL objects for + * the specified graphics context. Otherwise, releases OpenGL objexts + * for all graphics contexts. */ + virtual void releaseGLObjects(osg::State* state=0) const; + + typedef OpenThreads::Mutex FontMutex; + + typedef std::vector< osg::ref_ptr > GlyphTextureList; + GlyphTextureList& getGlyphTextureList() { return _glyphTextureList; } + +protected: + + virtual ~Font(); + + void addGlyph(const FontResolution& fontRes, unsigned int charcode, Glyph* glyph); + + typedef std::vector< osg::ref_ptr > StateSetList; + typedef std::map< unsigned int, osg::ref_ptr > GlyphMap; + typedef std::map< unsigned int, osg::ref_ptr > Glyph3DMap; + + typedef std::map< FontResolution, GlyphMap > FontSizeGlyphMap; + + mutable OpenThreads::Mutex _glyphMapMutex; + + osg::ref_ptr _texenv; + osg::ref_ptr _stateset; + FontSizeGlyphMap _sizeGlyphMap; + GlyphTextureList _glyphTextureList; + + + Glyph3DMap _glyph3DMap; + + // current active size of font + FontResolution _fontSize; + unsigned int _margin; + float _marginRatio; + + unsigned int _textureWidthHint; + unsigned int _textureHeightHint; + osg::Texture::FilterMode _minFilterHint; + osg::Texture::FilterMode _magFilterHint; + + unsigned int _depth; + unsigned int _numCurveSamples; + + + osg::ref_ptr _implementation; + + +// declare the nested classes. +public: + + class FontImplementation : public osg::Referenced + { + public: + + FontImplementation(): + osg::Referenced(true), + _facade(0) {} + + virtual std::string getFileName() const = 0; + + virtual bool supportsMultipleFontResolutions() const = 0; + + /** Get a Glyph for specified charcode, and the font size nearest to the current font size hint.*/ + virtual Glyph* getGlyph(const FontResolution& fontRes, unsigned int charcode) = 0; + + /** Get a Glyph3D for specified charcode.*/ + virtual Glyph3D* getGlyph3D(unsigned int charcode) = 0; + + /** Get a kerning (adjustment of spacing of two adjacent character) for specified charcodes, w.r.t the current font size hint.*/ + virtual osg::Vec2 getKerning(unsigned int leftcharcode,unsigned int rightcharcode, KerningType kerningType) = 0; + + /** Return true if this font provides vertical alignments and spacing or glyphs.*/ + virtual bool hasVertical() const = 0; + + void addGlyph(const FontResolution& fontRes, unsigned int charcode, Glyph* glyph) + { + _facade->addGlyph(fontRes, charcode, glyph); + } + + Font* _facade; + + virtual bool getVerticalSize(float & /*ascender*/, float & /*descender*/) const { return false; } + }; + + + +}; + +} + +#endif diff --git a/libs/include/android/osgText/Font3D b/libs/include/android/osgText/Font3D new file mode 100755 index 0000000..8d9d05a --- /dev/null +++ b/libs/include/android/osgText/Font3D @@ -0,0 +1,55 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGTEXT_FONT3D +#define OSGTEXT_FONT3D 1 + +#include + +namespace osgText { + +typedef Font Font3D; + +/** deprecated, use readFontFile() instead.*/ +inline Font* readFont3DFile(const std::string& filename, const osgDB::ReaderWriter::Options* userOptions = 0) +{ + return readFontFile(filename,userOptions); +} + +/** deprecated, use readFontStream() instead.*/ +inline Font* readFont3DStream(std::istream& stream, const osgDB::ReaderWriter::Options* userOptions = 0) +{ + return readFontStream(stream, userOptions); +} + +/** deprecated, use readRefFontFile() instead.*/ +inline osg::ref_ptr readRefFont3DFile(const std::string& filename, const osgDB::ReaderWriter::Options* userOptions = 0) +{ + return readRefFontFile(filename, userOptions); +} + +/** deprecated, use readRefFontStream() instead.*/ +inline osg::ref_ptr readRefFont3DStream(std::istream& stream, const osgDB::ReaderWriter::Options* userOptions = 0) +{ + return readRefFontStream(stream, userOptions); +} + +/** deprecated, use findFontFile() instead.*/ +inline std::string findFont3DFile(const std::string& str) +{ + return findFontFile(str); +} + +} + +#endif diff --git a/libs/include/android/osgText/Glyph b/libs/include/android/osgText/Glyph new file mode 100755 index 0000000..b84f4a4 --- /dev/null +++ b/libs/include/android/osgText/Glyph @@ -0,0 +1,296 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2010 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * OpenSceneGraph Public License for more details. +*/ + +#ifndef OSGTEXT_GLYPH +#define OSGTEXT_GLYPH 1 + +#include +#include + +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include + +namespace osgText { + +class Font; +class Text; +class Glyph3D; +class GlyphGeometry; +class GlyphTexture; + +class OSGTEXT_EXPORT Glyph : public osg::Image +{ +public: + + Glyph(Font* font, unsigned int glyphCode); + + Font* getFont() { return _font; } + const Font* getFont() const { return _font; } + + unsigned int getGlyphCode() const { return _glyphCode; } + + void setWidth(float width) { _width = width; } + float getWidth() const { return _width; } + + void setHeight(float height) { _height = height; } + float getHeight() const { return _height; } + + void setHorizontalBearing(const osg::Vec2& bearing); + const osg::Vec2& getHorizontalBearing() const; + + void setHorizontalAdvance(float advance); + float getHorizontalAdvance() const; + + void setVerticalBearing(const osg::Vec2& bearing); + const osg::Vec2& getVerticalBearing() const; + + void setVerticalAdvance(float advance); + float getVerticalAdvance() const; + + void setTexture(GlyphTexture* texture); + GlyphTexture* getTexture(); + const GlyphTexture* getTexture() const; + + void setTexturePosition(int posX,int posY); + int getTexturePositionX() const; + int getTexturePositionY() const; + + void setMinTexCoord(const osg::Vec2& coord); + const osg::Vec2& getMinTexCoord() const; + + void setMaxTexCoord(const osg::Vec2& coord); + const osg::Vec2& getMaxTexCoord() const; + + void subload() const; + +protected: + + virtual ~Glyph(); + + Font* _font; + unsigned int _glyphCode; + + float _width; + float _height; + + osg::Vec2 _horizontalBearing; + float _horizontalAdvance; + + osg::Vec2 _verticalBearing; + float _verticalAdvance; + + GlyphTexture* _texture; + int _texturePosX; + int _texturePosY; + osg::Vec2 _minTexCoord; + osg::Vec2 _maxTexCoord; + + typedef osg::buffered_value GLObjectList; + mutable GLObjectList _globjList; + +}; + +class OSGTEXT_EXPORT GlyphGeometry : public osg::Referenced +{ + public: + + GlyphGeometry(); + + void setup(const Glyph3D* glyph, const Style* style); + + bool match(const Style* style) const; + + osg::Geode* getGeode() const { return _geode.get(); } + osg::Geometry* getGeometry() const { return _geometry.get(); } + + /** Set the VertexArray of the glyph. */ + void setVertexArray(osg::Vec3Array * va) { _vertices = va; } + /** Get the VertexArray of the glyph. */ + osg::Vec3Array * getVertexArray() const { return _vertices.get(); } + + /** Set the VertexArray of the glyph. */ + void setNormalArray(osg::Vec3Array* na) { _normals = na; } + /** Get the NormalArray for the wall face. */ + osg::Vec3Array* getNormalArray() const { return _normals.get(); } + + /** Get the PrimitiveSetList for the front face. */ + osg::Geometry::PrimitiveSetList& getFrontPrimitiveSetList() { return _frontPrimitiveSetList; } + /** Get the PrimitiveSetList for the wall face. */ + osg::Geometry::PrimitiveSetList& getWallPrimitiveSetList() { return _wallPrimitiveSetList; } + /** Get et the PrimitiveSetList for the back face. */ + osg::Geometry::PrimitiveSetList& getBackPrimitiveSetList() { return _backPrimitiveSetList; } + + /** Set whether to use a mutex to ensure ref() and unref() are thread safe.*/ + virtual void setThreadSafeRefUnref(bool threadSafe); + + protected: + + osg::ref_ptr