Showing preview only (325K chars total). Download the full file or copy to clipboard to get everything.
Repository: kbranigan/Simple-OpenGL-Image-Library
Branch: master
Commit: 7a056e19c3b2
Files: 25
Total size: 313.6 KB
Directory structure:
gitextract_7lf2bp5s/
├── .gitignore
├── CMakeLists.txt
├── Makefile
├── README.md
├── projects/
│ ├── VC6/
│ │ ├── SOIL.dsp
│ │ └── SOIL.dsw
│ ├── VC7.1/
│ │ ├── SOIL.sln
│ │ └── SOIL.vcproj
│ ├── VC8/
│ │ ├── SOIL.sln
│ │ └── SOIL.vcproj
│ ├── VC9/
│ │ ├── SOIL.sln
│ │ └── SOIL.vcproj
│ └── codeblocks/
│ └── SOIL.cbp
├── soil.html
└── src/
├── SOIL.c
├── SOIL.h
├── image_DXT.c
├── image_DXT.h
├── image_helper.c
├── image_helper.h
├── stb_image_aug.c
├── stb_image_aug.h
├── stbi_DDS_aug.h
├── stbi_DDS_aug_c.h
└── test_SOIL.cpp
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
# Prerequisites
*.d
# Compiled Object files
*.slo
*.lo
*.o
*.obj
# Precompiled Headers
*.gch
*.pch
# Compiled Dynamic libraries
*.so
*.dylib
*.dll
# Fortran module files
*.mod
*.smod
# Compiled Static libraries
*.lai
*.la
*.a
*.lib
# Executables
*.exe
*.out
*.app
# Local builds
build*
Debug*
Release*
*.ipch
*.suo
*VC.db
*.vcxproj
*.vcxproj.filters
================================================
FILE: CMakeLists.txt
================================================
cmake_minimum_required (VERSION 2.6)
project (SOIL)
set (SOIL_BUILD_TESTS false CACHE BOOL "Build tests")
if(ANDROID)
# Android requires GL ES 2.0 package automatically
set(LIBRARIES GLESv2)
else()
find_package (OpenGL REQUIRED)
include_directories (${OPENGL_INCLUDE_DIR})
set(LIBRARIES ${OPENGL_LIBRARIES})
endif()
file (GLOB SOIL_SOURCES src/*.c)
file (GLOB SOIL_HEADERS src/*.h)
add_library (SOIL ${SOIL_SOURCES} ${SOIL_HEADERS})
target_link_libraries (SOIL ${LIBRARIES})
install (TARGETS SOIL
LIBRARY DESTINATION lib
ARCHIVE DESTINATION lib)
install (FILES ${SOIL_HEADERS} DESTINATION include/SOIL)
if (SOIL_BUILD_TESTS)
add_executable (test_SOIL src/test_SOIL.cpp)
target_link_libraries (test_SOIL SOIL)
install (TARGETS SOIL test_SOIL RUNTIME DESTINATION bin)
endif ()
================================================
FILE: Makefile
================================================
# SOIL makefile for linux (based on the AngelScript makefile)
# Type 'make' then 'make install' to complete the installation of the library
# For 'make install' to work, set LOCAL according to your system configuration
PREFIX = /usr/local
LOCAL = $(PREFIX)
LIB = libSOIL.a
INC = SOIL.h
SRCDIR = src
LIBDIR = lib
INCDIR = src
OBJDIR = obj
CFLAGS ?= -O2 -s -Wall
DELETER = rm -f
COPIER = cp
SRCNAMES = \
image_helper.c \
stb_image_aug.c \
image_DXT.c \
SOIL.c \
OBJ = $(addprefix $(OBJDIR)/, $(notdir $(SRCNAMES:.c=.o)))
BIN = $(LIBDIR)/$(LIB)
all: $(BIN)
$(BIN): $(OBJ)
mkdir -p $(LIBDIR)
$(DELETER) $(BIN)
ar r $(BIN) $(OBJ)
ranlib $(BIN)
@echo -------------------------------------------------------------------
@echo Done. As root, type 'make install' to install the library.
$(OBJDIR)/%.o: $(SRCDIR)/%.c
mkdir -p $(OBJDIR)
$(CC) $(CFLAGS) -o $@ -c $<
clean:
$(DELETER) $(OBJ) $(BIN)
$(LOCAL)/lib/:
mkdir $(LOCAL)/lib
$(LOCAL)/include/:
mkdir $(LOCAL)/include
install: $(BIN) $(LOCAL)/lib/ $(LOCAL)/include/
@echo Installing to: $(LOCAL)/lib and $(LOCAL)/include...
@echo -------------------------------------------------------------------
$(COPIER) $(BIN) $(LOCAL)/lib/
$(COPIER) $(INCDIR)/$(INC) $(LOCAL)/include/
@echo -------------------------------------------------------------------
@echo SOIL library installed. Enjoy!
uninstall:
$(DELETER) $(LOCAL)/include/$(INC) $(LOCAL)/lib/$(LIB)
@echo -------------------------------------------------------------------
@echo SOIL library uninstalled.
.PHONY: all clean install uninstall
================================================
FILE: README.md
================================================
This is a clone of Simple OpenGL Image Library from http://lonesock.net/soil.html which hasn't changed since July 7, 2008.
I wanted to work with the code and seeing it was MIT license and the original svn repo is offline, I figured it was acceptable to post it here.
Features:
=========
* Readable Image Formats:
* BMP - non-1bpp, non-RLE (from stb_image documentation)
* PNG - non-interlaced (from stb_image documentation)
* JPG - JPEG baseline (from stb_image documentation)
* TGA - greyscale or RGB or RGBA or indexed, uncompressed or RLE
* DDS - DXT1/2/3/4/5, uncompressed, cubemaps (can't read 3D DDS files yet)
* PSD - (from stb_image documentation)
* HDR - converted to LDR, unless loaded with *HDR* functions (RGBE or RGBdivA or RGBdivA2)
* Writeable Image Formats:
* TGA - Greyscale or RGB or RGBA, uncompressed
* BMP - RGB, uncompressed
* DDS - RGB as DXT1, or RGBA as DXT5
* Can load an image file directly into a 2D OpenGL texture, optionally performing the following functions:
* Can generate a new texture handle, or reuse one specified
* Can automatically rescale the image to the next largest power-of-two size
* Can automatically create MIPmaps
* Can scale (not simply clamp) the RGB values into the "safe range" for NTSC displays (16 to 235, as recommended here)
* Can multiply alpha on load (for more correct blending / compositing)
* Can flip the image vertically
* Can compress and upload any image as DXT1 or DXT5 (if EXT_texture_compression_s3tc is available), using an internal (very fast!) compressor
* Can convert the RGB to YCoCg color space (useful with DXT5 compression: see this link from NVIDIA)
* Will automatically downsize a texture if it is larger than GL_MAX_TEXTURE_SIZE
* Can directly upload DDS files (DXT1/3/5/uncompressed/cubemap, with or without MIPmaps). Note: directly uploading the compressed DDS image will disable the other options (no flipping, no pre-multiplying alpha, no rescaling, no creation of MIPmaps, no auto-downsizing)
* Can load rectangluar textures for GUI elements or splash screens (requires GL_ARB/EXT/NV_texture_rectangle)
* Can decompress images from RAM (e.g. via PhysicsFS or similar) into an OpenGL texture (same features as regular 2D textures, above)
* Can load cube maps directly into an OpenGL texture (same features as regular 2D textures, above)
* Can take six image files directly into an OpenGL cube map texture
* Can take a single image file where width = 6*height (or vice versa), split it into an OpenGL cube map texture
* No external dependencies
* Tiny
* Cross platform (Windows, *nix, Mac OS X)
* Public Domain
Usage:
=======
SOIL is meant to be used as a static library (as it's tiny and in the public domain). You can use the static library file included in the zip (libSOIL.a works for MinGW and Microsoft compilers...feel free to rename it to SOIL.lib if that makes you happy), or compile the library yourself. The code is cross-platform and has been tested on Windows, Linux, and Mac. (The heaviest testing has been on the Windows platform, so feel free to email me if you find any issues with other platforms.)
Simply include SOIL.h in your C or C++ file, link in the static library, and then use any of SOIL's functions. The file SOIL.h contains simple doxygen style documentation. (If you use the static library, no other header files are needed besides SOIL.h) Below are some simple usage examples:
load an image file directly as a new OpenGL texture
GLuint tex_2d = SOIL_load_OGL_texture
(
"img.png",
SOIL_LOAD_AUTO,
SOIL_CREATE_NEW_ID,
SOIL_FLAG_MIPMAPS | SOIL_FLAG_INVERT_Y | SOIL_FLAG_NTSC_SAFE_RGB | SOIL_FLAG_COMPRESS_TO_DXT
);
check for an error during the load process
if( 0 == tex_2d )
{
printf( "SOIL loading error: '%s'\n", SOIL_last_result() );
}
load another image, but into the same texture ID, overwriting the last one
tex_2d = SOIL_load_OGL_texture
(
"some_other_img.dds",
SOIL_LOAD_AUTO,
tex_2d,
SOIL_FLAG_DDS_LOAD_DIRECT
);
load 6 images into a new OpenGL cube map, forcing RGB
GLuint tex_cube = SOIL_load_OGL_cubemap
(
"xp.jpg",
"xn.jpg",
"yp.jpg",
"yn.jpg",
"zp.jpg",
"zn.jpg",
SOIL_LOAD_RGB,
SOIL_CREATE_NEW_ID,
SOIL_FLAG_MIPMAPS
);
load and split a single image into a new OpenGL cube map, default format
face order = East South West North Up Down => "ESWNUD", case sensitive!
GLuint single_tex_cube = SOIL_load_OGL_single_cubemap
(
"split_cubemap.png",
"EWUDNS",
SOIL_LOAD_AUTO,
SOIL_CREATE_NEW_ID,
SOIL_FLAG_MIPMAPS
);
actually, load a DDS cubemap over the last OpenGL cube map, default format
try to load it directly, but give the order of the faces in case that fails
the DDS cubemap face order is pre-defined as SOIL_DDS_CUBEMAP_FACE_ORDER
single_tex_cube = SOIL_load_OGL_single_cubemap
(
"overwrite_cubemap.dds",
SOIL_DDS_CUBEMAP_FACE_ORDER,
SOIL_LOAD_AUTO,
single_tex_cube,
SOIL_FLAG_MIPMAPS | SOIL_FLAG_DDS_LOAD_DIRECT
);
load an image as a heightmap, forcing greyscale (so channels should be 1)
int width, height, channels;
unsigned char *ht_map = SOIL_load_image
(
"terrain.tga",
&width, &height, &channels,
SOIL_LOAD_L
);
save that image as another type
int save_result = SOIL_save_image
(
"new_terrain.dds",
SOIL_SAVE_TYPE_DDS,
width, height, channels,
ht_map
);
save a screenshot of your awesome OpenGL game engine, running at 1024x768
save_result = SOIL_save_screenshot
(
"awesomenessity.bmp",
SOIL_SAVE_TYPE_BMP,
0, 0, 1024, 768
);
loaded a file via PhysicsFS, need to decompress the image from RAM,
where it's in a buffer: unsigned char *image_in_RAM
GLuint tex_2d_from_RAM = SOIL_load_OGL_texture_from_memory
(
image_in_RAM,
image_in_RAM_bytes,
SOIL_LOAD_AUTO,
SOIL_CREATE_NEW_ID,
SOIL_FLAG_MIPMAPS | SOIL_FLAG_INVERT_Y | SOIL_FLAG_COMPRESS_TO_DXT
);
done with the heightmap, free up the RAM
SOIL_free_image_data( ht_map );
================================================
FILE: projects/VC6/SOIL.dsp
================================================
# Microsoft Developer Studio Project File - Name="SOIL" - Package Owner=<4>
# Microsoft Developer Studio Generated Build File, Format Version 6.00
# ** DO NOT EDIT **
# TARGTYPE "Win32 (x86) Static Library" 0x0104
CFG=SOIL - Win32 Debug
!MESSAGE This is not a valid makefile. To build this project using NMAKE,
!MESSAGE use the Export Makefile command and run
!MESSAGE
!MESSAGE NMAKE /f "SOIL.mak".
!MESSAGE
!MESSAGE You can specify a configuration when running NMAKE
!MESSAGE by defining the macro CFG on the command line. For example:
!MESSAGE
!MESSAGE NMAKE /f "SOIL.mak" CFG="SOIL - Win32 Debug"
!MESSAGE
!MESSAGE Possible choices for configuration are:
!MESSAGE
!MESSAGE "SOIL - Win32 Release" (based on "Win32 (x86) Static Library")
!MESSAGE "SOIL - Win32 Debug" (based on "Win32 (x86) Static Library")
!MESSAGE
# Begin Project
# PROP AllowPerConfigDependencies 0
# PROP Scc_ProjName ""
# PROP Scc_LocalPath ""
CPP=cl.exe
RSC=rc.exe
!IF "$(CFG)" == "SOIL - Win32 Release"
# PROP BASE Use_MFC 0
# PROP BASE Use_Debug_Libraries 0
# PROP BASE Output_Dir "Release"
# PROP BASE Intermediate_Dir "Release"
# PROP BASE Target_Dir ""
# PROP Use_MFC 0
# PROP Use_Debug_Libraries 0
# PROP Output_Dir "Release"
# PROP Intermediate_Dir "Release"
# PROP Target_Dir ""
# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /YX /FD /c
# ADD CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /YX /FD /c
# ADD BASE RSC /l 0x409 /d "NDEBUG"
# ADD RSC /l 0x409 /d "NDEBUG"
BSC32=bscmake.exe
# ADD BASE BSC32 /nologo
# ADD BSC32 /nologo
LIB32=link.exe -lib
# ADD BASE LIB32 /nologo
# ADD LIB32 /nologo
!ELSEIF "$(CFG)" == "SOIL - Win32 Debug"
# PROP BASE Use_MFC 0
# PROP BASE Use_Debug_Libraries 1
# PROP BASE Output_Dir "Debug"
# PROP BASE Intermediate_Dir "Debug"
# PROP BASE Target_Dir ""
# PROP Use_MFC 0
# PROP Use_Debug_Libraries 1
# PROP Output_Dir "Debug"
# PROP Intermediate_Dir "Debug"
# PROP Target_Dir ""
# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "_LIB" /YX /FD /GZ /c
# ADD CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "_LIB" /YX /FD /GZ /c
# ADD BASE RSC /l 0x409 /d "_DEBUG"
# ADD RSC /l 0x409 /d "_DEBUG"
BSC32=bscmake.exe
# ADD BASE BSC32 /nologo
# ADD BSC32 /nologo
LIB32=link.exe -lib
# ADD BASE LIB32 /nologo
# ADD LIB32 /nologo
!ENDIF
# Begin Target
# Name "SOIL - Win32 Release"
# Name "SOIL - Win32 Debug"
# Begin Group "Source Files"
# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"
# Begin Source File
SOURCE=..\..\src\image_DXT.c
# End Source File
# Begin Source File
SOURCE=..\..\src\image_helper.c
# End Source File
# Begin Source File
SOURCE=..\..\src\SOIL.c
# End Source File
# Begin Source File
SOURCE=..\..\src\stb_image_aug.c
# End Source File
# End Group
# Begin Group "Header Files"
# PROP Default_Filter "h;hpp;hxx;hm;inl"
# Begin Source File
SOURCE=..\..\src\image_DXT.h
# End Source File
# Begin Source File
SOURCE=..\..\src\image_helper.h
# End Source File
# Begin Source File
SOURCE=..\..\src\SOIL.h
# End Source File
# Begin Source File
SOURCE=..\..\src\stb_image_aug.h
# End Source File
# Begin Source File
SOURCE=..\..\src\stbi_DDS_aug.h
# End Source File
# Begin Source File
SOURCE=..\..\src\stbi_DDS_aug_c.h
# End Source File
# End Group
# End Target
# End Project
================================================
FILE: projects/VC6/SOIL.dsw
================================================
Microsoft Developer Studio Workspace File, Format Version 6.00
# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE!
###############################################################################
Project: "SOIL"=".\SOIL.dsp" - Package Owner=<4>
Package=<5>
{{{
}}}
Package=<4>
{{{
}}}
###############################################################################
Global:
Package=<5>
{{{
}}}
Package=<3>
{{{
}}}
###############################################################################
================================================
FILE: projects/VC7.1/SOIL.sln
================================================
Microsoft Visual Studio Solution File, Format Version 8.00
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "SOIL", "SOIL.vcproj", "{35D9B7E3-EE73-4C06-9B98-FCB7F7644C99}"
ProjectSection(ProjectDependencies) = postProject
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfiguration) = preSolution
Debug = Debug
Release = Release
EndGlobalSection
GlobalSection(ProjectConfiguration) = postSolution
{35D9B7E3-EE73-4C06-9B98-FCB7F7644C99}.Debug.ActiveCfg = Debug|Win32
{35D9B7E3-EE73-4C06-9B98-FCB7F7644C99}.Debug.Build.0 = Debug|Win32
{35D9B7E3-EE73-4C06-9B98-FCB7F7644C99}.Release.ActiveCfg = Release|Win32
{35D9B7E3-EE73-4C06-9B98-FCB7F7644C99}.Release.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
EndGlobalSection
GlobalSection(ExtensibilityAddIns) = postSolution
EndGlobalSection
EndGlobal
================================================
FILE: projects/VC7.1/SOIL.vcproj
================================================
<?xml version="1.0" encoding="Windows-1252"?>
<VisualStudioProject
ProjectType="Visual C++"
Version="7.10"
Name="SOIL"
ProjectGUID="{35D9B7E3-EE73-4C06-9B98-FCB7F7644C99}"
Keyword="Win32Proj">
<Platforms>
<Platform
Name="Win32"/>
</Platforms>
<Configurations>
<Configuration
Name="Debug|Win32"
OutputDirectory="Debug"
IntermediateDirectory="Debug"
ConfigurationType="4"
CharacterSet="2">
<Tool
Name="VCCLCompilerTool"
Optimization="0"
PreprocessorDefinitions="WIN32;_DEBUG;_LIB"
MinimalRebuild="TRUE"
BasicRuntimeChecks="3"
RuntimeLibrary="5"
UsePrecompiledHeader="0"
WarningLevel="3"
Detect64BitPortabilityProblems="TRUE"
DebugInformationFormat="4"/>
<Tool
Name="VCCustomBuildTool"/>
<Tool
Name="VCLibrarianTool"
OutputFile="$(OutDir)/SOIL.lib"/>
<Tool
Name="VCMIDLTool"/>
<Tool
Name="VCPostBuildEventTool"/>
<Tool
Name="VCPreBuildEventTool"/>
<Tool
Name="VCPreLinkEventTool"/>
<Tool
Name="VCResourceCompilerTool"/>
<Tool
Name="VCWebServiceProxyGeneratorTool"/>
<Tool
Name="VCXMLDataGeneratorTool"/>
<Tool
Name="VCManagedWrapperGeneratorTool"/>
<Tool
Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
</Configuration>
<Configuration
Name="Release|Win32"
OutputDirectory="Release"
IntermediateDirectory="Release"
ConfigurationType="4"
CharacterSet="2">
<Tool
Name="VCCLCompilerTool"
PreprocessorDefinitions="WIN32;NDEBUG;_LIB"
RuntimeLibrary="4"
UsePrecompiledHeader="0"
WarningLevel="3"
Detect64BitPortabilityProblems="TRUE"
DebugInformationFormat="3"/>
<Tool
Name="VCCustomBuildTool"/>
<Tool
Name="VCLibrarianTool"
OutputFile="$(OutDir)/SOIL.lib"/>
<Tool
Name="VCMIDLTool"/>
<Tool
Name="VCPostBuildEventTool"/>
<Tool
Name="VCPreBuildEventTool"/>
<Tool
Name="VCPreLinkEventTool"/>
<Tool
Name="VCResourceCompilerTool"/>
<Tool
Name="VCWebServiceProxyGeneratorTool"/>
<Tool
Name="VCXMLDataGeneratorTool"/>
<Tool
Name="VCManagedWrapperGeneratorTool"/>
<Tool
Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
</Configuration>
</Configurations>
<References>
</References>
<Files>
<Filter
Name="Source Files"
Filter="cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx"
UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}">
<File
RelativePath="..\..\src\image_DXT.c">
</File>
<File
RelativePath="..\..\src\image_helper.c">
</File>
<File
RelativePath="..\..\src\SOIL.c">
</File>
<File
RelativePath="..\..\src\stb_image_aug.c">
</File>
</Filter>
<Filter
Name="Header Files"
Filter="h;hpp;hxx;hm;inl;inc;xsd"
UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}">
<File
RelativePath="..\..\src\image_DXT.h">
</File>
<File
RelativePath="..\..\src\image_helper.h">
</File>
<File
RelativePath="..\..\src\SOIL.h">
</File>
<File
RelativePath="..\..\src\stb_image_aug.h">
</File>
<File
RelativePath="..\..\src\stbi_DDS_aug.h">
</File>
<File
RelativePath="..\..\src\stbi_DDS_aug_c.h">
</File>
</Filter>
<Filter
Name="Resource Files"
Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx"
UniqueIdentifier="{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}">
</Filter>
<File
RelativePath=".\ReadMe.txt">
</File>
</Files>
<Globals>
</Globals>
</VisualStudioProject>
================================================
FILE: projects/VC8/SOIL.sln
================================================
Microsoft Visual Studio Solution File, Format Version 9.00
# Visual Studio 2005
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "SOIL", "SOIL.vcproj", "{C32FB2B4-500C-43CD-A099-EECCE079D3F1}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Win32 = Debug|Win32
Release|Win32 = Release|Win32
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{C32FB2B4-500C-43CD-A099-EECCE079D3F1}.Debug|Win32.ActiveCfg = Debug|Win32
{C32FB2B4-500C-43CD-A099-EECCE079D3F1}.Debug|Win32.Build.0 = Debug|Win32
{C32FB2B4-500C-43CD-A099-EECCE079D3F1}.Release|Win32.ActiveCfg = Release|Win32
{C32FB2B4-500C-43CD-A099-EECCE079D3F1}.Release|Win32.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
================================================
FILE: projects/VC8/SOIL.vcproj
================================================
<?xml version="1.0" encoding="Windows-1252"?>
<VisualStudioProject
ProjectType="Visual C++"
Version="8.00"
Name="SOIL"
ProjectGUID="{C32FB2B4-500C-43CD-A099-EECCE079D3F1}"
RootNamespace="SOIL"
Keyword="Win32Proj"
>
<Platforms>
<Platform
Name="Win32"
/>
</Platforms>
<ToolFiles>
</ToolFiles>
<Configurations>
<Configuration
Name="Debug|Win32"
OutputDirectory="$(SolutionDir)$(ConfigurationName)"
IntermediateDirectory="$(ConfigurationName)"
ConfigurationType="4"
CharacterSet="1"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="0"
PreprocessorDefinitions="WIN32;_DEBUG;_LIB"
MinimalRebuild="true"
BasicRuntimeChecks="3"
RuntimeLibrary="3"
UsePrecompiledHeader="0"
WarningLevel="3"
Detect64BitPortabilityProblems="true"
DebugInformationFormat="4"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLibrarianTool"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
<Configuration
Name="Release|Win32"
OutputDirectory="$(SolutionDir)$(ConfigurationName)"
IntermediateDirectory="$(ConfigurationName)"
ConfigurationType="4"
CharacterSet="1"
WholeProgramOptimization="1"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
/>
<Tool
Name="VCCLCompilerTool"
PreprocessorDefinitions="WIN32;NDEBUG;_LIB"
RuntimeLibrary="2"
UsePrecompiledHeader="0"
WarningLevel="3"
Detect64BitPortabilityProblems="true"
DebugInformationFormat="3"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLibrarianTool"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
</Configurations>
<References>
</References>
<Files>
<Filter
Name="Source Files"
Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"
>
<File
RelativePath="..\..\src\image_DXT.c"
>
</File>
<File
RelativePath="..\..\src\image_helper.c"
>
</File>
<File
RelativePath="..\..\src\SOIL.c"
>
</File>
<File
RelativePath="..\..\src\stb_image_aug.c"
>
</File>
</Filter>
<Filter
Name="Header Files"
Filter="h;hpp;hxx;hm;inl;inc;xsd"
UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"
>
<File
RelativePath="..\..\src\image_DXT.h"
>
</File>
<File
RelativePath="..\..\src\image_helper.h"
>
</File>
<File
RelativePath="..\..\src\SOIL.h"
>
</File>
<File
RelativePath="..\..\src\stb_image_aug.h"
>
</File>
<File
RelativePath="..\..\src\stbi_DDS_aug.h"
>
</File>
<File
RelativePath="..\..\src\stbi_DDS_aug_c.h"
>
</File>
</Filter>
<Filter
Name="Resource Files"
Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav"
UniqueIdentifier="{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}"
>
</Filter>
<File
RelativePath=".\ReadMe.txt"
>
</File>
</Files>
<Globals>
</Globals>
</VisualStudioProject>
================================================
FILE: projects/VC9/SOIL.sln
================================================
Microsoft Visual Studio Solution File, Format Version 10.00
# Visual Studio 2008
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "SOIL", "SOIL.vcproj", "{C32FB2B4-500C-43CD-A099-EECCE079D3F1}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Win32 = Debug|Win32
Debug|x64 = Debug|x64
Release|Win32 = Release|Win32
Release|x64 = Release|x64
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{C32FB2B4-500C-43CD-A099-EECCE079D3F1}.Debug|Win32.ActiveCfg = Debug|Win32
{C32FB2B4-500C-43CD-A099-EECCE079D3F1}.Debug|Win32.Build.0 = Debug|Win32
{C32FB2B4-500C-43CD-A099-EECCE079D3F1}.Debug|x64.ActiveCfg = Debug|x64
{C32FB2B4-500C-43CD-A099-EECCE079D3F1}.Debug|x64.Build.0 = Debug|x64
{C32FB2B4-500C-43CD-A099-EECCE079D3F1}.Release|Win32.ActiveCfg = Release|Win32
{C32FB2B4-500C-43CD-A099-EECCE079D3F1}.Release|Win32.Build.0 = Release|Win32
{C32FB2B4-500C-43CD-A099-EECCE079D3F1}.Release|x64.ActiveCfg = Release|x64
{C32FB2B4-500C-43CD-A099-EECCE079D3F1}.Release|x64.Build.0 = Release|x64
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
================================================
FILE: projects/VC9/SOIL.vcproj
================================================
<?xml version="1.0" encoding="Windows-1252"?>
<VisualStudioProject
ProjectType="Visual C++"
Version="9.00"
Name="SOIL"
ProjectGUID="{C32FB2B4-500C-43CD-A099-EECCE079D3F1}"
RootNamespace="SOIL"
Keyword="Win32Proj"
TargetFrameworkVersion="131072"
>
<Platforms>
<Platform
Name="Win32"
/>
<Platform
Name="x64"
/>
</Platforms>
<ToolFiles>
</ToolFiles>
<Configurations>
<Configuration
Name="Debug|Win32"
OutputDirectory="$(SolutionDir)$(ConfigurationName)"
IntermediateDirectory="$(ConfigurationName)"
ConfigurationType="4"
CharacterSet="1"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="0"
PreprocessorDefinitions="WIN32;_DEBUG;_LIB"
MinimalRebuild="true"
BasicRuntimeChecks="3"
RuntimeLibrary="3"
UsePrecompiledHeader="0"
WarningLevel="3"
Detect64BitPortabilityProblems="true"
DebugInformationFormat="4"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLibrarianTool"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
<Configuration
Name="Release|Win32"
OutputDirectory="$(SolutionDir)$(ConfigurationName)"
IntermediateDirectory="$(ConfigurationName)"
ConfigurationType="4"
CharacterSet="1"
WholeProgramOptimization="1"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
/>
<Tool
Name="VCCLCompilerTool"
PreprocessorDefinitions="WIN32;NDEBUG;_LIB"
RuntimeLibrary="2"
UsePrecompiledHeader="0"
WarningLevel="3"
Detect64BitPortabilityProblems="true"
DebugInformationFormat="3"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLibrarianTool"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
<Configuration
Name="Debug|x64"
OutputDirectory="$(SolutionDir)$(PlatformName)\$(ConfigurationName)"
IntermediateDirectory="$(PlatformName)\$(ConfigurationName)"
ConfigurationType="4"
CharacterSet="1"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
TargetEnvironment="3"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="0"
PreprocessorDefinitions="WIN32;_DEBUG;_LIB"
MinimalRebuild="true"
BasicRuntimeChecks="3"
RuntimeLibrary="3"
UsePrecompiledHeader="0"
WarningLevel="3"
Detect64BitPortabilityProblems="true"
DebugInformationFormat="3"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLibrarianTool"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
<Configuration
Name="Release|x64"
OutputDirectory="$(SolutionDir)$(PlatformName)\$(ConfigurationName)"
IntermediateDirectory="$(PlatformName)\$(ConfigurationName)"
ConfigurationType="4"
CharacterSet="1"
WholeProgramOptimization="1"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
TargetEnvironment="3"
/>
<Tool
Name="VCCLCompilerTool"
PreprocessorDefinitions="WIN32;NDEBUG;_LIB"
RuntimeLibrary="2"
UsePrecompiledHeader="0"
WarningLevel="3"
Detect64BitPortabilityProblems="true"
DebugInformationFormat="3"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLibrarianTool"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
</Configurations>
<References>
</References>
<Files>
<Filter
Name="Source Files"
Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"
>
<File
RelativePath="..\..\src\image_DXT.c"
>
</File>
<File
RelativePath="..\..\src\image_helper.c"
>
</File>
<File
RelativePath="..\..\src\SOIL.c"
>
</File>
<File
RelativePath="..\..\src\stb_image_aug.c"
>
</File>
</Filter>
<Filter
Name="Header Files"
Filter="h;hpp;hxx;hm;inl;inc;xsd"
UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"
>
<File
RelativePath="..\..\src\image_DXT.h"
>
</File>
<File
RelativePath="..\..\src\image_helper.h"
>
</File>
<File
RelativePath="..\..\src\SOIL.h"
>
</File>
<File
RelativePath="..\..\src\stb_image_aug.h"
>
</File>
<File
RelativePath="..\..\src\stbi_DDS_aug.h"
>
</File>
<File
RelativePath="..\..\src\stbi_DDS_aug_c.h"
>
</File>
</Filter>
<Filter
Name="Resource Files"
Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav"
UniqueIdentifier="{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}"
>
</Filter>
<File
RelativePath=".\ReadMe.txt"
>
</File>
</Files>
<Globals>
</Globals>
</VisualStudioProject>
================================================
FILE: projects/codeblocks/SOIL.cbp
================================================
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<CodeBlocks_project_file>
<FileVersion major="1" minor="6" />
<Project>
<Option title="Simple OpenGL Image Library" />
<Option pch_mode="2" />
<Option compiler="gcc" />
<Build>
<Target title="lib-Release">
<Option output="..\..\lib\libSOIL" prefix_auto="1" extension_auto="1" />
<Option working_dir="" />
<Option object_output="obj\Release\" />
<Option type="2" />
<Option compiler="gcc" />
<Option createDefFile="1" />
<Compiler>
<Add option="-Os" />
<Add option="-O2" />
</Compiler>
<Linker>
<Add option="-s" />
</Linker>
</Target>
<Target title="test-Debug">
<Option output="..\..\testSOIL" prefix_auto="1" extension_auto="1" />
<Option working_dir="..\..\" />
<Option object_output="obj\" />
<Option type="1" />
<Option compiler="gcc" />
<Compiler>
<Add option="-O" />
<Add option="-pg" />
<Add option="-g" />
</Compiler>
<Linker>
<Add option="-pg -lgmon" />
<Add library="opengl32" />
<Add library="gdi32" />
</Linker>
</Target>
<Target title="test-Release">
<Option output="..\..\testSOIL" prefix_auto="1" extension_auto="1" />
<Option working_dir="..\..\" />
<Option object_output="obj\" />
<Option type="1" />
<Option compiler="gcc" />
<Compiler>
<Add option="-Os" />
<Add option="-O2" />
</Compiler>
<Linker>
<Add option="-s" />
<Add library="opengl32" />
<Add library="gdi32" />
</Linker>
</Target>
</Build>
<Compiler>
<Add option="-Wall" />
</Compiler>
<Unit filename="..\..\src\SOIL.c">
<Option compilerVar="CC" />
</Unit>
<Unit filename="..\..\src\SOIL.h" />
<Unit filename="..\..\src\image_DXT.c">
<Option compilerVar="CC" />
</Unit>
<Unit filename="..\..\src\image_DXT.h" />
<Unit filename="..\..\src\image_helper.c">
<Option compilerVar="CC" />
</Unit>
<Unit filename="..\..\src\image_helper.h" />
<Unit filename="..\..\src\stb_image_aug.c">
<Option compilerVar="CC" />
</Unit>
<Unit filename="..\..\src\stb_image_aug.h" />
<Unit filename="..\..\src\stbi_DDS_aug.h" />
<Unit filename="..\..\src\stbi_DDS_aug_c.h" />
<Unit filename="..\..\src\test_SOIL.cpp">
<Option target="test-Debug" />
<Option target="test-Release" />
</Unit>
<Extensions>
<code_completion />
<envvars />
<debugger />
</Extensions>
</Project>
</CodeBlocks_project_file>
================================================
FILE: soil.html
================================================
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<META HTTP-EQUIV="CONTENT-TYPE" CONTENT="text/html; charset=windows-1252">
<TITLE>lonesock.net: SOIL</TITLE>
<style type="text/css">
<!--
body { color: #000000; background-color: #FFFFFF; }
.style1 { color: #505050; }
.style2 { color: #A0A0A0; }
.style3 { color: #8080FF; font-weight: bold; }
.style15 { color: #8080FF; font-weight: bold; }
.style17 { color: #008080; }
.style18 { color: #800000; }
.style4 { color: #F000F0; }
.style5 { color: #0000A0; font-weight: bold; }
.style16 { color: #00A000; font-weight: bold; }
.style6 { color: #0000FF; }
.style12 { color: #0000FF; }
.style7 { color: #E0A000; }
.style8 { color: #000000; }
.style9 { color: #00A000; }
.style10 { color: #FF0000; }
.style34 { color: #000000; background-color: #80FFFF; font-weight: bold; }
.style35 { color: #FFFFFF; background-color: #FF0000; font-weight: bold; }
--></style>
</HEAD>
<BODY LANG="en-US" DIR="LTR">
<PRE STYLE="margin-bottom: 0.2in; text-align: center">
<FONT SIZE=4 STYLE="font-size: 16pt"><B>Simple OpenGL Image Library</B></FONT>
</PRE>
<P>
<B>Introduction:</B><BR><BR>SOIL is a tiny C library used primarily
for uploading textures into OpenGL. It is based on stb_image version
1.16, the public domain code from Sean Barrett (found <A HREF="http://www.nothings.org/stb_image.c">here</A>).
I have extended it to load TGA and DDS files, and to perform common
functions needed in loading OpenGL textures. SOIL can also be used
to save and load images in a variety of formats (useful for loading
height maps, non-OpenGL applications, etc.)<BR>
<BR>
<B>Download:</B>
<BR>
<BR>
You can grab the latest version of SOIL <A HREF="http://www.lonesock.net/files/soil.zip">here</A>.
(July 7, 2008: see the change log at the bottom of this page.)<BR>
You can also checkout the latest code from the new SVN repository, login as guest/guest:<BR>
<A HREF="svn://www.twisted-works.com/jdummer/public/SOIL">svn://www.twisted-works.com/jdummer/public/SOIL</A><BR>
(thanks for the SVN hosting, Sherief!)
<BR>
<BR>
<B>License:</B>
<BR>
<BR>
Public Domain
<BR>
<BR>
<B>Features:</B>
</P>
<UL>
<LI>Readable Image Formats:
<UL>
<LI>BMP - non-1bpp, non-RLE (from stb_image documentation)
<LI>PNG - non-interlaced (from stb_image documentation)
<LI>JPG - JPEG baseline (from stb_image documentation)
<LI>TGA - greyscale or RGB or RGBA or indexed, uncompressed or RLE
<LI>DDS - DXT1/2/3/4/5, uncompressed, cubemaps (can't read 3D DDS files yet)
<LI>PSD - (from stb_image documentation)
<LI>HDR - converted to LDR, unless loaded with *HDR* functions (RGBE or RGBdivA or RGBdivA2)
</UL>
<LI>Writeable Image Formats:
<UL>
<LI>TGA - Greyscale or RGB or RGBA, uncompressed
<LI>BMP - RGB, uncompressed
<LI>DDS - RGB as DXT1, or RGBA as DXT5
</UL>
<LI>Can load an image file directly into a 2D OpenGL texture, optionally performing the following functions:
<UL>
<LI>Can generate a new texture handle, or reuse one specified
<LI>Can automatically rescale the image to the next largest power-of-two size
<LI>Can automatically create MIPmaps
<LI>Can scale (not simply clamp) the RGB values into the "safe range" for NTSC displays (16 to 235, as recommended <a href="http://msdn2.microsoft.com/en-us/library/bb174608.aspx#NTSC_Suggestions">here</a>)
<LI>Can multiply alpha on load (for more correct blending / compositing)
<LI>Can flip the image vertically
<LI>Can compress and upload any image as DXT1 or DXT5 (if EXT_texture_compression_s3tc is available), using an internal (very fast!) compressor
<LI>Can convert the RGB to YCoCg color space (useful with DXT5 compression: see <a href="http://developer.nvidia.com/object/real-time-ycocg-dxt-compression.html">this link</a> from NVIDIA)
<LI>Will automatically downsize a texture if it is larger than GL_MAX_TEXTURE_SIZE
<LI>Can directly upload DDS files (DXT1/3/5/uncompressed/cubemap, with or without MIPmaps). Note: directly uploading the compressed DDS image will disable the other options (no flipping, no pre-multiplying alpha, no rescaling, no creation of MIPmaps, no auto-downsizing)
<LI>Can load rectangluar textures for GUI elements or splash screens (requires GL_ARB/EXT/NV_texture_rectangle)
</UL>
<LI>Can decompress images from RAM (e.g. via <a href="http://icculus.org/physfs/">PhysicsFS</a> or similar) into an OpenGL texture (same features as regular 2D textures, above)
<LI>Can load cube maps directly into an OpenGL texture (same features as regular 2D textures, above)
<UL>
<LI>Can take six image files directly into an OpenGL cube map texture
<LI>Can take a single image file where width = 6*height (or vice versa), split it into an OpenGL cube map texture
</UL>
<LI>No external dependencies
<LI>Tiny
<LI>Cross platform (Windows, *nix, Mac OS X)
<LI>Public Domain
</UL>
<PRE STYLE="margin-bottom: 0.2in"><B>ToDo:</B></PRE>
<UL>
<LI>More testing
<LI>add HDR functions to load from memory and load to RGBE unsigned char*
</UL>
<P><BR><B>Usage:</B><BR><BR>SOIL is meant to be used as a static
library (as it's tiny and in the public domain). You can use the static
library file included in the zip (libSOIL.a works for MinGW and Microsoft
compilers...feel free to rename it to SOIL.lib if that makes you happy),
or compile the library yourself. The code is cross-platform and has been
tested on Windows, Linux, and Mac. (The heaviest testing has been on the
Windows platform, so feel free to email me if you find any issues with
other platforms.)
<BR><BR>Simply include SOIL.h in your C or C++ file,
link in the static library, and then use any of SOIL's functions. The
file SOIL.h contains simple doxygen style documentation. (If you use the
static library, no other header files are needed besides SOIL.h) Below
are some simple usage examples:
</P>
<pre>
<code><span style="font: 8pt Courier New;"><span class="style1">/* load an image file directly as a new OpenGL texture */
</span><span class="style11">GLuint tex_2d </span><span class="style10">= </span><span class="style11">SOIL_load_OGL_texture
</span><span class="style10">(
</span><span class="style6">"img.png"</span><span class="style10">,
</span><span class="style11">SOIL_LOAD_AUTO</span><span class="style10">,
</span><span class="style11">SOIL_CREATE_NEW_ID</span><span class="style10">,
</span><span class="style11">SOIL_FLAG_MIPMAPS </span><span class="style10">| </span><span class="style11">SOIL_FLAG_INVERT_Y </span><span class="style10">| </span><span class="style11">SOIL_FLAG_NTSC_SAFE_RGB </span><span class="style10">| </span><span class="style11">SOIL_FLAG_COMPRESS_TO_DXT
</span><span class="style10">);
</span><span class="style1">/* check for an error during the load process */
</span><span class="style5">if</span><span class="style10">( </span><span class="style4">0 </span><span class="style10">== </span><span class="style11">tex_2d </span><span class="style10">)
{
</span><span class="style11">printf</span><span class="style10">( </span><span class="style6">"SOIL loading error: '%s'\n"</span><span class="style10">, </span><span class="style11">SOIL_last_result</span><span class="style10">() );
}
</span><span class="style1">/* load another image, but into the same texture ID, overwriting the last one */
</span><span class="style11">tex_2d </span><span class="style10">= </span><span class="style11">SOIL_load_OGL_texture
</span><span class="style10">(
</span><span class="style6">"some_other_img.dds"</span><span class="style10">,
</span><span class="style11">SOIL_LOAD_AUTO</span><span class="style10">,
</span><span class="style11">tex_2d</span><span class="style10">,
</span><span class="style11">SOIL_FLAG_DDS_LOAD_DIRECT
</span><span class="style10">);
</span><span class="style1">/* load 6 images into a new OpenGL cube map, forcing RGB */
</span><span class="style11">GLuint tex_cube </span><span class="style10">= </span><span class="style11">SOIL_load_OGL_cubemap
</span><span class="style10">(
</span><span class="style6">"xp.jpg"</span><span class="style10">,
</span><span class="style6">"xn.jpg"</span><span class="style10">,
</span><span class="style6">"yp.jpg"</span><span class="style10">,
</span><span class="style6">"yn.jpg"</span><span class="style10">,
</span><span class="style6">"zp.jpg"</span><span class="style10">,
</span><span class="style6">"zn.jpg"</span><span class="style10">,
</span><span class="style11">SOIL_LOAD_RGB</span><span class="style10">,
</span><span class="style11">SOIL_CREATE_NEW_ID</span><span class="style10">,
</span><span class="style11">SOIL_FLAG_MIPMAPS
</span><span class="style10">);
</span><span class="style1">/* load and split a single image into a new OpenGL cube map, default format */
</span><span class="style1">/* face order = East South West North Up Down => "ESWNUD", case sensitive! */
</span><span class="style11">GLuint single_tex_cube </span><span class="style10">= </span><span class="style11">SOIL_load_OGL_single_cubemap
</span><span class="style10">(
</span><span class="style6">"split_cubemap.png"</span><span class="style10">,
</span><span class="style6">"EWUDNS"</span><span class="style10">,
</span><span class="style11">SOIL_LOAD_AUTO</span><span class="style10">,
</span><span class="style11">SOIL_CREATE_NEW_ID</span><span class="style10">,
</span><span class="style11">SOIL_FLAG_MIPMAPS
</span><span class="style10">);
</span><span class="style1">/* actually, load a DDS cubemap over the last OpenGL cube map, default format */
</span><span class="style1">/* try to load it directly, but give the order of the faces in case that fails */
</span><span class="style1">/* the DDS cubemap face order is pre-defined as SOIL_DDS_CUBEMAP_FACE_ORDER */
</span><span class="style11">single_tex_cube </span><span class="style10">= </span><span class="style11">SOIL_load_OGL_single_cubemap
</span><span class="style10">(
</span><span class="style6">"overwrite_cubemap.dds"</span><span class="style10">,
</span><span class="style11">SOIL_DDS_CUBEMAP_FACE_ORDER</span><span class="style10">,
</span><span class="style11">SOIL_LOAD_AUTO</span><span class="style10">,
</span><span class="style11">single_tex_cube</span><span class="style10">,
</span><span class="style11">SOIL_FLAG_MIPMAPS | SOIL_FLAG_DDS_LOAD_DIRECT
</span><span class="style10">);
</span><span class="style1">/* load an image as a heightmap, forcing greyscale (so channels should be 1) */
</span><span class="style5">int </span><span class="style11">width</span><span class="style10">, </span><span class="style11">height</span><span class="style10">, </span><span class="style11">channels</span><span class="style10">;
</span><span class="style5">unsigned char </span><span class="style10">*</span><span class="style11">ht_map </span><span class="style10">= </span><span class="style11">SOIL_load_image
</span><span class="style10">(
</span><span class="style6">"terrain.tga"</span><span class="style10">,
&</span><span class="style11">width</span><span class="style10">, &</span><span class="style11">height</span><span class="style10">, &</span><span class="style11">channels</span><span class="style10">,
</span><span class="style11">SOIL_LOAD_L
</span><span class="style10">);
</span><span class="style1">/* save that image as another type */
</span><span class="style5">int </span><span class="style11">save_result </span><span class="style10">= </span><span class="style11">SOIL_save_image
</span><span class="style10">(
</span><span class="style6">"new_terrain.dds"</span><span class="style10">,
</span><span class="style11">SOIL_SAVE_TYPE_DDS</span><span class="style10">,
</span><span class="style11">width</span><span class="style10">, </span><span class="style11">height</span><span class="style10">, </span><span class="style11">channels</span><span class="style10">,
</span><span class="style11">ht_map
</span><span class="style10">);
</span><span class="style1">/* save a screenshot of your awesome OpenGL game engine, running at 1024x768 */
</span><span class="style11">save_result </span><span class="style10">= </span><span class="style11">SOIL_save_screenshot
</span><span class="style10">(
</span><span class="style6">"awesomenessity.bmp"</span><span class="style10">,
</span><span class="style11">SOIL_SAVE_TYPE_BMP</span><span class="style10">,
</span><span class="style4">0</span><span class="style10">, </span><span class="style4">0</span><span class="style10">, </span><span class="style4">1024</span><span class="style10">, </span><span class="style4">768
</span><span class="style10">);
</span><span class="style1">/* loaded a file via PhysicsFS, need to decompress the image from RAM, */
</span><span class="style1">/* where it's in a buffer: unsigned char *image_in_RAM */
</span><span class="style11">GLuint tex_2d_from_RAM </span><span class="style10">= </span><span class="style11">SOIL_load_OGL_texture_from_memory
</span><span class="style10">(
</span><span class="style11">image_in_RAM</span><span class="style10">,
</span><span class="style11">image_in_RAM_bytes</span><span class="style10">,
</span><span class="style11">SOIL_LOAD_AUTO</span><span class="style10">,
</span><span class="style11">SOIL_CREATE_NEW_ID</span><span class="style10">,
</span><span class="style11">SOIL_FLAG_MIPMAPS </span><span class="style10">| </span><span class="style11">SOIL_FLAG_INVERT_Y </span><span class="style10">| </span><span class="style11">SOIL_FLAG_COMPRESS_TO_DXT
</span><span class="style10">);
</span><span class="style1">/* done with the heightmap, free up the RAM */
</span><span class="style11">SOIL_free_image_data</span><span class="style10">( </span><span class="style11">ht_map </span><span class="style10">);</span></span>
</code></pre>
<BR>
<BR>
<B>Change Log:</B>
<UL>
<LI>July 7, 2008
<UL>
<LI>upgraded to stb_image 1.16 (threadsafe! loads PSD and HDR formats)
<LI>removed <B>inline</B> keyword from native SOIL functions (thanks Sherief, Boder, Amnesiac5!)
<LI>added SOIL_load_OGL_HDR_texture (loads a Radience HDR file into RGBE, RGB/a, RGB/A^2)
<LI>fixed a potential bug loading DDS files with a filename
<LI>added a VC9 project file (thanks Sherief!)
</UL>
<LI>November 10, 2007: added SOIL_FLAG_TEXTURE_RECTANGLE (pixel addressed non POT, useful for GUI, splash screens, etc.). Not useful with cubemaps, and disables repeating and MIPmaps.
<LI>November 8, 2007
<UL>
<LI>upgraded to stb_image 1.07
<LI>fixed some includes and defines for compiling on OS X (thanks Mogui and swiftcoder!)
</UL>
<LI>October 30, 2007
<UL>
<LI>upgraded to stb_image 1.04, some tiny bug fixes
<LI>there is now a makefile (under projects) for ease of building under Linux (thanks D J Peters!)
<LI>Visual Studio 6/2003/2005 projects are working again
<LI>patched SOIL for better pointer handling of the glCompressedTexImage2D extension (thanks Peter Sperl!)
<LI>fixed DDS loading when force_channels=4 but there was no alpha; it was returning 3 channels. (Thanks LaurentGom!)
<LI>fixed a bunch of channel issues in general. (Thanks Sean Barrett!)
</UL>
<LI>October 27, 2007
<UL>
<LI>correctly reports when there is no OpenGL context (thanks Merick Zero!)
<LI>upgraded to stb_image 1.03 with support for loading the HDR image format
<LI>fixed loading JPEG images while forcing the number of channels (e.g. to RGBA)
<LI>changed SOIL_DDS_CUBEMAP_FACE_ORDER to a #define (thanks Dancho!)
<LI>reorganized my additions to stb_image (you can define STBI_NO_DDS to compile SOIL without DDS support)
<LI>added SOIL_FLAG_CoCg_Y, will convert RGB or RGBA to YCoCg color space (<a href="http://developer.nvidia.com/object/real-time-ycocg-dxt-compression.html">link</a>)
</UL>
<LI>October 5, 2007
<UL>
<LI>added SOIL_FLAG_NTSC_SAFE_RGB
<LI>bugfixed & optimized up_scale_image (used with SOIL_FLAG_POWER_OF_TWO and SOIL_FLAG_MIPMAPS)
</UL>
<LI>September 20, 2007
<UL>
<LI>upgraded to stb_image 1.0
<LI>added the DXT source files to the MSVS projects
<LI>removed sqrtf() calls (VS2k3 could not handle them)
<LI>distributing only 1 library file (libSOIL.a, compiled with MinGW 4.2.1 tech preview!) for all windows compilers
<LI>added an example of the *_from_memory() functions to the Usage section
</UL>
<LI>September 6, 2007
<UL>
<LI>added a slew of SOIL_load_*_from_memory() functions for people using PhysicsFS or similar
<LI>more robust loading of non-compliant DDS files (thanks Dan!)
</UL>
<LI>September 1, 2007 - fixed bugs from the last update [8^)
<LI>August 31, 2007
<UL>
<LI>can load uncompressed and cubemap DDS files
<LI>can create a cubemap texture from a single (stitched) image file of any type
<LI>sped up the image resizing code
</UL>
<LI>August 24, 2007 - updated the documentation examples (at the bottom of this page)
<LI>August 22, 2007
<UL>
<LI>can load cube maps (needs serious testing)
<LI>can compress 1- or 2-channel images to DXT1/5
<LI>fixed some malloc() casts
<LI>fixed C++ style comments
<LI>fixed includes to compile under *nix or Mac (hopefully, needs testing...any volunteers?)
</UL>
<LI>August 16, 2007
<UL>
<LI>Will now downsize the image if necessary to fit GL_MAX_TEXTURE_SIZE
<LI>added SOIL_create_OGL_texture() to upload raw image data that isn't from an image file
</UL>
<LI>August 14, 2007 (PM) - Can now load indexed TGA
<LI>August 14, 2007 (AM)
<UL>
<LI>Updated to stb_image 0.97
<LI>added result messages
<LI>can now decompress DDS files (DXT1/2/3/4/5)
</UL>
<LI>August 11, 2007 - MIPmaps can now handle non-square textures
<LI>August 7, 2007
<UL>
<LI>Can directly upload DXT1/3/5 DDS files (with or w/o MIPmaps)
<LI>can compress any image to DXT1/5 (using a new & fast & simple compression scheme) and upload
<LI>can save as DDS
</UL>
<LI>July 31, 2007 - added compressing to DXT and flipping about Y
<LI>July 30, 2007 - initial release
</UL>
<BR>
<BR>
<PRE STYLE="text-align: center">back to
<A HREF="http://www.lonesock.net/">www.lonesock.net</A></PRE>
</BODY>
</HTML>
================================================
FILE: src/SOIL.c
================================================
/*
Jonathan Dummer
2007-07-26-10.36
Simple OpenGL Image Library
Public Domain
using Sean Barret's stb_image as a base
Thanks to:
* Sean Barret - for the awesome stb_image
* Dan Venkitachalam - for finding some non-compliant DDS files, and patching some explicit casts
* everybody at gamedev.net
*/
#define SOIL_CHECK_FOR_GL_ERRORS 0
#ifdef _WIN64
#define WIN64_LEAN_AND_MEAN
#include <windows.h>
#include <wingdi.h>
#include <GL/gl.h>
#elif defined _WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <wingdi.h>
#include <GL/gl.h>
#elif defined(__APPLE__) || defined(__APPLE_CC__)
/* I can't test this Apple stuff! */
#include <OpenGL/gl.h>
#include <Carbon/Carbon.h>
#define APIENTRY
#elif defined(__ANDROID__)
#include <GLES/gl.h>
#define APIENTRY
#elif defined(__EMSCRIPTEN__)
#include <GL/gl.h>
#else
#include <GL/gl.h>
#include <GL/glx.h>
#endif
#include "SOIL.h"
#include "stb_image_aug.h"
#include "image_helper.h"
#include "image_DXT.h"
#include <stdlib.h>
#include <string.h>
/* error reporting */
char *result_string_pointer = "SOIL initialized";
/* for loading cube maps */
enum{
SOIL_CAPABILITY_UNKNOWN = -1,
SOIL_CAPABILITY_NONE = 0,
SOIL_CAPABILITY_PRESENT = 1
};
static int has_cubemap_capability = SOIL_CAPABILITY_UNKNOWN;
int query_cubemap_capability( void );
#define SOIL_TEXTURE_WRAP_R 0x8072
#define SOIL_CLAMP_TO_EDGE 0x812F
#define SOIL_NORMAL_MAP 0x8511
#define SOIL_REFLECTION_MAP 0x8512
#define SOIL_TEXTURE_CUBE_MAP 0x8513
#define SOIL_TEXTURE_BINDING_CUBE_MAP 0x8514
#define SOIL_TEXTURE_CUBE_MAP_POSITIVE_X 0x8515
#define SOIL_TEXTURE_CUBE_MAP_NEGATIVE_X 0x8516
#define SOIL_TEXTURE_CUBE_MAP_POSITIVE_Y 0x8517
#define SOIL_TEXTURE_CUBE_MAP_NEGATIVE_Y 0x8518
#define SOIL_TEXTURE_CUBE_MAP_POSITIVE_Z 0x8519
#define SOIL_TEXTURE_CUBE_MAP_NEGATIVE_Z 0x851A
#define SOIL_PROXY_TEXTURE_CUBE_MAP 0x851B
#define SOIL_MAX_CUBE_MAP_TEXTURE_SIZE 0x851C
/* for non-power-of-two texture */
static int has_NPOT_capability = SOIL_CAPABILITY_UNKNOWN;
int query_NPOT_capability( void );
/* for texture rectangles */
static int has_tex_rectangle_capability = SOIL_CAPABILITY_UNKNOWN;
int query_tex_rectangle_capability( void );
#define SOIL_TEXTURE_RECTANGLE_ARB 0x84F5
#define SOIL_MAX_RECTANGLE_TEXTURE_SIZE_ARB 0x84F8
/* for using DXT compression */
static int has_DXT_capability = SOIL_CAPABILITY_UNKNOWN;
int query_DXT_capability( void );
#define SOIL_RGB_S3TC_DXT1 0x83F0
#define SOIL_RGBA_S3TC_DXT1 0x83F1
#define SOIL_RGBA_S3TC_DXT3 0x83F2
#define SOIL_RGBA_S3TC_DXT5 0x83F3
typedef void (APIENTRY * P_SOIL_GLCOMPRESSEDTEXIMAGE2DPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const GLvoid * data);
P_SOIL_GLCOMPRESSEDTEXIMAGE2DPROC soilGlCompressedTexImage2D = NULL;
unsigned int SOIL_direct_load_DDS(
const char *filename,
unsigned int reuse_texture_ID,
int flags,
int loading_as_cubemap );
unsigned int SOIL_direct_load_DDS_from_memory(
const unsigned char *const buffer,
int buffer_length,
unsigned int reuse_texture_ID,
int flags,
int loading_as_cubemap );
/* other functions */
unsigned int
SOIL_internal_create_OGL_texture
(
const unsigned char *const data,
int width, int height, int channels,
unsigned int reuse_texture_ID,
unsigned int flags,
unsigned int opengl_texture_type,
unsigned int opengl_texture_target,
unsigned int texture_check_size_enum
);
/* and the code magic begins here [8^) */
unsigned int
SOIL_load_OGL_texture
(
const char *filename,
int force_channels,
unsigned int reuse_texture_ID,
unsigned int flags
)
{
/* variables */
unsigned char* img;
int width, height, channels;
unsigned int tex_id;
/* does the user want direct uploading of the image as a DDS file? */
if( flags & SOIL_FLAG_DDS_LOAD_DIRECT )
{
/* 1st try direct loading of the image as a DDS file
note: direct uploading will only load what is in the
DDS file, no MIPmaps will be generated, the image will
not be flipped, etc. */
tex_id = SOIL_direct_load_DDS( filename, reuse_texture_ID, flags, 0 );
if( tex_id )
{
/* hey, it worked!! */
return tex_id;
}
}
/* try to load the image */
img = SOIL_load_image( filename, &width, &height, &channels, force_channels );
/* channels holds the original number of channels, which may have been forced */
if( (force_channels >= 1) && (force_channels <= 4) )
{
channels = force_channels;
}
if( NULL == img )
{
/* image loading failed */
result_string_pointer = stbi_failure_reason();
return 0;
}
/* OK, make it a texture! */
tex_id = SOIL_internal_create_OGL_texture(
img, width, height, channels,
reuse_texture_ID, flags,
GL_TEXTURE_2D, GL_TEXTURE_2D,
GL_MAX_TEXTURE_SIZE );
/* and nuke the image data */
SOIL_free_image_data( img );
/* and return the handle, such as it is */
return tex_id;
}
unsigned int
SOIL_load_OGL_HDR_texture
(
const char *filename,
int fake_HDR_format,
int rescale_to_max,
unsigned int reuse_texture_ID,
unsigned int flags
)
{
/* variables */
unsigned char* img;
int width, height, channels;
unsigned int tex_id;
/* no direct uploading of the image as a DDS file */
/* error check */
if( (fake_HDR_format != SOIL_HDR_RGBE) &&
(fake_HDR_format != SOIL_HDR_RGBdivA) &&
(fake_HDR_format != SOIL_HDR_RGBdivA2) )
{
result_string_pointer = "Invalid fake HDR format specified";
return 0;
}
/* try to load the image (only the HDR type) */
img = stbi_hdr_load_rgbe( filename, &width, &height, &channels, 4 );
/* channels holds the original number of channels, which may have been forced */
if( NULL == img )
{
/* image loading failed */
result_string_pointer = stbi_failure_reason();
return 0;
}
/* the load worked, do I need to convert it? */
if( fake_HDR_format == SOIL_HDR_RGBdivA )
{
RGBE_to_RGBdivA( img, width, height, rescale_to_max );
} else if( fake_HDR_format == SOIL_HDR_RGBdivA2 )
{
RGBE_to_RGBdivA2( img, width, height, rescale_to_max );
}
/* OK, make it a texture! */
tex_id = SOIL_internal_create_OGL_texture(
img, width, height, channels,
reuse_texture_ID, flags,
GL_TEXTURE_2D, GL_TEXTURE_2D,
GL_MAX_TEXTURE_SIZE );
/* and nuke the image data */
SOIL_free_image_data( img );
/* and return the handle, such as it is */
return tex_id;
}
unsigned int
SOIL_load_OGL_texture_from_memory
(
const unsigned char *const buffer,
int buffer_length,
int force_channels,
unsigned int reuse_texture_ID,
unsigned int flags
)
{
/* variables */
unsigned char* img;
int width, height, channels;
unsigned int tex_id;
/* does the user want direct uploading of the image as a DDS file? */
if( flags & SOIL_FLAG_DDS_LOAD_DIRECT )
{
/* 1st try direct loading of the image as a DDS file
note: direct uploading will only load what is in the
DDS file, no MIPmaps will be generated, the image will
not be flipped, etc. */
tex_id = SOIL_direct_load_DDS_from_memory(
buffer, buffer_length,
reuse_texture_ID, flags, 0 );
if( tex_id )
{
/* hey, it worked!! */
return tex_id;
}
}
/* try to load the image */
img = SOIL_load_image_from_memory(
buffer, buffer_length,
&width, &height, &channels,
force_channels );
/* channels holds the original number of channels, which may have been forced */
if( (force_channels >= 1) && (force_channels <= 4) )
{
channels = force_channels;
}
if( NULL == img )
{
/* image loading failed */
result_string_pointer = stbi_failure_reason();
return 0;
}
/* OK, make it a texture! */
tex_id = SOIL_internal_create_OGL_texture(
img, width, height, channels,
reuse_texture_ID, flags,
GL_TEXTURE_2D, GL_TEXTURE_2D,
GL_MAX_TEXTURE_SIZE );
/* and nuke the image data */
SOIL_free_image_data( img );
/* and return the handle, such as it is */
return tex_id;
}
unsigned int
SOIL_load_OGL_cubemap
(
const char *x_pos_file,
const char *x_neg_file,
const char *y_pos_file,
const char *y_neg_file,
const char *z_pos_file,
const char *z_neg_file,
int force_channels,
unsigned int reuse_texture_ID,
unsigned int flags
)
{
/* variables */
unsigned char* img;
int width, height, channels;
unsigned int tex_id;
/* error checking */
if( (x_pos_file == NULL) ||
(x_neg_file == NULL) ||
(y_pos_file == NULL) ||
(y_neg_file == NULL) ||
(z_pos_file == NULL) ||
(z_neg_file == NULL) )
{
result_string_pointer = "Invalid cube map files list";
return 0;
}
/* capability checking */
if( query_cubemap_capability() != SOIL_CAPABILITY_PRESENT )
{
result_string_pointer = "No cube map capability present";
return 0;
}
/* 1st face: try to load the image */
img = SOIL_load_image( x_pos_file, &width, &height, &channels, force_channels );
/* channels holds the original number of channels, which may have been forced */
if( (force_channels >= 1) && (force_channels <= 4) )
{
channels = force_channels;
}
if( NULL == img )
{
/* image loading failed */
result_string_pointer = stbi_failure_reason();
return 0;
}
/* upload the texture, and create a texture ID if necessary */
tex_id = SOIL_internal_create_OGL_texture(
img, width, height, channels,
reuse_texture_ID, flags,
SOIL_TEXTURE_CUBE_MAP, SOIL_TEXTURE_CUBE_MAP_POSITIVE_X,
SOIL_MAX_CUBE_MAP_TEXTURE_SIZE );
/* and nuke the image data */
SOIL_free_image_data( img );
/* continue? */
if( tex_id != 0 )
{
/* 1st face: try to load the image */
img = SOIL_load_image( x_neg_file, &width, &height, &channels, force_channels );
/* channels holds the original number of channels, which may have been forced */
if( (force_channels >= 1) && (force_channels <= 4) )
{
channels = force_channels;
}
if( NULL == img )
{
/* image loading failed */
result_string_pointer = stbi_failure_reason();
return 0;
}
/* upload the texture, but reuse the assigned texture ID */
tex_id = SOIL_internal_create_OGL_texture(
img, width, height, channels,
tex_id, flags,
SOIL_TEXTURE_CUBE_MAP, SOIL_TEXTURE_CUBE_MAP_NEGATIVE_X,
SOIL_MAX_CUBE_MAP_TEXTURE_SIZE );
/* and nuke the image data */
SOIL_free_image_data( img );
}
/* continue? */
if( tex_id != 0 )
{
/* 1st face: try to load the image */
img = SOIL_load_image( y_pos_file, &width, &height, &channels, force_channels );
/* channels holds the original number of channels, which may have been forced */
if( (force_channels >= 1) && (force_channels <= 4) )
{
channels = force_channels;
}
if( NULL == img )
{
/* image loading failed */
result_string_pointer = stbi_failure_reason();
return 0;
}
/* upload the texture, but reuse the assigned texture ID */
tex_id = SOIL_internal_create_OGL_texture(
img, width, height, channels,
tex_id, flags,
SOIL_TEXTURE_CUBE_MAP, SOIL_TEXTURE_CUBE_MAP_POSITIVE_Y,
SOIL_MAX_CUBE_MAP_TEXTURE_SIZE );
/* and nuke the image data */
SOIL_free_image_data( img );
}
/* continue? */
if( tex_id != 0 )
{
/* 1st face: try to load the image */
img = SOIL_load_image( y_neg_file, &width, &height, &channels, force_channels );
/* channels holds the original number of channels, which may have been forced */
if( (force_channels >= 1) && (force_channels <= 4) )
{
channels = force_channels;
}
if( NULL == img )
{
/* image loading failed */
result_string_pointer = stbi_failure_reason();
return 0;
}
/* upload the texture, but reuse the assigned texture ID */
tex_id = SOIL_internal_create_OGL_texture(
img, width, height, channels,
tex_id, flags,
SOIL_TEXTURE_CUBE_MAP, SOIL_TEXTURE_CUBE_MAP_NEGATIVE_Y,
SOIL_MAX_CUBE_MAP_TEXTURE_SIZE );
/* and nuke the image data */
SOIL_free_image_data( img );
}
/* continue? */
if( tex_id != 0 )
{
/* 1st face: try to load the image */
img = SOIL_load_image( z_pos_file, &width, &height, &channels, force_channels );
/* channels holds the original number of channels, which may have been forced */
if( (force_channels >= 1) && (force_channels <= 4) )
{
channels = force_channels;
}
if( NULL == img )
{
/* image loading failed */
result_string_pointer = stbi_failure_reason();
return 0;
}
/* upload the texture, but reuse the assigned texture ID */
tex_id = SOIL_internal_create_OGL_texture(
img, width, height, channels,
tex_id, flags,
SOIL_TEXTURE_CUBE_MAP, SOIL_TEXTURE_CUBE_MAP_POSITIVE_Z,
SOIL_MAX_CUBE_MAP_TEXTURE_SIZE );
/* and nuke the image data */
SOIL_free_image_data( img );
}
/* continue? */
if( tex_id != 0 )
{
/* 1st face: try to load the image */
img = SOIL_load_image( z_neg_file, &width, &height, &channels, force_channels );
/* channels holds the original number of channels, which may have been forced */
if( (force_channels >= 1) && (force_channels <= 4) )
{
channels = force_channels;
}
if( NULL == img )
{
/* image loading failed */
result_string_pointer = stbi_failure_reason();
return 0;
}
/* upload the texture, but reuse the assigned texture ID */
tex_id = SOIL_internal_create_OGL_texture(
img, width, height, channels,
tex_id, flags,
SOIL_TEXTURE_CUBE_MAP, SOIL_TEXTURE_CUBE_MAP_NEGATIVE_Z,
SOIL_MAX_CUBE_MAP_TEXTURE_SIZE );
/* and nuke the image data */
SOIL_free_image_data( img );
}
/* and return the handle, such as it is */
return tex_id;
}
unsigned int
SOIL_load_OGL_cubemap_from_memory
(
const unsigned char *const x_pos_buffer,
int x_pos_buffer_length,
const unsigned char *const x_neg_buffer,
int x_neg_buffer_length,
const unsigned char *const y_pos_buffer,
int y_pos_buffer_length,
const unsigned char *const y_neg_buffer,
int y_neg_buffer_length,
const unsigned char *const z_pos_buffer,
int z_pos_buffer_length,
const unsigned char *const z_neg_buffer,
int z_neg_buffer_length,
int force_channels,
unsigned int reuse_texture_ID,
unsigned int flags
)
{
/* variables */
unsigned char* img;
int width, height, channels;
unsigned int tex_id;
/* error checking */
if( (x_pos_buffer == NULL) ||
(x_neg_buffer == NULL) ||
(y_pos_buffer == NULL) ||
(y_neg_buffer == NULL) ||
(z_pos_buffer == NULL) ||
(z_neg_buffer == NULL) )
{
result_string_pointer = "Invalid cube map buffers list";
return 0;
}
/* capability checking */
if( query_cubemap_capability() != SOIL_CAPABILITY_PRESENT )
{
result_string_pointer = "No cube map capability present";
return 0;
}
/* 1st face: try to load the image */
img = SOIL_load_image_from_memory(
x_pos_buffer, x_pos_buffer_length,
&width, &height, &channels, force_channels );
/* channels holds the original number of channels, which may have been forced */
if( (force_channels >= 1) && (force_channels <= 4) )
{
channels = force_channels;
}
if( NULL == img )
{
/* image loading failed */
result_string_pointer = stbi_failure_reason();
return 0;
}
/* upload the texture, and create a texture ID if necessary */
tex_id = SOIL_internal_create_OGL_texture(
img, width, height, channels,
reuse_texture_ID, flags,
SOIL_TEXTURE_CUBE_MAP, SOIL_TEXTURE_CUBE_MAP_POSITIVE_X,
SOIL_MAX_CUBE_MAP_TEXTURE_SIZE );
/* and nuke the image data */
SOIL_free_image_data( img );
/* continue? */
if( tex_id != 0 )
{
/* 1st face: try to load the image */
img = SOIL_load_image_from_memory(
x_neg_buffer, x_neg_buffer_length,
&width, &height, &channels, force_channels );
/* channels holds the original number of channels, which may have been forced */
if( (force_channels >= 1) && (force_channels <= 4) )
{
channels = force_channels;
}
if( NULL == img )
{
/* image loading failed */
result_string_pointer = stbi_failure_reason();
return 0;
}
/* upload the texture, but reuse the assigned texture ID */
tex_id = SOIL_internal_create_OGL_texture(
img, width, height, channels,
tex_id, flags,
SOIL_TEXTURE_CUBE_MAP, SOIL_TEXTURE_CUBE_MAP_NEGATIVE_X,
SOIL_MAX_CUBE_MAP_TEXTURE_SIZE );
/* and nuke the image data */
SOIL_free_image_data( img );
}
/* continue? */
if( tex_id != 0 )
{
/* 1st face: try to load the image */
img = SOIL_load_image_from_memory(
y_pos_buffer, y_pos_buffer_length,
&width, &height, &channels, force_channels );
/* channels holds the original number of channels, which may have been forced */
if( (force_channels >= 1) && (force_channels <= 4) )
{
channels = force_channels;
}
if( NULL == img )
{
/* image loading failed */
result_string_pointer = stbi_failure_reason();
return 0;
}
/* upload the texture, but reuse the assigned texture ID */
tex_id = SOIL_internal_create_OGL_texture(
img, width, height, channels,
tex_id, flags,
SOIL_TEXTURE_CUBE_MAP, SOIL_TEXTURE_CUBE_MAP_POSITIVE_Y,
SOIL_MAX_CUBE_MAP_TEXTURE_SIZE );
/* and nuke the image data */
SOIL_free_image_data( img );
}
/* continue? */
if( tex_id != 0 )
{
/* 1st face: try to load the image */
img = SOIL_load_image_from_memory(
y_neg_buffer, y_neg_buffer_length,
&width, &height, &channels, force_channels );
/* channels holds the original number of channels, which may have been forced */
if( (force_channels >= 1) && (force_channels <= 4) )
{
channels = force_channels;
}
if( NULL == img )
{
/* image loading failed */
result_string_pointer = stbi_failure_reason();
return 0;
}
/* upload the texture, but reuse the assigned texture ID */
tex_id = SOIL_internal_create_OGL_texture(
img, width, height, channels,
tex_id, flags,
SOIL_TEXTURE_CUBE_MAP, SOIL_TEXTURE_CUBE_MAP_NEGATIVE_Y,
SOIL_MAX_CUBE_MAP_TEXTURE_SIZE );
/* and nuke the image data */
SOIL_free_image_data( img );
}
/* continue? */
if( tex_id != 0 )
{
/* 1st face: try to load the image */
img = SOIL_load_image_from_memory(
z_pos_buffer, z_pos_buffer_length,
&width, &height, &channels, force_channels );
/* channels holds the original number of channels, which may have been forced */
if( (force_channels >= 1) && (force_channels <= 4) )
{
channels = force_channels;
}
if( NULL == img )
{
/* image loading failed */
result_string_pointer = stbi_failure_reason();
return 0;
}
/* upload the texture, but reuse the assigned texture ID */
tex_id = SOIL_internal_create_OGL_texture(
img, width, height, channels,
tex_id, flags,
SOIL_TEXTURE_CUBE_MAP, SOIL_TEXTURE_CUBE_MAP_POSITIVE_Z,
SOIL_MAX_CUBE_MAP_TEXTURE_SIZE );
/* and nuke the image data */
SOIL_free_image_data( img );
}
/* continue? */
if( tex_id != 0 )
{
/* 1st face: try to load the image */
img = SOIL_load_image_from_memory(
z_neg_buffer, z_neg_buffer_length,
&width, &height, &channels, force_channels );
/* channels holds the original number of channels, which may have been forced */
if( (force_channels >= 1) && (force_channels <= 4) )
{
channels = force_channels;
}
if( NULL == img )
{
/* image loading failed */
result_string_pointer = stbi_failure_reason();
return 0;
}
/* upload the texture, but reuse the assigned texture ID */
tex_id = SOIL_internal_create_OGL_texture(
img, width, height, channels,
tex_id, flags,
SOIL_TEXTURE_CUBE_MAP, SOIL_TEXTURE_CUBE_MAP_NEGATIVE_Z,
SOIL_MAX_CUBE_MAP_TEXTURE_SIZE );
/* and nuke the image data */
SOIL_free_image_data( img );
}
/* and return the handle, such as it is */
return tex_id;
}
unsigned int
SOIL_load_OGL_single_cubemap
(
const char *filename,
const char face_order[6],
int force_channels,
unsigned int reuse_texture_ID,
unsigned int flags
)
{
/* variables */
unsigned char* img;
int width, height, channels, i;
unsigned int tex_id = 0;
/* error checking */
if( filename == NULL )
{
result_string_pointer = "Invalid single cube map file name";
return 0;
}
/* does the user want direct uploading of the image as a DDS file? */
if( flags & SOIL_FLAG_DDS_LOAD_DIRECT )
{
/* 1st try direct loading of the image as a DDS file
note: direct uploading will only load what is in the
DDS file, no MIPmaps will be generated, the image will
not be flipped, etc. */
tex_id = SOIL_direct_load_DDS( filename, reuse_texture_ID, flags, 1 );
if( tex_id )
{
/* hey, it worked!! */
return tex_id;
}
}
/* face order checking */
for( i = 0; i < 6; ++i )
{
if( (face_order[i] != 'N') &&
(face_order[i] != 'S') &&
(face_order[i] != 'W') &&
(face_order[i] != 'E') &&
(face_order[i] != 'U') &&
(face_order[i] != 'D') )
{
result_string_pointer = "Invalid single cube map face order";
return 0;
};
}
/* capability checking */
if( query_cubemap_capability() != SOIL_CAPABILITY_PRESENT )
{
result_string_pointer = "No cube map capability present";
return 0;
}
/* 1st off, try to load the full image */
img = SOIL_load_image( filename, &width, &height, &channels, force_channels );
/* channels holds the original number of channels, which may have been forced */
if( (force_channels >= 1) && (force_channels <= 4) )
{
channels = force_channels;
}
if( NULL == img )
{
/* image loading failed */
result_string_pointer = stbi_failure_reason();
return 0;
}
/* now, does this image have the right dimensions? */
if( (width != 6*height) &&
(6*width != height) )
{
SOIL_free_image_data( img );
result_string_pointer = "Single cubemap image must have a 6:1 ratio";
return 0;
}
/* try the image split and create */
tex_id = SOIL_create_OGL_single_cubemap(
img, width, height, channels,
face_order, reuse_texture_ID, flags
);
/* nuke the temporary image data and return the texture handle */
SOIL_free_image_data( img );
return tex_id;
}
unsigned int
SOIL_load_OGL_single_cubemap_from_memory
(
const unsigned char *const buffer,
int buffer_length,
const char face_order[6],
int force_channels,
unsigned int reuse_texture_ID,
unsigned int flags
)
{
/* variables */
unsigned char* img;
int width, height, channels, i;
unsigned int tex_id = 0;
/* error checking */
if( buffer == NULL )
{
result_string_pointer = "Invalid single cube map buffer";
return 0;
}
/* does the user want direct uploading of the image as a DDS file? */
if( flags & SOIL_FLAG_DDS_LOAD_DIRECT )
{
/* 1st try direct loading of the image as a DDS file
note: direct uploading will only load what is in the
DDS file, no MIPmaps will be generated, the image will
not be flipped, etc. */
tex_id = SOIL_direct_load_DDS_from_memory(
buffer, buffer_length,
reuse_texture_ID, flags, 1 );
if( tex_id )
{
/* hey, it worked!! */
return tex_id;
}
}
/* face order checking */
for( i = 0; i < 6; ++i )
{
if( (face_order[i] != 'N') &&
(face_order[i] != 'S') &&
(face_order[i] != 'W') &&
(face_order[i] != 'E') &&
(face_order[i] != 'U') &&
(face_order[i] != 'D') )
{
result_string_pointer = "Invalid single cube map face order";
return 0;
};
}
/* capability checking */
if( query_cubemap_capability() != SOIL_CAPABILITY_PRESENT )
{
result_string_pointer = "No cube map capability present";
return 0;
}
/* 1st off, try to load the full image */
img = SOIL_load_image_from_memory(
buffer, buffer_length,
&width, &height, &channels,
force_channels );
/* channels holds the original number of channels, which may have been forced */
if( (force_channels >= 1) && (force_channels <= 4) )
{
channels = force_channels;
}
if( NULL == img )
{
/* image loading failed */
result_string_pointer = stbi_failure_reason();
return 0;
}
/* now, does this image have the right dimensions? */
if( (width != 6*height) &&
(6*width != height) )
{
SOIL_free_image_data( img );
result_string_pointer = "Single cubemap image must have a 6:1 ratio";
return 0;
}
/* try the image split and create */
tex_id = SOIL_create_OGL_single_cubemap(
img, width, height, channels,
face_order, reuse_texture_ID, flags
);
/* nuke the temporary image data and return the texture handle */
SOIL_free_image_data( img );
return tex_id;
}
unsigned int
SOIL_create_OGL_single_cubemap
(
const unsigned char *const data,
int width, int height, int channels,
const char face_order[6],
unsigned int reuse_texture_ID,
unsigned int flags
)
{
/* variables */
unsigned char* sub_img;
int dw, dh, sz, i;
unsigned int tex_id;
/* error checking */
if( data == NULL )
{
result_string_pointer = "Invalid single cube map image data";
return 0;
}
/* face order checking */
for( i = 0; i < 6; ++i )
{
if( (face_order[i] != 'N') &&
(face_order[i] != 'S') &&
(face_order[i] != 'W') &&
(face_order[i] != 'E') &&
(face_order[i] != 'U') &&
(face_order[i] != 'D') )
{
result_string_pointer = "Invalid single cube map face order";
return 0;
};
}
/* capability checking */
if( query_cubemap_capability() != SOIL_CAPABILITY_PRESENT )
{
result_string_pointer = "No cube map capability present";
return 0;
}
/* now, does this image have the right dimensions? */
if( (width != 6*height) &&
(6*width != height) )
{
result_string_pointer = "Single cubemap image must have a 6:1 ratio";
return 0;
}
/* which way am I stepping? */
if( width > height )
{
dw = height;
dh = 0;
} else
{
dw = 0;
dh = width;
}
sz = dw+dh;
sub_img = (unsigned char *)malloc( sz*sz*channels );
/* do the splitting and uploading */
tex_id = reuse_texture_ID;
for( i = 0; i < 6; ++i )
{
int x, y, idx = 0;
unsigned int cubemap_target = 0;
/* copy in the sub-image */
for( y = i*dh; y < i*dh+sz; ++y )
{
for( x = i*dw*channels; x < (i*dw+sz)*channels; ++x )
{
sub_img[idx++] = data[y*width*channels+x];
}
}
/* what is my texture target?
remember, this coordinate system is
LHS if viewed from inside the cube! */
switch( face_order[i] )
{
case 'N':
cubemap_target = SOIL_TEXTURE_CUBE_MAP_POSITIVE_Z;
break;
case 'S':
cubemap_target = SOIL_TEXTURE_CUBE_MAP_NEGATIVE_Z;
break;
case 'W':
cubemap_target = SOIL_TEXTURE_CUBE_MAP_NEGATIVE_X;
break;
case 'E':
cubemap_target = SOIL_TEXTURE_CUBE_MAP_POSITIVE_X;
break;
case 'U':
cubemap_target = SOIL_TEXTURE_CUBE_MAP_POSITIVE_Y;
break;
case 'D':
cubemap_target = SOIL_TEXTURE_CUBE_MAP_NEGATIVE_Y;
break;
}
/* upload it as a texture */
tex_id = SOIL_internal_create_OGL_texture(
sub_img, sz, sz, channels,
tex_id, flags,
SOIL_TEXTURE_CUBE_MAP,
cubemap_target,
SOIL_MAX_CUBE_MAP_TEXTURE_SIZE );
}
/* and nuke the image and sub-image data */
SOIL_free_image_data( sub_img );
/* and return the handle, such as it is */
return tex_id;
}
unsigned int
SOIL_create_OGL_texture
(
const unsigned char *const data,
int width, int height, int channels,
unsigned int reuse_texture_ID,
unsigned int flags
)
{
/* wrapper function for 2D textures */
return SOIL_internal_create_OGL_texture(
data, width, height, channels,
reuse_texture_ID, flags,
GL_TEXTURE_2D, GL_TEXTURE_2D,
GL_MAX_TEXTURE_SIZE );
}
#if SOIL_CHECK_FOR_GL_ERRORS
void check_for_GL_errors( const char *calling_location )
{
/* check for errors */
GLenum err_code = glGetError();
while( GL_NO_ERROR != err_code )
{
printf( "OpenGL Error @ %s: %i", calling_location, err_code );
err_code = glGetError();
}
}
#else
void check_for_GL_errors( const char *calling_location )
{
/* no check for errors */
}
#endif
unsigned int
SOIL_internal_create_OGL_texture
(
const unsigned char *const data,
int width, int height, int channels,
unsigned int reuse_texture_ID,
unsigned int flags,
unsigned int opengl_texture_type,
unsigned int opengl_texture_target,
unsigned int texture_check_size_enum
)
{
/* variables */
unsigned char* img;
unsigned int tex_id;
unsigned int internal_texture_format = 0, original_texture_format = 0;
int DXT_mode = SOIL_CAPABILITY_UNKNOWN;
int max_supported_size;
/* If the user wants to use the texture rectangle I kill a few flags */
if( flags & SOIL_FLAG_TEXTURE_RECTANGLE )
{
/* well, the user asked for it, can we do that? */
if( query_tex_rectangle_capability() == SOIL_CAPABILITY_PRESENT )
{
/* only allow this if the user in _NOT_ trying to do a cubemap! */
if( opengl_texture_type == GL_TEXTURE_2D )
{
/* clean out the flags that cannot be used with texture rectangles */
flags &= ~(
SOIL_FLAG_POWER_OF_TWO | SOIL_FLAG_MIPMAPS |
SOIL_FLAG_TEXTURE_REPEATS
);
/* and change my target */
opengl_texture_target = SOIL_TEXTURE_RECTANGLE_ARB;
opengl_texture_type = SOIL_TEXTURE_RECTANGLE_ARB;
} else
{
/* not allowed for any other uses (yes, I'm looking at you, cubemaps!) */
flags &= ~SOIL_FLAG_TEXTURE_RECTANGLE;
}
} else
{
/* can't do it, and that is a breakable offense (uv coords use pixels instead of [0,1]!) */
result_string_pointer = "Texture Rectangle extension unsupported";
return 0;
}
}
/* create a copy the image data */
img = (unsigned char*)malloc( width*height*channels );
memcpy( img, data, width*height*channels );
/* does the user want me to invert the image? */
if( flags & SOIL_FLAG_INVERT_Y )
{
int i, j;
for( j = 0; j*2 < height; ++j )
{
int index1 = j * width * channels;
int index2 = (height - 1 - j) * width * channels;
for( i = width * channels; i > 0; --i )
{
unsigned char temp = img[index1];
img[index1] = img[index2];
img[index2] = temp;
++index1;
++index2;
}
}
}
/* does the user want me to scale the colors into the NTSC safe RGB range? */
if( flags & SOIL_FLAG_NTSC_SAFE_RGB )
{
scale_image_RGB_to_NTSC_safe( img, width, height, channels );
}
/* does the user want me to convert from straight to pre-multiplied alpha?
(and do we even _have_ alpha?) */
if( flags & SOIL_FLAG_MULTIPLY_ALPHA )
{
int i;
switch( channels )
{
case 2:
for( i = 0; i < 2*width*height; i += 2 )
{
img[i] = (img[i] * img[i+1] + 128) >> 8;
}
break;
case 4:
for( i = 0; i < 4*width*height; i += 4 )
{
img[i+0] = (img[i+0] * img[i+3] + 128) >> 8;
img[i+1] = (img[i+1] * img[i+3] + 128) >> 8;
img[i+2] = (img[i+2] * img[i+3] + 128) >> 8;
}
break;
default:
/* no other number of channels contains alpha data */
break;
}
}
/* if the user can't support NPOT textures, make sure we force the POT option */
if( (query_NPOT_capability() == SOIL_CAPABILITY_NONE) &&
!(flags & SOIL_FLAG_TEXTURE_RECTANGLE) )
{
/* add in the POT flag */
flags |= SOIL_FLAG_POWER_OF_TWO;
}
/* how large of a texture can this OpenGL implementation handle? */
/* texture_check_size_enum will be GL_MAX_TEXTURE_SIZE or SOIL_MAX_CUBE_MAP_TEXTURE_SIZE */
glGetIntegerv( texture_check_size_enum, &max_supported_size );
/* do I need to make it a power of 2? */
if(
(flags & SOIL_FLAG_POWER_OF_TWO) || /* user asked for it */
(flags & SOIL_FLAG_MIPMAPS) || /* need it for the MIP-maps */
(width > max_supported_size) || /* it's too big, (make sure it's */
(height > max_supported_size) ) /* 2^n for later down-sampling) */
{
int new_width = 1;
int new_height = 1;
while( new_width < width )
{
new_width *= 2;
}
while( new_height < height )
{
new_height *= 2;
}
/* still? */
if( (new_width != width) || (new_height != height) )
{
/* yep, resize */
unsigned char *resampled = (unsigned char*)malloc( channels*new_width*new_height );
up_scale_image(
img, width, height, channels,
resampled, new_width, new_height );
/* OJO this is for debug only! */
/*
SOIL_save_image( "\\showme.bmp", SOIL_SAVE_TYPE_BMP,
new_width, new_height, channels,
resampled );
*/
/* nuke the old guy, then point it at the new guy */
SOIL_free_image_data( img );
img = resampled;
width = new_width;
height = new_height;
}
}
/* now, if it is too large... */
if( (width > max_supported_size) || (height > max_supported_size) )
{
/* I've already made it a power of two, so simply use the MIPmapping
code to reduce its size to the allowable maximum. */
unsigned char *resampled;
int reduce_block_x = 1, reduce_block_y = 1;
int new_width, new_height;
if( width > max_supported_size )
{
reduce_block_x = width / max_supported_size;
}
if( height > max_supported_size )
{
reduce_block_y = height / max_supported_size;
}
new_width = width / reduce_block_x;
new_height = height / reduce_block_y;
resampled = (unsigned char*)malloc( channels*new_width*new_height );
/* perform the actual reduction */
mipmap_image( img, width, height, channels,
resampled, reduce_block_x, reduce_block_y );
/* nuke the old guy, then point it at the new guy */
SOIL_free_image_data( img );
img = resampled;
width = new_width;
height = new_height;
}
/* does the user want us to use YCoCg color space? */
if( flags & SOIL_FLAG_CoCg_Y )
{
/* this will only work with RGB and RGBA images */
convert_RGB_to_YCoCg( img, width, height, channels );
/*
save_image_as_DDS( "CoCg_Y.dds", width, height, channels, img );
*/
}
/* create the OpenGL texture ID handle
(note: allowing a forced texture ID lets me reload a texture) */
tex_id = reuse_texture_ID;
if( tex_id == 0 )
{
glGenTextures( 1, &tex_id );
}
check_for_GL_errors( "glGenTextures" );
/* Note: sometimes glGenTextures fails (usually no OpenGL context) */
if( tex_id )
{
/* and what type am I using as the internal texture format? */
switch( channels )
{
case 1:
original_texture_format = GL_LUMINANCE;
break;
case 2:
original_texture_format = GL_LUMINANCE_ALPHA;
break;
case 3:
original_texture_format = GL_RGB;
break;
case 4:
original_texture_format = GL_RGBA;
break;
}
internal_texture_format = original_texture_format;
/* does the user want me to, and can I, save as DXT? */
if( flags & SOIL_FLAG_COMPRESS_TO_DXT )
{
DXT_mode = query_DXT_capability();
if( DXT_mode == SOIL_CAPABILITY_PRESENT )
{
/* I can use DXT, whether I compress it or OpenGL does */
if( (channels & 1) == 1 )
{
/* 1 or 3 channels = DXT1 */
internal_texture_format = SOIL_RGB_S3TC_DXT1;
} else
{
/* 2 or 4 channels = DXT5 */
internal_texture_format = SOIL_RGBA_S3TC_DXT5;
}
}
}
/* bind an OpenGL texture ID */
glBindTexture( opengl_texture_type, tex_id );
check_for_GL_errors( "glBindTexture" );
/* upload the main image */
if( DXT_mode == SOIL_CAPABILITY_PRESENT )
{
/* user wants me to do the DXT conversion! */
int DDS_size;
unsigned char *DDS_data = NULL;
if( (channels & 1) == 1 )
{
/* RGB, use DXT1 */
DDS_data = convert_image_to_DXT1( img, width, height, channels, &DDS_size );
} else
{
/* RGBA, use DXT5 */
DDS_data = convert_image_to_DXT5( img, width, height, channels, &DDS_size );
}
if( DDS_data )
{
soilGlCompressedTexImage2D(
opengl_texture_target, 0,
internal_texture_format, width, height, 0,
DDS_size, DDS_data );
check_for_GL_errors( "glCompressedTexImage2D" );
SOIL_free_image_data( DDS_data );
/* printf( "Internal DXT compressor\n" ); */
} else
{
/* my compression failed, try the OpenGL driver's version */
glTexImage2D(
opengl_texture_target, 0,
internal_texture_format, width, height, 0,
original_texture_format, GL_UNSIGNED_BYTE, img );
check_for_GL_errors( "glTexImage2D" );
/* printf( "OpenGL DXT compressor\n" ); */
}
} else
{
/* user want OpenGL to do all the work! */
glTexImage2D(
opengl_texture_target, 0,
internal_texture_format, width, height, 0,
original_texture_format, GL_UNSIGNED_BYTE, img );
check_for_GL_errors( "glTexImage2D" );
/*printf( "OpenGL DXT compressor\n" ); */
}
/* are any MIPmaps desired? */
if( flags & SOIL_FLAG_MIPMAPS )
{
int MIPlevel = 1;
int MIPwidth = (width+1) / 2;
int MIPheight = (height+1) / 2;
unsigned char *resampled = (unsigned char*)malloc( channels*MIPwidth*MIPheight );
while( ((1<<MIPlevel) <= width) || ((1<<MIPlevel) <= height) )
{
/* do this MIPmap level */
mipmap_image(
img, width, height, channels,
resampled,
(1 << MIPlevel), (1 << MIPlevel) );
/* upload the MIPmaps */
if( DXT_mode == SOIL_CAPABILITY_PRESENT )
{
/* user wants me to do the DXT conversion! */
int DDS_size;
unsigned char *DDS_data = NULL;
if( (channels & 1) == 1 )
{
/* RGB, use DXT1 */
DDS_data = convert_image_to_DXT1(
resampled, MIPwidth, MIPheight, channels, &DDS_size );
} else
{
/* RGBA, use DXT5 */
DDS_data = convert_image_to_DXT5(
resampled, MIPwidth, MIPheight, channels, &DDS_size );
}
if( DDS_data )
{
soilGlCompressedTexImage2D(
opengl_texture_target, MIPlevel,
internal_texture_format, MIPwidth, MIPheight, 0,
DDS_size, DDS_data );
check_for_GL_errors( "glCompressedTexImage2D" );
SOIL_free_image_data( DDS_data );
} else
{
/* my compression failed, try the OpenGL driver's version */
glTexImage2D(
opengl_texture_target, MIPlevel,
internal_texture_format, MIPwidth, MIPheight, 0,
original_texture_format, GL_UNSIGNED_BYTE, resampled );
check_for_GL_errors( "glTexImage2D" );
}
} else
{
/* user want OpenGL to do all the work! */
glTexImage2D(
opengl_texture_target, MIPlevel,
internal_texture_format, MIPwidth, MIPheight, 0,
original_texture_format, GL_UNSIGNED_BYTE, resampled );
check_for_GL_errors( "glTexImage2D" );
}
/* prep for the next level */
++MIPlevel;
MIPwidth = (MIPwidth + 1) / 2;
MIPheight = (MIPheight + 1) / 2;
}
SOIL_free_image_data( resampled );
/* instruct OpenGL to use the MIPmaps */
glTexParameteri( opengl_texture_type, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
glTexParameteri( opengl_texture_type, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR );
check_for_GL_errors( "GL_TEXTURE_MIN/MAG_FILTER" );
} else
{
/* instruct OpenGL _NOT_ to use the MIPmaps */
glTexParameteri( opengl_texture_type, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
glTexParameteri( opengl_texture_type, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
check_for_GL_errors( "GL_TEXTURE_MIN/MAG_FILTER" );
}
/* does the user want clamping, or wrapping? */
if( flags & SOIL_FLAG_TEXTURE_REPEATS )
{
glTexParameteri( opengl_texture_type, GL_TEXTURE_WRAP_S, GL_REPEAT );
glTexParameteri( opengl_texture_type, GL_TEXTURE_WRAP_T, GL_REPEAT );
if( opengl_texture_type == SOIL_TEXTURE_CUBE_MAP )
{
/* SOIL_TEXTURE_WRAP_R is invalid if cubemaps aren't supported */
glTexParameteri( opengl_texture_type, SOIL_TEXTURE_WRAP_R, GL_REPEAT );
}
check_for_GL_errors( "GL_TEXTURE_WRAP_*" );
} else
{
unsigned int clamp_mode = SOIL_CLAMP_TO_EDGE;
glTexParameteri( opengl_texture_type, GL_TEXTURE_WRAP_S, clamp_mode );
glTexParameteri( opengl_texture_type, GL_TEXTURE_WRAP_T, clamp_mode );
if( opengl_texture_type == SOIL_TEXTURE_CUBE_MAP )
{
/* SOIL_TEXTURE_WRAP_R is invalid if cubemaps aren't supported */
glTexParameteri( opengl_texture_type, SOIL_TEXTURE_WRAP_R, clamp_mode );
}
check_for_GL_errors( "GL_TEXTURE_WRAP_*" );
}
/* done */
result_string_pointer = "Image loaded as an OpenGL texture";
} else
{
/* failed */
result_string_pointer = "Failed to generate an OpenGL texture name; missing OpenGL context?";
}
SOIL_free_image_data( img );
return tex_id;
}
int
SOIL_save_screenshot
(
const char *filename,
int image_type,
int x, int y,
int width, int height
)
{
unsigned char *pixel_data;
int i, j;
int save_result;
/* error checks */
if( (width < 1) || (height < 1) )
{
result_string_pointer = "Invalid screenshot dimensions";
return 0;
}
if( (x < 0) || (y < 0) )
{
result_string_pointer = "Invalid screenshot location";
return 0;
}
if( filename == NULL )
{
result_string_pointer = "Invalid screenshot filename";
return 0;
}
/* Get the data from OpenGL */
pixel_data = (unsigned char*)malloc( 3*width*height );
glReadPixels (x, y, width, height, GL_RGB, GL_UNSIGNED_BYTE, pixel_data);
/* invert the image */
for( j = 0; j*2 < height; ++j )
{
int index1 = j * width * 3;
int index2 = (height - 1 - j) * width * 3;
for( i = width * 3; i > 0; --i )
{
unsigned char temp = pixel_data[index1];
pixel_data[index1] = pixel_data[index2];
pixel_data[index2] = temp;
++index1;
++index2;
}
}
/* save the image */
save_result = SOIL_save_image( filename, image_type, width, height, 3, pixel_data);
/* And free the memory */
SOIL_free_image_data( pixel_data );
return save_result;
}
unsigned char*
SOIL_load_image
(
const char *filename,
int *width, int *height, int *channels,
int force_channels
)
{
unsigned char *result = stbi_load( filename,
width, height, channels, force_channels );
if( result == NULL )
{
result_string_pointer = stbi_failure_reason();
} else
{
result_string_pointer = "Image loaded";
}
return result;
}
unsigned char*
SOIL_load_image_from_memory
(
const unsigned char *const buffer,
int buffer_length,
int *width, int *height, int *channels,
int force_channels
)
{
unsigned char *result = stbi_load_from_memory(
buffer, buffer_length,
width, height, channels,
force_channels );
if( result == NULL )
{
result_string_pointer = stbi_failure_reason();
} else
{
result_string_pointer = "Image loaded from memory";
}
return result;
}
int
SOIL_save_image
(
const char *filename,
int image_type,
int width, int height, int channels,
const unsigned char *const data
)
{
int save_result;
/* error check */
if( (width < 1) || (height < 1) ||
(channels < 1) || (channels > 4) ||
(data == NULL) ||
(filename == NULL) )
{
return 0;
}
if( image_type == SOIL_SAVE_TYPE_BMP )
{
save_result = stbi_write_bmp( filename,
width, height, channels, (void*)data );
} else
if( image_type == SOIL_SAVE_TYPE_TGA )
{
save_result = stbi_write_tga( filename,
width, height, channels, (void*)data );
} else
if( image_type == SOIL_SAVE_TYPE_DDS )
{
save_result = save_image_as_DDS( filename,
width, height, channels, (const unsigned char *const)data );
} else
{
save_result = 0;
}
if( save_result == 0 )
{
result_string_pointer = "Saving the image failed";
} else
{
result_string_pointer = "Image saved";
}
return save_result;
}
void
SOIL_free_image_data
(
unsigned char *img_data
)
{
free( (void*)img_data );
}
const char*
SOIL_last_result
(
void
)
{
return result_string_pointer;
}
unsigned int SOIL_direct_load_DDS_from_memory(
const unsigned char *const buffer,
int buffer_length,
unsigned int reuse_texture_ID,
int flags,
int loading_as_cubemap )
{
/* variables */
DDS_header header;
unsigned int buffer_index = 0;
unsigned int tex_ID = 0;
/* file reading variables */
unsigned int S3TC_type = 0;
unsigned char *DDS_data;
unsigned int DDS_main_size;
unsigned int DDS_full_size;
unsigned int width, height;
int mipmaps, cubemap, uncompressed, block_size = 16;
unsigned int flag;
unsigned int cf_target, ogl_target_start, ogl_target_end;
unsigned int opengl_texture_type;
int i;
/* 1st off, does the filename even exist? */
if( NULL == buffer )
{
/* we can't do it! */
result_string_pointer = "NULL buffer";
return 0;
}
if( buffer_length < sizeof( DDS_header ) )
{
/* we can't do it! */
result_string_pointer = "DDS file was too small to contain the DDS header";
return 0;
}
/* try reading in the header */
memcpy ( (void*)(&header), (const void *)buffer, sizeof( DDS_header ) );
buffer_index = sizeof( DDS_header );
/* guilty until proven innocent */
result_string_pointer = "Failed to read a known DDS header";
/* validate the header (warning, "goto"'s ahead, shield your eyes!!) */
flag = ('D'<<0)|('D'<<8)|('S'<<16)|(' '<<24);
if( header.dwMagic != flag ) {goto quick_exit;}
if( header.dwSize != 124 ) {goto quick_exit;}
/* I need all of these */
flag = DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH | DDSD_PIXELFORMAT;
if( (header.dwFlags & flag) != flag ) {goto quick_exit;}
/* According to the MSDN spec, the dwFlags should contain
DDSD_LINEARSIZE if it's compressed, or DDSD_PITCH if
uncompressed. Some DDS writers do not conform to the
spec, so I need to make my reader more tolerant */
/* I need one of these */
flag = DDPF_FOURCC | DDPF_RGB;
if( (header.sPixelFormat.dwFlags & flag) == 0 ) {goto quick_exit;}
if( header.sPixelFormat.dwSize != 32 ) {goto quick_exit;}
if( (header.sCaps.dwCaps1 & DDSCAPS_TEXTURE) == 0 ) {goto quick_exit;}
/* make sure it is a type we can upload */
if( (header.sPixelFormat.dwFlags & DDPF_FOURCC) &&
!(
(header.sPixelFormat.dwFourCC == (('D'<<0)|('X'<<8)|('T'<<16)|('1'<<24))) ||
(header.sPixelFormat.dwFourCC == (('D'<<0)|('X'<<8)|('T'<<16)|('3'<<24))) ||
(header.sPixelFormat.dwFourCC == (('D'<<0)|('X'<<8)|('T'<<16)|('5'<<24)))
) )
{
goto quick_exit;
}
/* OK, validated the header, let's load the image data */
result_string_pointer = "DDS header loaded and validated";
width = header.dwWidth;
height = header.dwHeight;
uncompressed = 1 - (header.sPixelFormat.dwFlags & DDPF_FOURCC) / DDPF_FOURCC;
cubemap = (header.sCaps.dwCaps2 & DDSCAPS2_CUBEMAP) / DDSCAPS2_CUBEMAP;
if( uncompressed )
{
S3TC_type = GL_RGB;
block_size = 3;
if( header.sPixelFormat.dwFlags & DDPF_ALPHAPIXELS )
{
S3TC_type = GL_RGBA;
block_size = 4;
}
DDS_main_size = width * height * block_size;
} else
{
/* can we even handle direct uploading to OpenGL DXT compressed images? */
if( query_DXT_capability() != SOIL_CAPABILITY_PRESENT )
{
/* we can't do it! */
result_string_pointer = "Direct upload of S3TC images not supported by the OpenGL driver";
return 0;
}
/* well, we know it is DXT1/3/5, because we checked above */
switch( (header.sPixelFormat.dwFourCC >> 24) - '0' )
{
case 1:
S3TC_type = SOIL_RGBA_S3TC_DXT1;
block_size = 8;
break;
case 3:
S3TC_type = SOIL_RGBA_S3TC_DXT3;
block_size = 16;
break;
case 5:
S3TC_type = SOIL_RGBA_S3TC_DXT5;
block_size = 16;
break;
}
DDS_main_size = ((width+3)>>2)*((height+3)>>2)*block_size;
}
if( cubemap )
{
/* does the user want a cubemap? */
if( !loading_as_cubemap )
{
/* we can't do it! */
result_string_pointer = "DDS image was a cubemap";
return 0;
}
/* can we even handle cubemaps with the OpenGL driver? */
if( query_cubemap_capability() != SOIL_CAPABILITY_PRESENT )
{
/* we can't do it! */
result_string_pointer = "Direct upload of cubemap images not supported by the OpenGL driver";
return 0;
}
ogl_target_start = SOIL_TEXTURE_CUBE_MAP_POSITIVE_X;
ogl_target_end = SOIL_TEXTURE_CUBE_MAP_NEGATIVE_Z;
opengl_texture_type = SOIL_TEXTURE_CUBE_MAP;
} else
{
/* does the user want a non-cubemap? */
if( loading_as_cubemap )
{
/* we can't do it! */
result_string_pointer = "DDS image was not a cubemap";
return 0;
}
ogl_target_start = GL_TEXTURE_2D;
ogl_target_end = GL_TEXTURE_2D;
opengl_texture_type = GL_TEXTURE_2D;
}
if( (header.sCaps.dwCaps1 & DDSCAPS_MIPMAP) && (header.dwMipMapCount > 1) )
{
int shift_offset;
mipmaps = header.dwMipMapCount - 1;
DDS_full_size = DDS_main_size;
if( uncompressed )
{
/* uncompressed DDS, simple MIPmap size calculation */
shift_offset = 0;
} else
{
/* compressed DDS, MIPmap size calculation is block based */
shift_offset = 2;
}
for( i = 1; i <= mipmaps; ++ i )
{
int w, h;
w = width >> (shift_offset + i);
h = height >> (shift_offset + i);
if( w < 1 )
{
w = 1;
}
if( h < 1 )
{
h = 1;
}
DDS_full_size += w*h*block_size;
}
} else
{
mipmaps = 0;
DDS_full_size = DDS_main_size;
}
DDS_data = (unsigned char*)malloc( DDS_full_size );
/* got the image data RAM, create or use an existing OpenGL texture handle */
tex_ID = reuse_texture_ID;
if( tex_ID == 0 )
{
glGenTextures( 1, &tex_ID );
}
/* bind an OpenGL texture ID */
glBindTexture( opengl_texture_type, tex_ID );
/* do this for each face of the cubemap! */
for( cf_target = ogl_target_start; cf_target <= ogl_target_end; ++cf_target )
{
if( buffer_index + DDS_full_size <= buffer_length )
{
unsigned int byte_offset = DDS_main_size;
memcpy( (void*)DDS_data, (const void*)(&buffer[buffer_index]), DDS_full_size );
buffer_index += DDS_full_size;
/* upload the main chunk */
if( uncompressed )
{
/* and remember, DXT uncompressed uses BGR(A),
so swap to RGB(A) for ALL MIPmap levels */
for( i = 0; i < DDS_full_size; i += block_size )
{
unsigned char temp = DDS_data[i];
DDS_data[i] = DDS_data[i+2];
DDS_data[i+2] = temp;
}
glTexImage2D(
cf_target, 0,
S3TC_type, width, height, 0,
S3TC_type, GL_UNSIGNED_BYTE, DDS_data );
} else
{
soilGlCompressedTexImage2D(
cf_target, 0,
S3TC_type, width, height, 0,
DDS_main_size, DDS_data );
}
/* upload the mipmaps, if we have them */
for( i = 1; i <= mipmaps; ++i )
{
int w, h, mip_size;
w = width >> i;
h = height >> i;
if( w < 1 )
{
w = 1;
}
if( h < 1 )
{
h = 1;
}
/* upload this mipmap */
if( uncompressed )
{
mip_size = w*h*block_size;
glTexImage2D(
cf_target, i,
S3TC_type, w, h, 0,
S3TC_type, GL_UNSIGNED_BYTE, &DDS_data[byte_offset] );
} else
{
mip_size = ((w+3)/4)*((h+3)/4)*block_size;
soilGlCompressedTexImage2D(
cf_target, i,
S3TC_type, w, h, 0,
mip_size, &DDS_data[byte_offset] );
}
/* and move to the next mipmap */
byte_offset += mip_size;
}
/* it worked! */
result_string_pointer = "DDS file loaded";
} else
{
glDeleteTextures( 1, & tex_ID );
tex_ID = 0;
cf_target = ogl_target_end + 1;
result_string_pointer = "DDS file was too small for expected image data";
}
}/* end reading each face */
SOIL_free_image_data( DDS_data );
if( tex_ID )
{
/* did I have MIPmaps? */
if( mipmaps > 0 )
{
/* instruct OpenGL to use the MIPmaps */
glTexParameteri( opengl_texture_type, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
glTexParameteri( opengl_texture_type, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR );
} else
{
/* instruct OpenGL _NOT_ to use the MIPmaps */
glTexParameteri( opengl_texture_type, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
glTexParameteri( opengl_texture_type, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
}
/* does the user want clamping, or wrapping? */
if( flags & SOIL_FLAG_TEXTURE_REPEATS )
{
glTexParameteri( opengl_texture_type, GL_TEXTURE_WRAP_S, GL_REPEAT );
glTexParameteri( opengl_texture_type, GL_TEXTURE_WRAP_T, GL_REPEAT );
glTexParameteri( opengl_texture_type, SOIL_TEXTURE_WRAP_R, GL_REPEAT );
} else
{
unsigned int clamp_mode = SOIL_CLAMP_TO_EDGE;
glTexParameteri( opengl_texture_type, GL_TEXTURE_WRAP_S, clamp_mode );
glTexParameteri( opengl_texture_type, GL_TEXTURE_WRAP_T, clamp_mode );
glTexParameteri( opengl_texture_type, SOIL_TEXTURE_WRAP_R, clamp_mode );
}
}
quick_exit:
/* report success or failure */
return tex_ID;
}
unsigned int SOIL_direct_load_DDS(
const char *filename,
unsigned int reuse_texture_ID,
int flags,
int loading_as_cubemap )
{
FILE *f;
unsigned char *buffer;
size_t buffer_length, bytes_read;
unsigned int tex_ID = 0;
/* error checks */
if( NULL == filename )
{
result_string_pointer = "NULL filename";
return 0;
}
f = fopen( filename, "rb" );
if( NULL == f )
{
/* the file doesn't seem to exist (or be open-able) */
result_string_pointer = "Can not find DDS file";
return 0;
}
fseek( f, 0, SEEK_END );
buffer_length = ftell( f );
fseek( f, 0, SEEK_SET );
buffer = (unsigned char *) malloc( buffer_length );
if( NULL == buffer )
{
result_string_pointer = "malloc failed";
fclose( f );
return 0;
}
bytes_read = fread( (void*)buffer, 1, buffer_length, f );
fclose( f );
if( bytes_read < buffer_length )
{
/* huh? */
buffer_length = bytes_read;
}
/* now try to do the loading */
tex_ID = SOIL_direct_load_DDS_from_memory(
(const unsigned char *const)buffer, buffer_length,
reuse_texture_ID, flags, loading_as_cubemap );
SOIL_free_image_data( buffer );
return tex_ID;
}
int query_NPOT_capability( void )
{
/* check for the capability */
if( has_NPOT_capability == SOIL_CAPABILITY_UNKNOWN )
{
/* we haven't yet checked for the capability, do so */
if(
(NULL == strstr( (char const*)glGetString( GL_EXTENSIONS ),
"GL_ARB_texture_non_power_of_two" ) )
&&
(NULL == strstr( (char const*)glGetString( GL_EXTENSIONS ),
"GL_OES_texture_npot" ) )
)
{
/* not there, flag the failure */
has_NPOT_capability = SOIL_CAPABILITY_NONE;
} else
{
/* it's there! */
has_NPOT_capability = SOIL_CAPABILITY_PRESENT;
}
}
/* let the user know if we can do non-power-of-two textures or not */
return has_NPOT_capability;
}
int query_tex_rectangle_capability( void )
{
/* check for the capability */
if( has_tex_rectangle_capability == SOIL_CAPABILITY_UNKNOWN )
{
/* we haven't yet checked for the capability, do so */
if(
(NULL == strstr( (char const*)glGetString( GL_EXTENSIONS ),
"GL_ARB_texture_rectangle" ) )
&&
(NULL == strstr( (char const*)glGetString( GL_EXTENSIONS ),
"GL_EXT_texture_rectangle" ) )
&&
(NULL == strstr( (char const*)glGetString( GL_EXTENSIONS ),
"GL_NV_texture_rectangle" ) )
)
{
/* not there, flag the failure */
has_tex_rectangle_capability = SOIL_CAPABILITY_NONE;
} else
{
/* it's there! */
has_tex_rectangle_capability = SOIL_CAPABILITY_PRESENT;
}
}
/* let the user know if we can do texture rectangles or not */
return has_tex_rectangle_capability;
}
int query_cubemap_capability( void )
{
/* check for the capability */
if( has_cubemap_capability == SOIL_CAPABILITY_UNKNOWN )
{
/* we haven't yet checked for the capability, do so */
if(
(NULL == strstr( (char const*)glGetString( GL_EXTENSIONS ),
"GL_ARB_texture_cube_map" ) )
&&
(NULL == strstr( (char const*)glGetString( GL_EXTENSIONS ),
"GL_EXT_texture_cube_map" ) )
#ifdef GL_ES_VERSION_2_0
&& (0) /* GL ES 2.0 supports cubemaps, always enable */
#endif
)
{
/* not there, flag the failure */
has_cubemap_capability = SOIL_CAPABILITY_NONE;
} else
{
/* it's there! */
has_cubemap_capability = SOIL_CAPABILITY_PRESENT;
}
}
/* let the user know if we can do cubemaps or not */
return has_cubemap_capability;
}
int query_DXT_capability( void )
{
/* check for the capability */
if( has_DXT_capability == SOIL_CAPABILITY_UNKNOWN )
{
/* we haven't yet checked for the capability, do so */
if( NULL == strstr(
(char const*)glGetString( GL_EXTENSIONS ),
"GL_EXT_texture_compression_s3tc" ) )
{
/* not there, flag the failure */
has_DXT_capability = SOIL_CAPABILITY_NONE;
} else
{
/* and find the address of the extension function */
P_SOIL_GLCOMPRESSEDTEXIMAGE2DPROC ext_addr = NULL;
#ifdef WIN32
ext_addr = (P_SOIL_GLCOMPRESSEDTEXIMAGE2DPROC)
wglGetProcAddress
(
"glCompressedTexImage2DARB"
);
#elif defined(__APPLE__) || defined(__APPLE_CC__)
/* I can't test this Apple stuff! */
CFBundleRef bundle;
CFURLRef bundleURL =
CFURLCreateWithFileSystemPath(
kCFAllocatorDefault,
CFSTR("/System/Library/Frameworks/OpenGL.framework"),
kCFURLPOSIXPathStyle,
true );
CFStringRef extensionName =
CFStringCreateWithCString(
kCFAllocatorDefault,
"glCompressedTexImage2DARB",
kCFStringEncodingASCII );
bundle = CFBundleCreate( kCFAllocatorDefault, bundleURL );
assert( bundle != NULL );
ext_addr = (P_SOIL_GLCOMPRESSEDTEXIMAGE2DPROC)
CFBundleGetFunctionPointerForName
(
bundle, extensionName
);
CFRelease( bundleURL );
CFRelease( extensionName );
CFRelease( bundle );
#elif defined(__ANDROID__) || defined(__EMSCRIPTEN__)
ext_addr = (P_SOIL_GLCOMPRESSEDTEXIMAGE2DPROC)(glCompressedTexImage2D);
#else
ext_addr = (P_SOIL_GLCOMPRESSEDTEXIMAGE2DPROC)
glXGetProcAddressARB
(
(const GLubyte *)"glCompressedTexImage2DARB"
);
#endif
/* Flag it so no checks needed later */
if( NULL == ext_addr )
{
/* hmm, not good!! This should not happen, but does on my
laptop's VIA chipset. The GL_EXT_texture_compression_s3tc
spec requires that ARB_texture_compression be present too.
this means I can upload and have the OpenGL drive do the
conversion, but I can't use my own routines or load DDS files
from disk and upload them directly [8^( */
has_DXT_capability = SOIL_CAPABILITY_NONE;
} else
{
/* all's well! */
soilGlCompressedTexImage2D = ext_addr;
has_DXT_capability = SOIL_CAPABILITY_PRESENT;
}
}
}
/* let the user know if we can do DXT or not */
return has_DXT_capability;
}
================================================
FILE: src/SOIL.h
================================================
/**
@mainpage SOIL
Jonathan Dummer
2007-07-26-10.36
Simple OpenGL Image Library
A tiny c library for uploading images as
textures into OpenGL. Also saving and
loading of images is supported.
I'm using Sean's Tool Box image loader as a base:
http://www.nothings.org/
I'm upgrading it to load TGA and DDS files, and a direct
path for loading DDS files straight into OpenGL textures,
when applicable.
Image Formats:
- BMP load & save
- TGA load & save
- DDS load & save
- PNG load
- JPG load
OpenGL Texture Features:
- resample to power-of-two sizes
- MIPmap generation
- compressed texture S3TC formats (if supported)
- can pre-multiply alpha for you, for better compositing
- can flip image about the y-axis (except pre-compressed DDS files)
Thanks to:
* Sean Barret - for the awesome stb_image
* Dan Venkitachalam - for finding some non-compliant DDS files, and patching some explicit casts
* everybody at gamedev.net
**/
#ifndef HEADER_SIMPLE_OPENGL_IMAGE_LIBRARY
#define HEADER_SIMPLE_OPENGL_IMAGE_LIBRARY
#ifdef __cplusplus
extern "C" {
#endif
/**
The format of images that may be loaded (force_channels).
SOIL_LOAD_AUTO leaves the image in whatever format it was found.
SOIL_LOAD_L forces the image to load as Luminous (greyscale)
SOIL_LOAD_LA forces the image to load as Luminous with Alpha
SOIL_LOAD_RGB forces the image to load as Red Green Blue
SOIL_LOAD_RGBA forces the image to load as Red Green Blue Alpha
**/
enum
{
SOIL_LOAD_AUTO = 0,
SOIL_LOAD_L = 1,
SOIL_LOAD_LA = 2,
SOIL_LOAD_RGB = 3,
SOIL_LOAD_RGBA = 4
};
/**
Passed in as reuse_texture_ID, will cause SOIL to
register a new texture ID using glGenTextures().
If the value passed into reuse_texture_ID > 0 then
SOIL will just re-use that texture ID (great for
reloading image assets in-game!)
**/
enum
{
SOIL_CREATE_NEW_ID = 0
};
/**
flags you can pass into SOIL_load_OGL_texture()
and SOIL_create_OGL_texture().
(note that if SOIL_FLAG_DDS_LOAD_DIRECT is used
the rest of the flags with the exception of
SOIL_FLAG_TEXTURE_REPEATS will be ignored while
loading already-compressed DDS files.)
SOIL_FLAG_POWER_OF_TWO: force the image to be POT
SOIL_FLAG_MIPMAPS: generate mipmaps for the texture
SOIL_FLAG_TEXTURE_REPEATS: otherwise will clamp
SOIL_FLAG_MULTIPLY_ALPHA: for using (GL_ONE,GL_ONE_MINUS_SRC_ALPHA) blending
SOIL_FLAG_INVERT_Y: flip the image vertically
SOIL_FLAG_COMPRESS_TO_DXT: if the card can display them, will convert RGB to DXT1, RGBA to DXT5
SOIL_FLAG_DDS_LOAD_DIRECT: will load DDS files directly without _ANY_ additional processing
SOIL_FLAG_NTSC_SAFE_RGB: clamps RGB components to the range [16,235]
SOIL_FLAG_CoCg_Y: Google YCoCg; RGB=>CoYCg, RGBA=>CoCgAY
SOIL_FLAG_TEXTURE_RECTANGE: uses ARB_texture_rectangle ; pixel indexed & no repeat or MIPmaps or cubemaps
**/
enum
{
SOIL_FLAG_POWER_OF_TWO = 1,
SOIL_FLAG_MIPMAPS = 2,
SOIL_FLAG_TEXTURE_REPEATS = 4,
SOIL_FLAG_MULTIPLY_ALPHA = 8,
SOIL_FLAG_INVERT_Y = 16,
SOIL_FLAG_COMPRESS_TO_DXT = 32,
SOIL_FLAG_DDS_LOAD_DIRECT = 64,
SOIL_FLAG_NTSC_SAFE_RGB = 128,
SOIL_FLAG_CoCg_Y = 256,
SOIL_FLAG_TEXTURE_RECTANGLE = 512
};
/**
The types of images that may be saved.
(TGA supports uncompressed RGB / RGBA)
(BMP supports uncompressed RGB)
(DDS supports DXT1 and DXT5)
**/
enum
{
SOIL_SAVE_TYPE_TGA = 0,
SOIL_SAVE_TYPE_BMP = 1,
SOIL_SAVE_TYPE_DDS = 2
};
/**
Defines the order of faces in a DDS cubemap.
I recommend that you use the same order in single
image cubemap files, so they will be interchangeable
with DDS cubemaps when using SOIL.
**/
#define SOIL_DDS_CUBEMAP_FACE_ORDER "EWUDNS"
/**
The types of internal fake HDR representations
SOIL_HDR_RGBE: RGB * pow( 2.0, A - 128.0 )
SOIL_HDR_RGBdivA: RGB / A
SOIL_HDR_RGBdivA2: RGB / (A*A)
**/
enum
{
SOIL_HDR_RGBE = 0,
SOIL_HDR_RGBdivA = 1,
SOIL_HDR_RGBdivA2 = 2
};
/**
Loads an image from disk into an OpenGL texture.
\param filename the name of the file to upload as a texture
\param force_channels 0-image format, 1-luminous, 2-luminous/alpha, 3-RGB, 4-RGBA
\param reuse_texture_ID 0-generate a new texture ID, otherwise reuse the texture ID (overwriting the old texture)
\param flags can be any of SOIL_FLAG_POWER_OF_TWO | SOIL_FLAG_MIPMAPS | SOIL_FLAG_TEXTURE_REPEATS | SOIL_FLAG_MULTIPLY_ALPHA | SOIL_FLAG_INVERT_Y | SOIL_FLAG_COMPRESS_TO_DXT | SOIL_FLAG_DDS_LOAD_DIRECT
\return 0-failed, otherwise returns the OpenGL texture handle
**/
unsigned int
SOIL_load_OGL_texture
(
const char *filename,
int force_channels,
unsigned int reuse_texture_ID,
unsigned int flags
);
/**
Loads 6 images from disk into an OpenGL cubemap texture.
\param x_pos_file the name of the file to upload as the +x cube face
\param x_neg_file the name of the file to upload as the -x cube face
\param y_pos_file the name of the file to upload as the +y cube face
\param y_neg_file the name of the file to upload as the -y cube face
\param z_pos_file the name of the file to upload as the +z cube face
\param z_neg_file the name of the file to upload as the -z cube face
\param force_channels 0-image format, 1-luminous, 2-luminous/alpha, 3-RGB, 4-RGBA
\param reuse_texture_ID 0-generate a new texture ID, otherwise reuse the texture ID (overwriting the old texture)
\param flags can be any of SOIL_FLAG_POWER_OF_TWO | SOIL_FLAG_MIPMAPS | SOIL_FLAG_TEXTURE_REPEATS | SOIL_FLAG_MULTIPLY_ALPHA | SOIL_FLAG_INVERT_Y | SOIL_FLAG_COMPRESS_TO_DXT | SOIL_FLAG_DDS_LOAD_DIRECT
\return 0-failed, otherwise returns the OpenGL texture handle
**/
unsigned int
SOIL_load_OGL_cubemap
(
const char *x_pos_file,
const char *x_neg_file,
const char *y_pos_file,
const char *y_neg_file,
const char *z_pos_file,
const char *z_neg_file,
int force_channels,
unsigned int reuse_texture_ID,
unsigned int flags
);
/**
Loads 1 image from disk and splits it into an OpenGL cubemap texture.
\param filename the name of the file to upload as a texture
\param face_order the order of the faces in the file, any combination of NSWEUD, for North, South, Up, etc.
\param force_channels 0-image format, 1-luminous, 2-luminous/alpha, 3-RGB, 4-RGBA
\param reuse_texture_ID 0-generate a new texture ID, otherwise reuse the texture ID (overwriting the old texture)
\param flags can be any of SOIL_FLAG_POWER_OF_TWO | SOIL_FLAG_MIPMAPS | SOIL_FLAG_TEXTURE_REPEATS | SOIL_FLAG_MULTIPLY_ALPHA | SOIL_FLAG_INVERT_Y | SOIL_FLAG_COMPRESS_TO_DXT | SOIL_FLAG_DDS_LOAD_DIRECT
\return 0-failed, otherwise returns the OpenGL texture handle
**/
unsigned int
SOIL_load_OGL_single_cubemap
(
const char *filename,
const char face_order[6],
int force_channels,
unsigned int reuse_texture_ID,
unsigned int flags
);
/**
Loads an HDR image from disk into an OpenGL texture.
\param filename the name of the file to upload as a texture
\param fake_HDR_format SOIL_HDR_RGBE, SOIL_HDR_RGBdivA, SOIL_HDR_RGBdivA2
\param reuse_texture_ID 0-generate a new texture ID, otherwise reuse the texture ID (overwriting the old texture)
\param flags can be any of SOIL_FLAG_POWER_OF_TWO | SOIL_FLAG_MIPMAPS | SOIL_FLAG_TEXTURE_REPEATS | SOIL_FLAG_MULTIPLY_ALPHA | SOIL_FLAG_INVERT_Y | SOIL_FLAG_COMPRESS_TO_DXT
\return 0-failed, otherwise returns the OpenGL texture handle
**/
unsigned int
SOIL_load_OGL_HDR_texture
(
const char *filename,
int fake_HDR_format,
int rescale_to_max,
unsigned int reuse_texture_ID,
unsigned int flags
);
/**
Loads an image from RAM into an OpenGL texture.
\param buffer the image data in RAM just as if it were still in a file
\param buffer_length the size of the buffer in bytes
\param force_channels 0-image format, 1-luminous, 2-luminous/alpha, 3-RGB, 4-RGBA
\param reuse_texture_ID 0-generate a new texture ID, otherwise reuse the texture ID (overwriting the old texture)
\param flags can be any of SOIL_FLAG_POWER_OF_TWO | SOIL_FLAG_MIPMAPS | SOIL_FLAG_TEXTURE_REPEATS | SOIL_FLAG_MULTIPLY_ALPHA | SOIL_FLAG_INVERT_Y | SOIL_FLAG_COMPRESS_TO_DXT | SOIL_FLAG_DDS_LOAD_DIRECT
\return 0-failed, otherwise returns the OpenGL texture handle
**/
unsigned int
SOIL_load_OGL_texture_from_memory
(
const unsigned char *const buffer,
int buffer_length,
int force_channels,
unsigned int reuse_texture_ID,
unsigned int flags
);
/**
Loads 6 images from memory into an OpenGL cubemap texture.
\param x_pos_buffer the image data in RAM to upload as the +x cube face
\param x_pos_buffer_length the size of the above buffer
\param x_neg_buffer the image data in RAM to upload as the +x cube face
\param x_neg_buffer_length the size of the above buffer
\param y_pos_buffer the image data in RAM to upload as the +x cube face
\param y_pos_buffer_length the size of the above buffer
\param y_neg_buffer the image data in RAM to upload as the +x cube face
\param y_neg_buffer_length the size of the above buffer
\param z_pos_buffer the image data in RAM to upload as the +x cube face
\param z_pos_buffer_length the size of the above buffer
\param z_neg_buffer the image data in RAM to upload as the +x cube face
\param z_neg_buffer_length the size of the above buffer
\param force_channels 0-image format, 1-luminous, 2-luminous/alpha, 3-RGB, 4-RGBA
\param reuse_texture_ID 0-generate a new texture ID, otherwise reuse the texture ID (overwriting the old texture)
\param flags can be any of SOIL_FLAG_POWER_OF_TWO | SOIL_FLAG_MIPMAPS | SOIL_FLAG_TEXTURE_REPEATS | SOIL_FLAG_MULTIPLY_ALPHA | SOIL_FLAG_INVERT_Y | SOIL_FLAG_COMPRESS_TO_DXT | SOIL_FLAG_DDS_LOAD_DIRECT
\return 0-failed, otherwise returns the OpenGL texture handle
**/
unsigned int
SOIL_load_OGL_cubemap_from_memory
(
const unsigned char *const x_pos_buffer,
int x_pos_buffer_length,
const unsigned char *const x_neg_buffer,
int x_neg_buffer_length,
const unsigned char *const y_pos_buffer,
int y_pos_buffer_length,
const unsigned char *const y_neg_buffer,
int y_neg_buffer_length,
const unsigned char *const z_pos_buffer,
int z_pos_buffer_length,
const unsigned char *const z_neg_buffer,
int z_neg_buffer_length,
int force_channels,
unsigned int reuse_texture_ID,
unsigned int flags
);
/**
Loads 1 image from RAM and splits it into an OpenGL cubemap texture.
\param buffer the image data in RAM just as if it were still in a file
\param buffer_length the size of the buffer in bytes
\param face_order the order of the faces in the file, any combination of NSWEUD, for North, South, Up, etc.
\param force_channels 0-image format, 1-luminous, 2-luminous/alpha, 3-RGB, 4-RGBA
\param reuse_texture_ID 0-generate a new texture ID, otherwise reuse the texture ID (overwriting the old texture)
\param flags can be any of SOIL_FLAG_POWER_OF_TWO | SOIL_FLAG_MIPMAPS | SOIL_FLAG_TEXTURE_REPEATS | SOIL_FLAG_MULTIPLY_ALPHA | SOIL_FLAG_INVERT_Y | SOIL_FLAG_COMPRESS_TO_DXT | SOIL_FLAG_DDS_LOAD_DIRECT
\return 0-failed, otherwise returns the OpenGL texture handle
**/
unsigned int
SOIL_load_OGL_single_cubemap_from_memory
(
const unsigned char *const buffer,
int buffer_length,
const char face_order[6],
int force_channels,
unsigned int reuse_texture_ID,
unsigned int flags
);
/**
Creates a 2D OpenGL texture from raw image data. Note that the raw data is
_NOT_ freed after the upload (so the user can load various versions).
\param data the raw data to be uploaded as an OpenGL texture
\param width the width of the image in pixels
\param height the height of the image in pixels
\param channels the number of channels: 1-luminous, 2-luminous/alpha, 3-RGB, 4-RGBA
\param reuse_texture_ID 0-generate a new texture ID, otherwise reuse the texture ID (overwriting the old texture)
\param flags can be any of SOIL_FLAG_POWER_OF_TWO | SOIL_FLAG_MIPMAPS | SOIL_FLAG_TEXTURE_REPEATS | SOIL_FLAG_MULTIPLY_ALPHA | SOIL_FLAG_INVERT_Y | SOIL_FLAG_COMPRESS_TO_DXT
\return 0-failed, otherwise returns the OpenGL texture handle
**/
unsigned int
SOIL_create_OGL_texture
(
const unsigned char *const data,
int width, int height, int channels,
unsigned int reuse_texture_ID,
unsigned int flags
);
/**
Creates an OpenGL cubemap texture by splitting up 1 image into 6 parts.
\param data the raw data to be uploaded as an OpenGL texture
\param width the width of the image in pixels
\param height the height of the image in pixels
\param channels the number of channels: 1-luminous, 2-luminous/alpha, 3-RGB, 4-RGBA
\param face_order the order of the faces in the file, and combination of NSWEUD, for North, South, Up, etc.
\param reuse_texture_ID 0-generate a new texture ID, otherwise reuse the texture ID (overwriting the old texture)
\param flags can be any of SOIL_FLAG_POWER_OF_TWO | SOIL_FLAG_MIPMAPS | SOIL_FLAG_TEXTURE_REPEATS | SOIL_FLAG_MULTIPLY_ALPHA | SOIL_FLAG_INVERT_Y | SOIL_FLAG_COMPRESS_TO_DXT | SOIL_FLAG_DDS_LOAD_DIRECT
\return 0-failed, otherwise returns the OpenGL texture handle
**/
unsigned int
SOIL_create_OGL_single_cubemap
(
const unsigned char *const data,
int width, int height, int channels,
const char face_order[6],
unsigned int reuse_texture_ID,
unsigned int flags
);
/**
Captures the OpenGL window (RGB) and saves it to disk
\return 0 if it failed, otherwise returns 1
**/
int
SOIL_save_screenshot
(
const char *filename,
int image_type,
int x, int y,
int width, int height
);
/**
Loads an image from disk into an array of unsigned chars.
Note that *channels return the original channel count of the
image. If force_channels was other than SOIL_LOAD_AUTO,
the resulting image has force_channels, but *channels may be
different (if the original image had a different channel
count).
\return 0 if failed, otherwise returns 1
**/
unsigned char*
SOIL_load_image
(
const char *filename,
int *width, int *height, int *channels,
int force_channels
);
/**
Loads an image from memory into an array of unsigned chars.
Note that *channels return the original channel count of the
image. If force_channels was other than SOIL_LOAD_AUTO,
the resulting image has force_channels, but *channels may be
different (if the original image had a different channel
count).
\return 0 if failed, otherwise returns 1
**/
unsigned char*
SOIL_load_image_from_memory
(
const unsigned char *const buffer,
int buffer_length,
int *width, int *height, int *channels,
int force_channels
);
/**
Saves an image from an array of unsigned chars (RGBA) to disk
\return 0 if failed, otherwise returns 1
**/
int
SOIL_save_image
(
const char *filename,
int image_type,
int width, int height, int channels,
const unsigned char *const data
);
/**
Frees the image data (note, this is just C's "free()"...this function is
present mostly so C++ programmers don't forget to use "free()" and call
"delete []" instead [8^)
**/
void
SOIL_free_image_data
(
unsigned char *img_data
);
/**
This function resturn a pointer to a string describing the last thing
that happened inside SOIL. It can be used to determine why an image
failed to load.
**/
const char*
SOIL_last_result
(
void
);
#ifdef __cplusplus
}
#endif
#endif /* HEADER_SIMPLE_OPENGL_IMAGE_LIBRARY */
================================================
FILE: src/image_DXT.c
================================================
/*
Jonathan Dummer
2007-07-31-10.32
simple DXT compression / decompression code
public domain
*/
#include "image_DXT.h"
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
/* set this =1 if you want to use the covarince matrix method...
which is better than my method of using standard deviations
overall, except on the infintesimal chance that the power
method fails for finding the largest eigenvector */
#define USE_COV_MAT 1
/********* Function Prototypes *********/
/*
Takes a 4x4 block of pixels and compresses it into 8 bytes
in DXT1 format (color only, no alpha). Speed is valued
over prettyness, at least for now.
*/
void compress_DDS_color_block(
int channels,
const unsigned char *const uncompressed,
unsigned char compressed[8] );
/*
Takes a 4x4 block of pixels and compresses the alpha
component it into 8 bytes for use in DXT5 DDS files.
Speed is valued over prettyness, at least for now.
*/
void compress_DDS_alpha_block(
const unsigned char *const uncompressed,
unsigned char compressed[8] );
/********* Actual Exposed Functions *********/
int
save_image_as_DDS
(
const char *filename,
int width, int height, int channels,
const unsigned char *const data
)
{
/* variables */
FILE *fout;
unsigned char *DDS_data;
DDS_header header;
int DDS_size;
/* error check */
if( (NULL == filename) ||
(width < 1) || (height < 1) ||
(channels < 1) || (channels > 4) ||
(data == NULL ) )
{
return 0;
}
/* Convert the image */
if( (channels & 1) == 1 )
{
/* no alpha, just use DXT1 */
DDS_data = convert_image_to_DXT1( data, width, height, channels, &DDS_size );
} else
{
/* has alpha, so use DXT5 */
DDS_data = convert_image_to_DXT5( data, width, height, channels, &DDS_size );
}
/* save it */
memset( &header, 0, sizeof( DDS_header ) );
header.dwMagic = ('D' << 0) | ('D' << 8) | ('S' << 16) | (' ' << 24);
header.dwSize = 124;
header.dwFlags = DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH | DDSD_PIXELFORMAT | DDSD_LINEARSIZE;
header.dwWidth = width;
header.dwHeight = height;
header.dwPitchOrLinearSize = DDS_size;
header.sPixelFormat.dwSize = 32;
header.sPixelFormat.dwFlags = DDPF_FOURCC;
if( (channels & 1) == 1 )
{
header.sPixelFormat.dwFourCC = ('D' << 0) | ('X' << 8) | ('T' << 16) | ('1' << 24);
} else
{
header.sPixelFormat.dwFourCC = ('D' << 0) | ('X' << 8) | ('T' << 16) | ('5' << 24);
}
header.sCaps.dwCaps1 = DDSCAPS_TEXTURE;
/* write it out */
fout = fopen( filename, "wb");
fwrite( &header, sizeof( DDS_header ), 1, fout );
fwrite( DDS_data, 1, DDS_size, fout );
fclose( fout );
/* done */
free( DDS_data );
return 1;
}
unsigned char* convert_image_to_DXT1(
const unsigned char *const uncompressed,
int width, int height, int channels,
int *out_size )
{
unsigned char *compressed;
int i, j, x, y;
unsigned char ublock[16*3];
unsigned char cblock[8];
int index = 0, chan_step = 1;
int block_count = 0;
/* error check */
*out_size = 0;
if( (width < 1) || (height < 1) ||
(NULL == uncompressed) ||
(channels < 1) || (channels > 4) )
{
return NULL;
}
/* for channels == 1 or 2, I do not step forward for R,G,B values */
if( channels < 3 )
{
chan_step = 0;
}
/* get the RAM for the compressed image
(8 bytes per 4x4 pixel block) */
*out_size = ((width+3) >> 2) * ((height+3) >> 2) * 8;
compressed = (unsigned char*)malloc( *out_size );
/* go through each block */
for( j = 0; j < height; j += 4 )
{
for( i = 0; i < width; i += 4 )
{
/* copy this block into a new one */
int idx = 0;
int mx = 4, my = 4;
if( j+4 >= height )
{
my = height - j;
}
if( i+4 >= width )
{
mx = width - i;
}
for( y = 0; y < my; ++y )
{
for( x = 0; x < mx; ++x )
{
ublock[idx++] = uncompressed[(j+y)*width*channels+(i+x)*channels];
ublock[idx++] = uncompressed[(j+y)*width*channels+(i+x)*channels+chan_step];
ublock[idx++] = uncompressed[(j+y)*width*channels+(i+x)*channels+chan_step+chan_step];
}
for( x = mx; x < 4; ++x )
{
ublock[idx++] = ublock[0];
ublock[idx++] = ublock[1];
ublock[idx++] = ublock[2];
}
}
for( y = my; y < 4; ++y )
{
for( x = 0; x < 4; ++x )
{
ublock[idx++] = ublock[0];
ublock[idx++] = ublock[1];
ublock[idx++] = ublock[2];
}
}
/* compress the block */
++block_count;
compress_DDS_color_block( 3, ublock, cblock );
/* copy the data from the block into the main block */
for( x = 0; x < 8; ++x )
{
compressed[index++] = cblock[x];
}
}
}
return compressed;
}
unsigned char* convert_image_to_DXT5(
const unsigned char *const uncompressed,
int width, int height, int channels,
int *out_size )
{
unsigned char *compressed;
int i, j, x, y;
unsigned char ublock[16*4];
unsigned char cblock[8];
int index = 0, chan_step = 1;
int block_count = 0, has_alpha;
/* error check */
*out_size = 0;
if( (width < 1) || (height < 1) ||
(NULL == uncompressed) ||
(channels < 1) || ( channels > 4) )
{
return NULL;
}
/* for channels == 1 or 2, I do not step forward for R,G,B vales */
if( channels < 3 )
{
chan_step = 0;
}
/* # channels = 1 or 3 have no alpha, 2 & 4 do have alpha */
has_alpha = 1 - (channels & 1);
/* get the RAM for the compressed image
(16 bytes per 4x4 pixel block) */
*out_size = ((width+3) >> 2) * ((height+3) >> 2) * 16;
compressed = (unsigned char*)malloc( *out_size );
/* go through each block */
for( j = 0; j < height; j += 4 )
{
for( i = 0; i < width; i += 4 )
{
/* local variables, and my block counter */
int idx = 0;
int mx = 4, my = 4;
if( j+4 >= height )
{
my = height - j;
}
if( i+4 >= width )
{
mx = width - i;
}
for( y = 0; y < my; ++y )
{
for( x = 0; x < mx; ++x )
{
ublock[idx++] = uncompressed[(j+y)*width*channels+(i+x)*channels];
ublock[idx++] = uncompressed[(j+y)*width*channels+(i+x)*channels+chan_step];
ublock[idx++] = uncompressed[(j+y)*width*channels+(i+x)*channels+chan_step+chan_step];
ublock[idx++] =
has_alpha * uncompressed[(j+y)*width*channels+(i+x)*channels+channels-1]
+ (1-has_alpha)*255;
}
for( x = mx; x < 4; ++x )
{
ublock[idx++] = ublock[0];
ublock[idx++] = ublock[1];
ublock[idx++] = ublock[2];
ublock[idx++] = ublock[3];
}
}
for( y = my; y < 4; ++y )
{
for( x = 0; x < 4; ++x )
{
ublock[idx++] = ublock[0];
ublock[idx++] = ublock[1];
ublock[idx++] = ublock[2];
ublock[idx++] = ublock[3];
}
}
/* now compress the alpha block */
compress_DDS_alpha_block( ublock, cblock );
/* copy the data from the compressed alpha block into the main buffer */
for( x = 0; x < 8; ++x )
{
compressed[index++] = cblock[x];
}
/* then compress the color block */
++block_count;
compress_DDS_color_block( 4, ublock, cblock );
/* copy the data from the compressed color block into the main buffer */
for( x = 0; x < 8; ++x )
{
compressed[index++] = cblock[x];
}
}
}
return compressed;
}
/********* Helper Functions *********/
int convert_bit_range( int c, int from_bits, int to_bits )
{
int b = (1 << (from_bits - 1)) + c * ((1 << to_bits) - 1);
return (b + (b >> from_bits)) >> from_bits;
}
int rgb_to_565( int r, int g, int b )
{
return
(convert_bit_range( r, 8, 5 ) << 11) |
(convert_bit_range( g, 8, 6 ) << 05) |
(convert_bit_range( b, 8, 5 ) << 00);
}
void rgb_888_from_565( unsigned int c, int *r, int *g, int *b )
{
*r = convert_bit_range( (c >> 11) & 31, 5, 8 );
*g = convert_bit_range( (c >> 05) & 63, 6, 8 );
*b = convert_bit_range( (c >> 00) & 31, 5, 8 );
}
void compute_color_line_STDEV(
const unsigned char *const uncompressed,
int channels,
float point[3], float direction[3] )
{
const float inv_16 = 1.0f / 16.0f;
int i;
float sum_r = 0.0f, sum_g = 0.0f, sum_b = 0.0f;
float sum_rr = 0.0f, sum_gg = 0.0f, sum_bb = 0.0f;
float sum_rg = 0.0f, sum_rb = 0.0f, sum_gb = 0.0f;
/* calculate all data needed for the covariance matrix
( to compare with _rygdxt code) */
for( i = 0; i < 16*channels; i += channels )
{
sum_r += uncompressed[i+0];
sum_rr += uncompressed[i+0] * uncompressed[i+0];
sum_g += uncompressed[i+1];
sum_gg += uncompressed[i+1] * uncompressed[i+1];
sum_b += uncompressed[i+2];
sum_bb += uncompressed[i+2] * uncompressed[i+2];
sum_rg += uncompressed[i+0] * uncompressed[i+1];
sum_rb += uncompressed[i+0] * uncompressed[i+2];
sum_gb += uncompressed[i+1] * uncompressed[i+2];
}
/* convert the sums to averages */
sum_r *= inv_16;
sum_g *= inv_16;
sum_b *= inv_16;
/* and convert the squares to the squares of the value - avg_value */
sum_rr -= 16.0f * sum_r * sum_r;
sum_gg -= 16.0f * sum_g * sum_g;
sum_bb -= 16.0f * sum_b * sum_b;
sum_rg -= 16.0f * sum_r * sum_g;
sum_rb -= 16.0f * sum_r * sum_b;
sum_gb -= 16.0f * sum_g * sum_b;
/* the point on the color line is the average */
point[0] = sum_r;
point[1] = sum_g;
point[2] = sum_b;
#if USE_COV_MAT
/*
The following idea was from ryg.
(https://mollyrocket.com/forums/viewtopic.php?t=392)
The method worked great (less RMSE than mine) most of
the time, but had some issues handling some simple
boundary cases, like full green next to full red,
which would generate a covariance matrix like this:
| 1 -1 0 |
| -1 1 0 |
| 0 0 0 |
For a given starting vector, the power method can
generate all zeros! So no starting with {1,1,1}
as I was doing! This kind of error is still a
slight posibillity, but will be very rare.
*/
/* use the covariance matrix directly
(1st iteration, don't use all 1.0 values!) */
sum_r = 1.0f;
sum_g = 2.718281828f;
sum_b = 3.141592654f;
direction[0] = sum_r*sum_rr + sum_g*sum_rg + sum_b*sum_rb;
direction[1] = sum_r*sum_rg + sum_g*sum_gg + sum_b*sum_gb;
direction[2] = sum_r*sum_rb + sum_g*sum_gb + sum_b*sum_bb;
/* 2nd iteration, use results from the 1st guy */
sum_r = direction[0];
sum_g = direction[1];
sum_b = direction[2];
direction[0] = sum_r*sum_rr + sum_g*sum_rg + sum_b*sum_rb;
direction[1] = sum_r*sum_rg + sum_g*sum_gg + sum_b*sum_gb;
direction[2] = sum_r*sum_rb + sum_g*sum_gb + sum_b*sum_bb;
/* 3rd iteration, use results from the 2nd guy */
sum_r = direction[0];
sum_g = direction[1];
sum_b = direction[2];
direction[0] = sum_r*sum_rr + sum_g*sum_rg + sum_b*sum_rb;
direction[1] = sum_r*sum_rg + sum_g*sum_gg + sum_b*sum_gb;
direction[2] = sum_r*sum_rb + sum_g*sum_gb + sum_b*sum_bb;
#else
/* use my standard deviation method
(very robust, a tiny bit slower and less accurate) */
direction[0] = sqrt( sum_rr );
direction[1] = sqrt( sum_gg );
direction[2] = sqrt( sum_bb );
/* which has a greater component */
if( sum_gg > sum_rr )
{
/* green has greater component, so base the other signs off of green */
if( sum_rg < 0.0f )
{
direction[0] = -direction[0];
}
if( sum_gb < 0.0f )
{
direction[2] = -direction[2];
}
} else
{
/* red has a greater component */
if( sum_rg < 0.0f )
{
direction[1] = -direction[1];
}
if( sum_rb < 0.0f )
{
direction[2] = -direction[2];
}
}
#endif
}
void LSE_master_colors_max_min(
int *cmax, int *cmin,
int channels,
const unsigned char *const uncompressed )
{
int i, j;
/* the master colors */
int c0[3], c1[3];
/* used for fitting the line */
float sum_x[] = { 0.0f, 0.0f, 0.0f };
float sum_x2[] = { 0.0f, 0.0f, 0.0f };
float dot_max = 1.0f, dot_min = -1.0f;
float vec_len2 = 0.0f;
float dot;
/* error check */
if( (channels < 3) || (channels > 4) )
{
return;
}
compute_color_line_STDEV( uncompressed, channels, sum_x, sum_x2 );
vec_len2 = 1.0f / ( 0.00001f +
sum_x2[0]*sum_x2[0] + sum_x2[1]*sum_x2[1] + sum_x2[2]*sum_x2[2] );
/* finding the max and min vector values */
dot_max =
(
sum_x2[0] * uncompressed[0] +
sum_x2[1] * uncompressed[1] +
sum_x2[2] * uncompressed[2]
);
dot_min = dot_max;
for( i = 1; i < 16; ++i )
{
dot =
(
sum_x2[0] * uncompressed[i*channels+0] +
sum_x2[1] * uncompressed[i*channels+1] +
sum_x2[2] * uncompressed[i*channels+2]
);
if( dot < dot_min )
{
dot_min = dot;
} else if( dot > dot_max )
{
dot_max = dot;
}
}
/* and the offset (from the average location) */
dot = sum_x2[0]*sum_x[0] + sum_x2[1]*sum_x[1] + sum_x2[2]*sum_x[2];
dot_min -= dot;
dot_max -= dot;
/* post multiply by the scaling factor */
dot_min *= vec_len2;
dot_max *= vec_len2;
/* OK, build the master colors */
for( i = 0; i < 3; ++i )
{
/* color 0 */
c0[i] = (int)(0.5f + sum_x[i] + dot_max * sum_x2[i]);
if( c0[i] < 0 )
{
c0[i] = 0;
} else if( c0[i] > 255 )
{
c0[i] = 255;
}
/* color 1 */
c1[i] = (int)(0.5f + sum_x[i] + dot_min * sum_x2[i]);
if( c1[i] < 0 )
{
c1[i] = 0;
} else if( c1[i] > 255 )
{
c1[i] = 255;
}
}
/* down_sample (with rounding?) */
i = rgb_to_565( c0[0], c0[1], c0[2] );
j = rgb_to_565( c1[0], c1[1], c1[2] );
if( i > j )
{
*cmax = i;
*cmin = j;
} else
{
*cmax = j;
*cmin = i;
}
}
void
compress_DDS_color_block
(
int channels,
const unsigned char *const uncompressed,
unsigned char compressed[8]
)
{
/* variables */
int i;
int next_bit;
int enc_c0, enc_c1;
int c0[4], c1[4];
float color_line[] = { 0.0f, 0.0f, 0.0f, 0.0f };
float vec_len2 = 0.0f, dot_offset = 0.0f;
/* stupid order */
int swizzle4[] = { 0, 2, 3, 1 };
/* get the master colors */
LSE_master_colors_max_min( &enc_c0, &enc_c1, channels, uncompressed );
/* store the 565 color 0 and color 1 */
compressed[0] = (enc_c0 >> 0) & 255;
compressed[1] = (enc_c0 >> 8) & 255;
compressed[2] = (enc_c1 >> 0) & 255;
compressed[3] = (enc_c1 >> 8) & 255;
/* zero out the compressed data */
compressed[4] = 0;
compressed[5] = 0;
compressed[6] = 0;
compressed[7] = 0;
/* reconstitute the master color vectors */
rgb_888_from_565( enc_c0, &c0[0], &c0[1], &c0[2] );
rgb_888_from_565( enc_c1, &c1[0], &c1[1], &c1[2] );
/* the new vector */
vec_len2 = 0.0f;
for( i = 0; i < 3; ++i )
{
color_line[i] = (float)(c1[i] - c0[i]);
vec_len2 += color_line[i] * color_line[i];
}
if( vec_len2 > 0.0f )
{
vec_len2 = 1.0f / vec_len2;
}
/* pre-proform the scaling */
color_line[0] *= vec_len2;
color_line[1] *= vec_len2;
color_line[2] *= vec_len2;
/* compute the offset (constant) portion of the dot product */
dot_offset = color_line[0]*c0[0] + color_line[1]*c0[1] + color_line[2]*c0[2];
/* store the rest of the bits */
next_bit = 8*4;
for( i = 0; i < 16; ++i )
{
/* find the dot product of this color, to place it on the line
(should be [-1,1]) */
int next_value = 0;
float dot_product =
color_line[0] * uncompressed[i*channels+0] +
color_line[1] * uncompressed[i*channels+1] +
color_line[2] * uncompressed[i*channels+2] -
dot_offset;
/* map to [0,3] */
next_value = (int)( dot_product * 3.0f + 0.5f );
if( next_value > 3 )
{
next_value = 3;
} else if( next_value < 0 )
{
next_value = 0;
}
/* OK, store this value */
compressed[next_bit >> 3] |= swizzle4[ next_value ] << (next_bit & 7);
next_bit += 2;
}
/* done compressing to DXT1 */
}
void
compress_DDS_alpha_block
(
const unsigned char *const uncompressed,
unsigned char compressed[8]
)
{
/* variables */
int i;
int next_bit;
int a0, a1;
float scale_me;
/* stupid order */
int swizzle8[] = { 1, 7, 6, 5, 4, 3, 2, 0 };
/* get the alpha limits (a0 > a1) */
a0 = a1 = uncompressed[3];
for( i = 4+3; i < 16*4; i += 4 )
{
if( uncompressed[i] > a0 )
{
a0 = uncompressed[i];
} else if( uncompressed[i] < a1 )
{
a1 = uncompressed[i];
}
}
/* store those limits, and zero the rest of the compressed dataset */
compressed[0] = a0;
compressed[1] = a1;
/* zero out the compressed data */
compressed[2] = 0;
compressed[3] = 0;
compressed[4] = 0;
compressed[5] = 0;
compressed[6] = 0;
compressed[7] = 0;
/* store the all of the alpha values */
next_bit = 8*2;
scale_me = 7.9999f / (a0 - a1);
for( i = 3; i < 16*4; i += 4 )
{
/* convert this alpha value to a 3 bit number */
int svalue;
int value = (int)((uncompressed[i] - a1) * scale_me);
svalue = swizzle8[ value&7 ];
/* OK, store this value, start with the 1st byte */
compressed[next_bit >> 3] |= svalue << (next_bit & 7);
if( (next_bit & 7) > 5 )
{
/* spans 2 bytes, fill in the start of the 2nd byte */
compressed[1 + (next_bit >> 3)] |= svalue >> (8 - (next_bit & 7) );
}
next_bit += 3;
}
/* done compressing to DXT1 */
}
================================================
FILE: src/image_DXT.h
================================================
/*
Jonathan Dummer
2007-07-31-10.32
simple DXT compression / decompression code
public domain
*/
#ifndef HEADER_IMAGE_DXT
#define HEADER_IMAGE_DXT
/**
Converts an image from an array of unsigned chars (RGB or RGBA) to
DXT1 or DXT5, then saves the converted image to disk.
\return 0 if failed, otherwise returns 1
**/
int
save_image_as_DDS
(
const char *filename,
int width, int height, int channels,
const unsigned char *const data
);
/**
take an image and convert it to DXT1 (no alpha)
**/
unsigned char*
convert_image_to_DXT1
(
const unsigned char *const uncompressed,
int width, int height, int channels,
int *out_size
);
/**
take an image and convert it to DXT5 (with alpha)
**/
unsigned char*
convert_image_to_DXT5
(
const unsigned char *const uncompressed,
int width, int height, int channels,
int *out_size
);
/** A bunch of DirectDraw Surface structures and flags **/
typedef struct
{
unsigned int dwMagic;
unsigned int dwSize;
unsigned int dwFlags;
unsigned int dwHeight;
unsigned int dwWidth;
unsigned int dwPitchOrLinearSize;
unsigned int dwDepth;
unsigned int dwMipMapCount;
unsigned int dwReserved1[ 11 ];
/* DDPIXELFORMAT */
struct
{
unsigned int dwSize;
unsigned int dwFlags;
unsigned int dwFourCC;
unsigned int dwRGBBitCount;
unsigned int dwRBitMask;
unsigned int dwGBitMask;
unsigned int dwBBitMask;
unsigned int dwAlphaBitMask;
}
sPixelFormat;
/* DDCAPS2 */
struct
{
unsigned int dwCaps1;
unsigned int dwCaps2;
unsigned int dwDDSX;
unsigned int dwReserved;
}
sCaps;
unsigned int dwReserved2;
}
DDS_header ;
/* the following constants were copied directly off the MSDN website */
/* The dwFlags member of the original DDSURFACEDESC2 structure
can be set to one or more of the following values. */
#define DDSD_CAPS 0x00000001
#define DDSD_HEIGHT 0x00000002
#define DDSD_WIDTH 0x00000004
#define DDSD_PITCH 0x00000008
#define DDSD_PIXELFORMAT 0x00001000
#define DDSD_MIPMAPCOUNT 0x00020000
#define DDSD_LINEARSIZE 0x00080000
#define DDSD_DEPTH 0x00800000
/* DirectDraw Pixel Format */
#define DDPF_ALPHAPIXELS 0x00000001
#define DDPF_FOURCC 0x00000004
#define DDPF_RGB 0x00000040
/* The dwCaps1 member of the DDSCAPS2 structure can be
set to one or more of the following values. */
#define DDSCAPS_COMPLEX 0x00000008
#define DDSCAPS_TEXTURE 0x00001000
#define DDSCAPS_MIPMAP 0x00400000
/* The dwCaps2 member of the DDSCAPS2 structure can be
set to one or more of the following values. */
#define DDSCAPS2_CUBEMAP 0x00000200
#define DDSCAPS2_CUBEMAP_POSITIVEX 0x00000400
#define DDSCAPS2_CUBEMAP_NEGATIVEX 0x00000800
#define DDSCAPS2_CUBEMAP_POSITIVEY 0x00001000
#define DDSCAPS2_CUBEMAP_NEGATIVEY 0x00002000
#define DDSCAPS2_CUBEMAP_POSITIVEZ 0x00004000
#define DDSCAPS2_CUBEMAP_NEGATIVEZ 0x00008000
#define DDSCAPS2_VOLUME 0x00200000
#endif /* HEADER_IMAGE_DXT */
================================================
FILE: src/image_helper.c
================================================
/*
Jonathan Dummer
image helper functions
MIT license
*/
#include "image_helper.h"
#include <stdlib.h>
#include <math.h>
/* Upscaling the image uses simple bilinear interpolation */
int
up_scale_image
(
const unsigned char* const orig,
int width, int height, int channels,
unsigned char* resampled,
int resampled_width, int resampled_height
)
{
float dx, dy;
int x, y, c;
/* error(s) check */
if ( (width < 1) || (height < 1) ||
(resampled_width < 2) || (resampled_height < 2) ||
(channels < 1) ||
(NULL == orig) || (NULL == resampled) )
{
/* signify badness */
return 0;
}
/*
for each given pixel in the new map, find the exact location
from the original map which would contribute to this guy
*/
dx = (width - 1.0f) / (resampled_width - 1.0f);
dy = (height - 1.0f) / (resampled_height - 1.0f);
for ( y = 0; y < resampled_height; ++y )
{
/* find the base y index and fractional offset from that */
float sampley = y * dy;
int inty = (int)sampley;
/* if( inty < 0 ) { inty = 0; } else */
if( inty > height - 2 ) { inty = height - 2; }
sampley -= inty;
for ( x = 0; x < resampled_width; ++x )
{
float samplex = x * dx;
int intx = (int)samplex;
int base_index;
/* find the base x index and fractional offset from that */
/* if( intx < 0 ) { intx = 0; } else */
if( intx > width - 2 ) { intx = width - 2; }
samplex -= intx;
/* base index into the original image */
base_index = (inty * width + intx) * channels;
for ( c = 0; c < channels; ++c )
{
/* do the sampling */
float value = 0.5f;
value += orig[base_index]
*(1.0f-samplex)*(1.0f-sampley);
value += orig[base_index+channels]
*(samplex)*(1.0f-sampley);
value += orig[base_index+width*channels]
*(1.0f-samplex)*(sampley);
value += orig[base_index+width*channels+channels]
*(samplex)*(sampley);
/* move to the next channel */
++base_index;
/* save the new value */
resampled[y*resampled_width*channels+x*channels+c] =
(unsigned char)(value);
}
}
}
/* done */
return 1;
}
int
mipmap_image
(
const unsigned char* const orig,
int width, int height, int channels,
unsigned char* resampled,
int block_size_x, int block_size_y
)
{
int mip_width, mip_height;
int i, j, c;
/* error check */
if( (width < 1) || (height < 1) ||
(channels < 1) || (orig == NULL) ||
(resampled == NULL) ||
(block_size_x < 1) || (block_size_y < 1) )
{
/* nothing to do */
return 0;
}
mip_width = width / block_size_x;
mip_height = height / block_size_y;
if( mip_width < 1 )
{
mip_width = 1;
}
if( mip_height < 1 )
{
mip_height = 1;
}
for( j = 0; j < mip_height; ++j )
{
for( i = 0; i < mip_width; ++i )
{
for( c = 0; c < channels; ++c )
{
const int index = (j*block_size_y)*width*channels + (i*block_size_x)*channels + c;
int sum_value;
int u,v;
int u_block = block_size_x;
int v_block = block_size_y;
int block_area;
/* do a bit of checking so we don't over-run the boundaries
(necessary for non-square textures!) */
if( block_size_x * (i+1) > width )
{
u_block = width - i*block_size_y;
}
if( block_size_y * (j+1) > height )
{
v_block = height - j*block_size_y;
}
block_area = u_block*v_block;
/* for this pixel, see what the average
of all the values in the block are.
note: start the sum at the rounding value, not at 0 */
sum_value = block_area >> 1;
for( v = 0; v < v_block; ++v )
for( u = 0; u < u_block; ++u )
{
sum_value += orig[index + v*width*channels + u*channels];
}
resampled[j*mip_width*channels + i*channels + c] = sum_value / block_area;
}
}
}
return 1;
}
int
scale_image_RGB_to_NTSC_safe
(
unsigned char* orig,
int width, int height, int channels
)
{
const float scale_lo = 16.0f - 0.499f;
const float scale_hi = 235.0f + 0.499f;
int i, j;
int nc = channels;
unsigned char scale_LUT[256];
/* error check */
if( (width < 1) || (height < 1) ||
(channels < 1) || (orig == NULL) )
{
/* nothing to do */
return 0;
}
/* set up the scaling Look Up Table */
for( i = 0; i < 256; ++i )
{
scale_LUT[i] = (unsigned char)((scale_hi - scale_lo) * i / 255.0f + scale_lo);
}
/* for channels = 2 or 4, ignore the alpha component */
nc -= 1 - (channels & 1);
/* OK, go through the image and scale any non-alpha components */
for( i = 0; i < width*height*channels; i += channels )
{
for( j = 0; j < nc; ++j )
{
orig[i+j] = scale_LUT[orig[i+j]];
}
}
return 1;
}
unsigned char clamp_byte( int x ) { return ( (x) < 0 ? (0) : ( (x) > 255 ? 255 : (x) ) ); }
/*
This function takes the RGB components of the image
and converts them into YCoCg. 3 components will be
re-ordered to CoYCg (for optimum DXT1 compression),
while 4 components will be ordered CoCgAY (for DXT5
compression).
*/
int
convert_RGB_to_YCoCg
(
unsigned char* orig,
int width, int height, int channels
)
{
int i;
/* error check */
if( (width < 1) || (height < 1) ||
(channels < 3) || (channels > 4) ||
(orig == NULL) )
{
/* nothing to do */
return -1;
}
/* do the conversion */
if( channels == 3 )
{
for( i = 0; i < width*height*3; i += 3 )
{
int r = orig[i+0];
int g = (orig[i+1] + 1) >> 1;
int b = orig[i+2];
int tmp = (2 + r + b) >> 2;
/* Co */
orig[i+0] = clamp_byte( 128 + ((r - b + 1) >> 1) );
/* Y */
orig[i+1] = clamp_byte( g + tmp );
/* Cg */
orig[i+2] = clamp_byte( 128 + g - tmp );
}
} else
{
for( i = 0; i < width*height*4; i += 4 )
{
int r = orig[i+0];
int g = (orig[i+1] + 1) >> 1;
int b = orig[i+2];
unsigned char a = orig[i+3];
int tmp = (2 + r + b) >> 2;
/* Co */
orig[i+0] = clamp_byte( 128 + ((r - b + 1) >> 1) );
/* Cg */
orig[i+1] = clamp_byte( 128 + g - tmp );
/* Alpha */
orig[i+2] = a;
/* Y */
orig[i+3] = clamp_byte( g + tmp );
}
}
/* done */
return 0;
}
/*
This function takes the YCoCg components of the image
and converts them into RGB. See above.
*/
int
convert_YCoCg_to_RGB
(
unsigned char* orig,
int width, int height, int channels
)
{
int i;
/* error check */
if( (width < 1) || (height < 1) ||
(channels < 3) || (channels > 4) ||
(orig == NULL) )
{
/* nothing to do */
return -1;
}
/* do the conversion */
if( channels == 3 )
{
for( i = 0; i < width*height*3; i += 3 )
{
int co = orig[i+0] - 128;
int y = orig[i+1];
int cg = orig[i+2] - 128;
/* R */
orig[i+0] = clamp_byte( y + co - cg );
/* G */
orig[i+1] = clamp_byte( y + cg );
/* B */
orig[i+2] = clamp_byte( y - co - cg );
}
} else
{
for( i = 0; i < width*height*4; i += 4 )
{
int co = orig[i+0] - 128;
int cg = orig[i+1] - 128;
unsigned char a = orig[i+2];
int y = orig[i+3];
/* R */
orig[i+0] = clamp_byte( y + co - cg );
/* G */
orig[i+1] = clamp_byte( y + cg );
/* B */
orig[i+2] = clamp_byte( y - co - cg );
/* A */
orig[i+3] = a;
}
}
/* done */
return 0;
}
float
find_max_RGBE
(
unsigned char *image,
int width, int height
)
{
float max_val = 0.0f;
unsigned char *img = image;
int i, j;
for( i = width * height; i > 0; --i )
{
/* float scale = powf( 2.0f, img[3] - 128.0f ) / 255.0f; */
float scale = ldexp( 1.0f / 255.0f, (int)(img[3]) - 128 );
for( j = 0; j < 3; ++j )
{
if( img[j] * scale > max_val )
{
max_val = img[j] * scale;
}
}
/* next pixel */
img += 4;
}
return max_val;
}
int
RGBE_to_RGBdivA
(
unsigned char *image,
int width, int height,
int rescale_to_max
)
{
/* local variables */
int i, iv;
unsigned char *img = image;
float scale = 1.0f;
/* error check */
if( (!image) || (width < 1) || (height < 1) )
{
return 0;
}
/* convert (note: no negative numbers, but 0.0 is possible) */
if( rescale_to_max )
{
scale = 255.0f / find_max_RGBE( image, width, height );
}
for( i = width * height; i > 0; --i )
{
/* decode this pixel, and find the max */
float r,g,b,e, m;
/* e = scale * powf( 2.0f, img[3] - 128.0f ) / 255.0f; */
e = scale * ldexp( 1.0f / 255.0f, (int)(img[3]) - 128 );
r = e * img[0];
g = e * img[1];
b = e * img[2];
m = (r > g) ? r : g;
m = (b > m) ? b : m;
/* and encode it into RGBdivA */
iv = (m != 0.0f) ? (int)(255.0f / m) : 1.0f;
iv = (iv < 1) ? 1 : iv;
img[3] = (iv > 255) ? 255 : iv;
iv = (int)(img[3] * r + 0.5f);
img[0] = (iv > 255) ? 255 : iv;
iv = (int)(img[3] * g + 0.5f);
img[1] = (iv > 255) ? 255 : iv;
iv = (int)(img[3] * b + 0.5f);
img[2] = (iv > 255) ? 255 : iv;
/* and on to the next pixel */
img += 4;
}
return 1;
}
int
RGBE_to_RGBdivA2
(
unsigned char *image,
int width, int height,
int rescale_to_max
)
{
/* local variables */
int i, iv;
unsigned char *img = image;
float scale = 1.0f;
/* error check */
if( (!image) || (width < 1) || (height < 1) )
{
return 0;
}
/* convert (note: no negative numbers, but 0.0 is possible) */
if( rescale_to_max )
{
scale = 255.0f * 255.0f / find_max_RGBE( image, width, height );
}
for( i = width * height; i > 0; --i )
{
/* decode this pixel, and find the max */
float r,g,b,e, m;
/* e = scale * powf( 2.0f, img[3] - 128.0f ) / 255.0f; */
e = scale * ldexp( 1.0f / 255.0f, (int)(img[3]) - 128 );
r = e * img[0];
g = e * img[1];
b = e * img[2];
m = (r > g) ? r : g;
m = (b > m) ? b : m;
/* and encode it into RGBdivA */
iv = (m != 0.0f) ? (int)sqrtf( 255.0f * 255.0f / m ) : 1.0f;
iv = (iv < 1) ? 1 : iv;
img[3] = (iv > 255) ? 255 : iv;
iv = (int)(img[3] * img[3] * r / 255.0f + 0.5f);
img[0] = (iv > 255) ? 255 : iv;
iv = (int)(img[3] * img[3] * g / 255.0f + 0.5f);
img[1] = (iv > 255) ? 255 : iv;
iv = (int)(img[3] * img[3] * b / 255.0f + 0.5f);
img[2] = (iv > 255) ? 255 : iv;
/* and on to the next pixel */
img += 4;
}
return 1;
}
================================================
FILE: src/image_helper.h
================================================
/*
Jonathan Dummer
Image helper functions
MIT license
*/
#ifndef HEADER_IMAGE_HELPER
#define HEADER_IMAGE_HELPER
#ifdef __cplusplus
extern "C" {
#endif
/**
This function upscales an image.
Not to be used to create MIPmaps,
but to make it square,
or to make it a power-of-two sized.
**/
int
up_scale_image
(
const unsigned char* const orig,
int width, int height, int channels,
unsigned char* resampled,
int resampled_width, int resampled_height
);
/**
This function downscales an image.
Used for creating MIPmaps,
the incoming image should be a
power-of-two sized.
**/
int
mipmap_image
(
const unsigned char* const orig,
int width, int height, int channels,
unsigned char* resampled,
int block_size_x, int block_size_y
);
/**
This function takes the RGB components of the image
and scales each channel from [0,255] to [16,235].
This makes the colors "Safe" for display on NTSC
displays. Note that this is _NOT_ a good idea for
loading images like normal- or height-maps!
**/
int
scale_image_RGB_to_NTSC_safe
(
unsigned char* orig,
int width, int height, int channels
);
/**
This function takes the RGB components of the image
and converts them into YCoCg. 3 components will be
re-ordered to CoYCg (for optimum DXT1 compression),
while 4 components will be ordered CoCgAY (for DXT5
compression).
**/
int
convert_RGB_to_YCoCg
(
unsigned char* orig,
int width, int height, int channels
);
/**
This function takes the YCoCg components of the image
and converts them into RGB. See above.
**/
int
convert_YCoCg_to_RGB
(
unsigned char* orig,
int width, int height, int channels
);
/**
Converts an HDR image from an array
of unsigned chars (RGBE) to RGBdivA
\return 0 if failed, otherwise returns 1
**/
int
RGBE_to_RGBdivA
(
unsigned char *image,
int width, int height,
int rescale_to_max
);
/**
Converts an HDR image from an array
of unsigned chars (RGBE) to RGBdivA2
\return 0 if failed, otherwise returns 1
**/
int
RGBE_to_RGBdivA2
(
unsigned char *image,
int width, int height,
int rescale_to_max
);
#ifdef __cplusplus
}
#endif
#endif /* HEADER_IMAGE_HELPER */
================================================
FILE: src/stb_image_aug.c
================================================
/* stbi-1.16 - public domain JPEG/PNG reader - http://nothings.org/stb_image.c
when you control the images you're loading
QUICK NOTES:
Primarily of interest to game developers and other people who can
avoid problematic images and only need the trivial interface
JPEG baseline (no JPEG progressive, no oddball channel decimations)
PNG non-interlaced
BMP non-1bpp, non-RLE
TGA (not sure what subset, if a subset)
PSD (composited view only, no extra channels)
HDR (radiance rgbE format)
writes BMP,TGA (define STBI_NO_WRITE to remove code)
decoded from memory or through stdio FILE (define STBI_NO_STDIO to remove code)
supports installable dequantizing-IDCT, YCbCr-to-RGB conversion (define STBI_SIMD)
TODO:
stbi_info_*
history:
1.16 major bugfix - convert_format converted one too many pixels
1.15 initialize some fields for thread safety
1.14 fix threadsafe conversion bug; header-file-only version (#define STBI_HEADER_FILE_ONLY before including)
1.13 threadsafe
1.12 const qualifiers in the API
1.11 Support installable IDCT, colorspace conversion routines
1.10 Fixes for 64-bit (don't use "unsigned long")
optimized upsampling by Fabian "ryg" Giesen
1.09 Fix format-conversion for PSD code (bad global variables!)
1.08 Thatcher Ulrich's PSD code integrated by Nicolas Schulz
1.07 attempt to fix C++ warning/errors again
1.06 attempt to fix C++ warning/errors again
1.05 fix TGA loading to return correct *comp and use good luminance calc
1.04 default float alpha is 1, not 255; use 'void *' for stbi_image_free
1.03 bugfixes to STBI_NO_STDIO, STBI_NO_HDR
1.02 support for (subset of) HDR files, float interface for preferred access to them
1.01 fix bug: possible bug in handling right-side up bmps... not sure
fix bug: the stbi_bmp_load() and stbi_tga_load() functions didn't work at all
1.00 interface to zlib that skips zlib header
0.99 correct handling of alpha in palette
0.98 TGA loader by lonesock; dynamically add loaders (untested)
0.97 jpeg errors on too large a file; also catch another malloc failure
0.96 fix detection of invalid v value - particleman@mollyrocket forum
0.95 during header scan, seek to markers in case of padding
0.94 STBI_NO_STDIO to disable stdio usage; rename all #defines the same
0.93 handle jpegtran output; verbose errors
0.92 read 4,8,16,24,32-bit BMP files of several formats
0.91 output 24-bit Windows 3.0 BMP files
0.90 fix a few more warnings; bump version number to approach 1.0
0.61 bugfixes due to Marc LeBlanc, Christopher Lloyd
0.60 fix compiling as c++
0.59 fix warnings: merge Dave Moore's -Wall fixes
0.58 fix bug: zlib uncompressed mode len/nlen was wrong endian
0.57 fix bug: jpg last huffman symbol before marker was >9 bits but less
than 16 available
0.56 fix bug: zlib uncompressed mode len vs. nlen
0.55 fix bug: restart_interval not initialized to 0
0.54 allow NULL for 'int *comp'
0.53 fix bug in png 3->4; speedup png decoding
0.52 png handles req_comp=3,4 directly; minor cleanup; jpeg comments
0.51 obey req_comp requests, 1-component jpegs return as 1-component,
on 'test' only check type, not whether we support this variant
*/
#include "stb_image_aug.h"
#ifndef STBI_NO_HDR
#include <math.h> // ldexp
#include <string.h> // strcmp
#endif
#ifndef STBI_NO_STDIO
#include <stdio.h>
#endif
#include <stdlib.h>
#include <memory.h>
#include <assert.h>
#include <stdarg.h>
#ifndef _MSC_VER
#ifdef __cplusplus
#define __forceinline inline
#else
#define __forceinline
#endif
#endif
// implementation:
typedef unsigned char uint8;
typedef unsigned short uint16;
typedef signed short int16;
typedef unsigned int uint32;
typedef signed int int32;
typedef unsigned int uint;
// should produce compiler error if size is wrong
typedef unsigned char validate_uint32[sizeof(uint32)==4];
#if defined(STBI_NO_STDIO) && !defined(STBI_NO_WRITE)
#define STBI_NO_WRITE
#endif
#ifndef STBI_NO_DDS
#include "stbi_DDS_aug.h"
#endif
// I (JLD) want full messages for SOIL
#define STBI_FAILURE_USERMSG 1
//////////////////////////////////////////////////////////////////////////////
//
// Generic API that works on all image types
//
// this is not threadsafe
static char *failure_reason;
char *stbi_failure_reason(void)
{
return failure_reason;
}
static int e(char *str)
{
failure_reason = str;
return 0;
}
#ifdef STBI_NO_FAILURE_STRINGS
#define e(x,y) 0
#elif defined(STBI_FAILURE_USERMSG)
#define e(x,y) e(y)
#else
#define e(x,y) e(x)
#endif
#define epf(x,y) ((float *) (e(x,y)?NULL:NULL))
#define epuc(x,y) ((unsigned char *) (e(x,y)?NULL:NULL))
void stbi_image_free(void *retval_from_stbi_load)
{
free(retval_from_stbi_load);
}
#define MAX_LOADERS 32
stbi_loader *loaders[MAX_LOADERS];
static int max_loaders = 0;
int stbi_register_loader(stbi_loader *loader)
{
int i;
for (i=0; i < MAX_LOADERS; ++i) {
// already present?
if (loaders[i] == loader)
return 1;
// end of the list?
if (loaders[i] == NULL) {
loaders[i] = loader;
max_loaders = i+1;
return 1;
}
}
// no room for it
return 0;
}
#ifndef STBI_NO_HDR
static float *ldr_to_hdr(stbi_uc *data, int x, int y, int comp);
static stbi_uc *hdr_to_ldr(float *data, int x, int y, int comp);
#endif
#ifndef STBI_NO_STDIO
unsigned char *stbi_load(char const *filename, int *x, int *y, int *comp, int req_comp)
{
FILE *f = fopen(filename, "rb");
unsigned char *result;
if (!f) return epuc("can't fopen", "Unable to open file");
result = stbi_load_from_file(f,x,y,comp,req_comp);
fclose(f);
return result;
}
unsigned char *stbi_load_from_file(FILE *f, int *x, int *y, int *comp, int req_comp)
{
int i;
if (stbi_jpeg_test_file(f))
return stbi_jpeg_load_from_file(f,x,y,comp,req_comp);
if (stbi_png_test_file(f))
return stbi_png_load_from_file(f,x,y,comp,req_comp);
if (stbi_bmp_test_file(f))
return stbi_bmp_load_from_file(f,x,y,comp,req_comp);
if (stbi_psd_test_file(f))
return stbi_psd_load_from_file(f,x,y,comp,req_comp);
#ifndef STBI_NO_DDS
if (stbi_dds_test_file(f))
return stbi_dds_load_from_file(f,x,y,comp,req_comp);
#endif
#ifndef STBI_NO_HDR
if (stbi_hdr_test_file(f)) {
float *hdr = stbi_hdr_load_from_file(f, x,y,comp,req_comp);
return hdr_to_ldr(hdr, *x, *y, req_comp ? req_comp : *comp);
}
#endif
for (i=0; i < max_loaders; ++i)
if (loaders[i]->test_file(f))
return loaders[i]->load_from_file(f,x,y,comp,req_comp);
// test tga last because it's a crappy test!
if (stbi_tga_test_file(f))
return stbi_tga_load_from_file(f,x,y,comp,req_comp);
return epuc("unknown image type", "Image not of any known type, or corrupt");
}
#endif
unsigned char *stbi_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp)
{
int i;
if (stbi_jpeg_test_memory(buffer,len))
return stbi_jpeg_load_from_memory(buffer,len,x,y,comp,req_comp);
if (stbi_png_test_memory(buffer,len))
return stbi_png_load_from_memory(buffer,len,x,y,comp,req_comp);
if (stbi_bmp_test_memory(buffer,len))
return stbi_bmp_load_from_memory(buffer,len,x,y,comp,req_comp);
if (stbi_psd_test_memory(buffer,len))
return stbi_psd_load_from_memory(buffer,len,x,y,comp,req_comp);
#ifndef STBI_NO_DDS
if (stbi_dds_test_memory(buffer,len))
return stbi_dds_load_from_memory(buffer,len,x,y,comp,req_comp);
#endif
#ifndef STBI_NO_HDR
if (stbi_hdr_test_memory(buffer, len)) {
float *hdr = stbi_hdr_load_from_memory(buffer, len,x,y,comp,req_comp);
return hdr_to_ldr(hdr, *x, *y, req_comp ? req_comp : *comp);
}
#endif
for (i=0; i < max_loaders; ++i)
if (loaders[i]->test_memory(buffer,len))
return loaders[i]->load_from_memory(buffer,len,x,y,comp,req_comp);
// test tga last because it's a crappy test!
if (stbi_tga_test_memory(buffer,len))
return stbi_tga_load_from_memory(buffer,len,x,y,comp,req_comp);
return epuc("unknown image type", "Image not of any known type, or corrupt");
}
#ifndef STBI_NO_HDR
#ifndef STBI_NO_STDIO
float *stbi_loadf(char const *filename, int *x, int *y, int *comp, int req_comp)
{
FILE *f = fopen(filename, "rb");
float *result;
if (!f) return epf("can't fopen", "Unable to open file");
result = stbi_loadf_from_file(f,x,y,comp,req_comp);
fclose(f);
return result;
}
float *stbi_loadf_from_file(FILE *f, int *x, int *y, int *comp, int req_comp)
{
unsigned char *data;
#ifndef STBI_NO_HDR
if (stbi_hdr_test_file(f))
return stbi_hdr_load_from_file(f,x,y,comp,req_comp);
#endif
data = stbi_load_from_file(f, x, y, comp, req_comp);
if (data)
return ldr_to_hdr(data, *x, *y, req_comp ? req_comp : *comp);
return epf("unknown image type", "Image not of any known type, or corrupt");
}
#endif
float *stbi_loadf_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp)
{
stbi_uc *data;
#ifndef STBI_NO_HDR
if (stbi_hdr_test_memory(buffer, len))
return stbi_hdr_load_from_memory(buffer, len,x,y,comp,req_comp);
#endif
data = stbi_load_from_memory(buffer, len, x, y, comp, req_comp);
if (data)
return ldr_to_hdr(data, *x, *y, req_comp ? req_comp : *comp);
return epf("unknown image type", "Image not of any known type, or corrupt");
}
#endif
// these is-hdr-or-not is defined independent of whether STBI_NO_HDR is
// defined, for API simplicity; if STBI_NO_HDR is defined, it always
// reports false!
int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len)
{
#ifndef STBI_NO_HDR
return stbi_hdr_test_memory(buffer, len);
#else
return 0;
#endif
}
#ifndef STBI_NO_STDIO
extern int stbi_is_hdr (char const *filename)
{
FILE *f = fopen(filename, "rb");
int result=0;
if (f) {
result = stbi_is_hdr_from_file(f);
fclose(f);
}
return result;
}
extern int stbi_is_hdr_from_file(FILE *f)
{
#ifndef STBI_NO_HDR
return stbi_hdr_test_file(f);
#else
return 0;
#endif
}
#endif
// @TODO: get image dimensions & components without fully decoding
#ifndef STBI_NO_STDIO
extern int stbi_info (char const *filename, int *x, int *y, int *comp);
extern int stbi_info_from_file (FILE *f, int *x, int *y, int *comp);
#endif
extern int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp);
#ifndef STBI_NO_HDR
static float h2l_gamma_i=1.0f/2.2f, h2l_scale_i=1.0f;
static float l2h_gamma=2.2f, l2h_scale=1.0f;
void stbi_hdr_to_ldr_gamma(float gamma) { h2l_gamma_i = 1/gamma; }
void stbi_hdr_to_ldr_scale(float scale) { h2l_scale_i = 1/scale; }
void stbi_ldr_to_hdr_gamma(float gamma) { l2h_gamma = gamma; }
void stbi_ldr_to_hdr_scale(float scale) { l2h_scale = scale; }
#endif
//////////////////////////////////////////////////////////////////////////////
//
// Common code used by all image loaders
//
enum
{
SCAN_load=0,
SCAN_type,
SCAN_header,
};
typedef struct
{
uint32 img_x, img_y;
int img_n, img_out_n;
#ifndef STBI_NO_STDIO
FILE *img_file;
#endif
uint8 *img_buffer, *img_buffer_end;
} stbi;
#ifndef STBI_NO_STDIO
static void start_file(stbi *s, FILE *f)
{
s->img_file = f;
}
#endif
static void start_mem(stbi *s, uint8 const *buffer, int len)
{
#ifndef STBI_NO_STDIO
s->img_file = NULL;
#endif
s->img_buffer = (uint8 *) buffer;
s->img_buffer_end = (uint8 *) buffer+len;
}
__forceinline static int get8(stbi *s)
{
#ifndef STBI_NO_STDIO
if (s->img_file) {
int c = fgetc(s->img_file);
return c == EOF ? 0 : c;
}
#endif
if (s->img_buffer < s->img_buffer_end)
return *s->img_buffer++;
return 0;
}
__forceinline static int at_eof(stbi *s)
{
#ifndef STBI_NO_STDIO
if (s->img_file)
return feof(s->img_file);
#endif
return s->img_buffer >= s->img_buffer_end;
}
__forceinline static uint8 get8u(stbi *s)
{
return (uint8) get8(s);
}
static void skip(stbi *s, int n)
{
#ifndef STBI_NO_STDIO
if (s->img_file)
fseek(s->img_file, n, SEEK_CUR);
else
#endif
s->img_buffer += n;
}
static int get16(stbi *s)
{
int z = get8(s);
return (z << 8) + get8(s);
}
static uint32 get32(stbi *s)
{
uint32 z = get16(s);
return (z << 16) + get16(s);
}
static int get16le(stbi *s)
{
int z = get8(s);
return z + (get8(s) << 8);
}
static uint32 get32le(stbi *s)
{
uint32 z = get16le(s);
return z + (get16le(s) << 16);
}
static void getn(stbi *s, stbi_uc *buffer, int n)
{
#ifndef STBI_NO_STDIO
if (s->img_file) {
fread(buffer, 1, n, s->img_file);
return;
}
#endif
memcpy(buffer, s->img_buffer, n);
s->img_buffer += n;
}
//////////////////////////////////////////////////////////////////////////////
//
// generic converter from built-in img_n to req_comp
// individual types do this automatically as much as possible (e.g. jpeg
// does all cases internally since it needs to colorspace convert anyway,
// and it never has alpha, so very few cases ). png can automatically
// interleave an alpha=255 channel, but falls back to this for other cases
//
// assume data buffer is malloced, so malloc a new one and free that one
// only failure mode is malloc failing
static uint8 compute_y(int r, int g, int b)
{
return (uint8) (((r*77) + (g*150) + (29*b)) >> 8);
}
static unsigned char *convert_format(unsigned char *data, int img_n, int req_comp, uint x, uint y)
{
int i,j;
unsigned char *good;
if (req_comp == img_n) return data;
assert(req_comp >= 1 && req_comp <= 4);
good = (unsigned char *) malloc(req_comp * x * y);
if (good == NULL) {
free(data);
return epuc("outofmem", "Out of memory");
}
for (j=0; j < (int) y; ++j) {
unsigned char *src = data + j * x * img_n ;
unsigned char *dest = good + j * x * req_comp;
#define COMBO(a,b) ((a)*8+(b))
#define CASE(a,b) case COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b)
// convert source image with img_n components to one with req_comp components;
// avoid switch per pixel, so use switch per scanline and massive macros
switch(COMBO(img_n, req_comp)) {
CASE(1,2) dest[0]=src[0], dest[1]=255; break;
CASE(1,3) dest[0]=dest[1]=dest[2]=src[0]; break;
CASE(1,4) dest[0]=dest[1]=dest[2]=src[0], dest[3]=255; break;
CASE(2,1) dest[0]=src[0]; break;
CASE(2,3) dest[0]=dest[1]=dest[2]=src[0]; break;
CASE(2,4) dest[0]=dest[1]=dest[2]=src[0], dest[3]=src[1]; break;
CASE(3,4) dest[0]=src[0],dest[1]=src[1],dest[2]=src[2],dest[3]=255; break;
CASE(3,1) dest[0]=compute_y(src[0],src[1],src[2]); break;
CASE(3,2) dest[0]=compute_y(src[0],src[1],src[2]), dest[1] = 255; break;
CASE(4,1) dest[0]=compute_y(src[0],src[1],src[2]); break;
CASE(4,2) dest[0]=compute_y(src[0],src[1],src[2]), dest[1] = src[3]; break;
CASE(4,3) dest[0]=src[0],dest[1]=src[1],dest[2]=src[2]; break;
default: assert(0);
}
#undef CASE
}
free(data);
return good;
}
#ifndef STBI_NO_HDR
static float *ldr_to_hdr(stbi_uc *data, int x, int y, int comp)
{
int i,k,n;
float *output = (float *) malloc(x * y * comp * sizeof(float));
if (output == NULL) { free(data); return epf("outofmem", "Out of memory"); }
// compute number of non-alpha components
if (comp & 1) n = comp; else n = comp-1;
for (i=0; i < x*y; ++i) {
for (k=0; k < n; ++k) {
output[i*comp + k] = (float) pow(data[i*comp+k]/255.0f, l2h_gamma) * l2h_scale;
}
if (k < comp) output[i*comp + k] = data[i*comp+k]/255.0f;
}
free(data);
return output;
}
#define float2int(x) ((int) (x))
static stbi_uc *hdr_to_ldr(float *data, int x, int y, int comp)
{
int i,k,n;
stbi_uc *output = (stbi_uc *) malloc(x * y * comp);
if (output == NULL) { free(data); return epuc("outofmem", "Out of memory"); }
// compute number of non-alpha components
if (comp & 1) n = comp; else n = comp-1;
for (i=0; i < x*y; ++i) {
for (k=0; k < n; ++k) {
float z = (float) pow(data[i*comp+k]*h2l_scale_i, h2l_gamma_i) * 255 + 0.5f;
if (z < 0) z = 0;
if (z > 255) z = 255;
output[i*comp + k] = float2int(z);
}
if (k < comp) {
float z = data[i*comp+k] * 255 + 0.5f;
if (z < 0) z = 0;
if (z > 255) z = 255;
output[i*comp + k] = float2int(z);
}
}
free(data);
return output;
}
#endif
//////////////////////////////////////////////////////////////////////////////
//
// "baseline" JPEG/JFIF decoder (not actually fully baseline implementation)
//
// simple implementation
// - channel subsampling of at most 2 in each dimension
// - doesn't support delayed output of y-dimension
// - simple interface (only one output format: 8-bit interleaved RGB)
// - doesn't try to recover corrupt jpegs
// - doesn't allow partial loading, loading multiple at once
// - still fast on x86 (copying globals into locals doesn't help x86)
// - allocates lots of intermediate memory (full size of all components)
// - non-interleaved case requires this anyway
// - allows good upsampling (see next)
// high-quality
// - upsampled channels are bilinearly interpolated, even across blocks
// - quality integer IDCT derived from IJG's 'slow'
// performance
// - fast huffman; reasonable integer IDCT
// - uses a lot of intermediate memory, could cache poorly
// - load http://nothings.org/remote/anemones.jpg 3 times on 2.8Ghz P4
// stb_jpeg: 1.34 seconds (MSVC6, default release build)
// stb_jpeg: 1.06 seconds (MSVC6, processor = Pentium Pro)
// IJL11.dll: 1.08 seconds (compiled by intel)
// IJG 1998: 0.98 seconds (MSVC6, makefile provided by IJG)
// IJG 1998: 0.95 seconds (MSVC6, makefile + proc=PPro)
// huffman decoding acceleration
#define FAST_BITS 9 // larger handles more cases; smaller stomps less cache
typedef struct
{
uint8 fast[1 << FAST_BITS];
// weirdly, repacking this into AoS is a 10% speed loss, instead of a win
uint16 code[256];
uint8 values[256];
uint8 size[257];
unsigned int maxcode[18];
int delta[17]; // old 'firstsymbol' - old 'firstcode'
} huffman;
typedef struct
{
#if STBI_SIMD
unsigned short dequant2[4][64];
#endif
stbi s;
huffman huff_dc[4];
huffman huff_ac[4];
uint8 dequant[4][64];
// sizes for components, interleaved MCUs
int img_h_max, img_v_max;
int img_mcu_x, img_mcu_y;
int img_mcu_w, img_mcu_h;
// definition of jpeg image component
struct
{
int id;
int h,v;
int tq;
int hd,ha;
int dc_pred;
int x,y,w2,h2;
uint8 *data;
void *raw_data;
uint8 *linebuf;
} img_comp[4];
uint32 code_buffer; // jpeg entropy-coded buffer
int code_bits; // number of valid bits
unsigned char marker; // marker seen while filling entropy buffer
int nomore; // flag if we saw a marker so must stop
int scan_n, order[4];
int restart_interval, todo;
} jpeg;
static int build_huffman(huffman *h, int *count)
{
int i,j,k=0,code;
// build size list for each symbol (from JPEG spec)
for (i=0; i < 16; ++i)
for (j=0; j < count[i]; ++j)
h->size[k++] = (uint8) (i+1);
h->size[k] = 0;
// compute actual symbols (from jpeg spec)
code = 0;
k = 0;
for(j=1; j <= 16; ++j) {
// compute delta to add to code to compute symbol id
h->delta[j] = k - code;
if (h->size[k] == j) {
while (h->size[k] == j)
h->code[k++] = (uint16) (code++);
if (code-1 >= (1 << j)) return e("bad code lengths","Corrupt JPEG");
}
// compute largest code + 1 for this size, preshifted as needed later
h->maxcode[j] = code << (16-j);
code <<= 1;
}
h->maxcode[j] = 0xffffffff;
// build non-spec acceleration table; 255 is flag for not-accelerated
memset(h->fast, 255, 1 << FAST_BITS);
for (i=0; i < k; ++i) {
int s = h->size[i];
if (s <= FAST_BITS) {
int c = h->code[i] << (FAST_BITS-s);
int m = 1 << (FAST_BITS-s);
for (j=0; j < m; ++j) {
h->fast[c+j] = (uint8) i;
}
}
}
return 1;
}
static void grow_buffer_unsafe(jpeg *j)
{
do {
int b = j->nomore ? 0 : get8(&j->s);
if (b == 0xff) {
int c = get8(&j->s);
if (c != 0) {
j->marker = (unsigned char) c;
j->nomore = 1;
return;
}
}
j->code_buffer = (j->code_buffer << 8) | b;
j->code_bits += 8;
} while (j->code_bits <= 24);
}
// (1 << n) - 1
static uint32 bmask[17]={0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535};
// decode a jpeg huffman value from the bitstream
__forceinline static int decode(jpeg *j, huffman *h)
{
unsigned int temp;
int c,k;
if (j->code_bits < 16) grow_buffer_unsafe(j);
// look at the top FAST_BITS and determine what symbol ID it is,
// if the code is <= FAST_BITS
c = (j->code_buffer >> (j->code_bits - FAST_BITS)) & ((1 << FAST_BITS)-1);
k = h->fast[c];
if (k < 255) {
if (h->size[k] > j->code_bits)
return -1;
j->code_bits -= h->size[k];
return h->values[k];
}
// naive test is to shift the code_buffer down so k bits are
// valid, then test against maxcode. To speed this up, we've
// preshifted maxcode left so that it has (16-k) 0s at the
// end; in other words, regardless of the number of bits, it
// wants to be compared against something shifted to have 16;
// that way we don't need to shift inside the loop.
if (j->code_bits < 16)
temp = (j->code_buffer << (16 - j->code_bits)) & 0xffff;
else
temp = (j->code_buffer >> (j->code_bits - 16)) & 0xffff;
for (k=FAST_BITS+1 ; ; ++k)
if (temp < h->maxcode[k])
break;
if (k == 17) {
// error! code not found
j->code_bits -= 16;
return -1;
}
if (k > j->code_bits)
return -1;
// convert the huffman code to the symbol id
c = ((j->code_buffer >> (j->code_bits - k)) & bmask[k]) + h->delta[k];
assert((((j->code_buffer) >> (j->code_bits - h->size[c])) & bmask[h->size[c]]) == h->code[c]);
// convert the id to a symbol
j->code_bits -= k;
return h->values[c];
}
// combined JPEG 'receive' and JPEG 'extend', since baseline
// always extends everything it receives.
__forceinline static int extend_receive(jpeg *j, int n)
{
unsigned int m = 1 << (n-1);
unsigned int k;
if (j->code_bits < n) grow_buffer_unsafe(j);
k = (j->code_buffer >> (j->code_bits - n)) & bmask[n];
j->code_bits -= n;
// the following test is probably a random branch that won't
// predict well. I tried to table accelerate it but failed.
// maybe it's compiling as a conditional move?
if (k < m)
return (-1 << n) + k + 1;
else
return k;
}
// given a value that's at position X in the zigzag stream,
// where does it appear in the 8x8 matrix coded as row-major?
static uint8 dezigzag[64+15] =
{
0, 1, 8, 16, 9, 2, 3, 10,
17, 24, 32, 25, 18, 11, 4, 5,
12, 19, 26, 33, 40, 48, 41, 34,
27, 20, 13, 6, 7, 14, 21, 28,
35, 42, 49, 56, 57, 50, 43, 36,
29, 22, 15, 23, 30, 37, 44, 51,
58, 59, 52, 45, 38, 31, 39, 46,
53, 60, 61, 54, 47, 55, 62, 63,
// let corrupt input sample past end
63, 63, 63, 63, 63, 63, 63, 63,
63, 63, 63, 63, 63, 63, 63
};
// decode one 64-entry block--
static int decode_block(jpeg *j, short data[64], huffman *hdc, huffman *hac, int b)
{
int diff,dc,k;
int t = decode(j, hdc);
if (t < 0) return e("bad huffman code","Corrupt JPEG");
// 0 all the ac values now so we can do it 32-bits at a time
memset(data,0,64*sizeof(data[0]));
diff = t ? extend_receive(j, t) : 0;
dc = j->img_comp[b].dc_pred + diff;
j->img_comp[b].dc_pred = dc;
data[0] = (short) dc;
// decode AC components, see JPEG spec
k = 1;
do {
int r,s;
int rs = decode(j, hac);
if (rs < 0) return e("bad huffman code","Corrupt JPEG");
s = rs & 15;
r = rs >> 4;
if (s == 0) {
if (rs != 0xf0) break; // end block
k += 16;
} else {
k += r;
// decode into unzigzag'd location
data[dezigzag[k++]] = (short) extend_receive(j,s);
}
} while (k < 64);
return 1;
}
// take a -128..127 value and clamp it and convert to 0..255
__forceinline static uint8 clamp(int x)
{
x += 128;
// trick to use a single test to catch both cases
if ((unsigned int) x > 255) {
if (x < 0) return 0;
if (x > 255) return 255;
}
return (uint8) x;
}
#define f2f(x) (int) (((x) * 4096 + 0.5))
#define fsh(x) ((x) << 12)
// derived from jidctint -- DCT_ISLOW
#define IDCT_1D(s0,s1,s2,s3,s4,s5,s6,s7) \
int t0,t1,t2,t3,p1,p2,p3,p4,p5,x0,x1,x2,x3; \
p2 = s2; \
p3 = s6; \
p1 = (p2+p3) * f2f(0.5411961f); \
t2 = p1 + p3*f2f(-1.847759065f); \
t3 = p1 + p2*f2f( 0.765366865f); \
p2 = s0; \
p3 = s4; \
t0 = fsh(p2+p3); \
t1 = fsh(p2-p3); \
x0 = t0+t3; \
x3 = t0-t3; \
x1 = t1+t2; \
x2 = t1-t2; \
t0 = s7; \
t1 = s5; \
t2 = s3; \
t3 = s1; \
p3 = t0+t2; \
p4 = t1+t3; \
p1 = t0+t3; \
p2 = t1+t2; \
p5 = (p3+p4)*f2f( 1.175875602f); \
t0 = t0*f2f( 0.298631336f); \
t1 = t1*f2f( 2.053119869f); \
t2 = t2*f2f( 3.072711026f); \
t3 = t3*f2f( 1.501321110f); \
p1 = p5 + p1*f2f(-0.899976223f); \
p2 = p5 + p2*f2f(-2.562915447f); \
p3 = p3*f2f(-1.961570560f); \
p4 = p4*f2f(-0.390180644f); \
t3 += p1+p4; \
t2 += p2+p3; \
t1 += p2+p4; \
t0 += p1+p3;
#if !STBI_SIMD
// .344 seconds on 3*anemones.jpg
static void idct_block(uint8 *out, int out_stride, short data[64], uint8 *dequantize)
{
int i,val[64],*v=val;
uint8 *o,*dq = dequantize;
short *d = data;
// columns
for (i=0; i < 8; ++i,++d,++dq, ++v) {
// if all zeroes, shortcut -- this avoids dequantizing 0s and IDCTing
if (d[ 8]==0 && d[16]==0 && d[24]==0 && d[32]==0
&& d[40]==0 && d[48]==0 && d[56]==0) {
// no shortcut 0 seconds
// (1|2|3|4|5|6|7)==0 0 seconds
// all separate -0.047 seconds
// 1 && 2|3 && 4|5 && 6|7: -0.047 seconds
int dcterm = d[0] * dq[0] << 2;
v[0] = v[8] = v[16] = v[24] = v[32] = v[40] = v[48] = v[56] = dcterm;
} else {
IDCT_1D(d[ 0]*dq[ 0],d[ 8]*dq[ 8],d[16]*dq[16],d[24]*dq[24],
d[32]*dq[32],d[40]*dq[40],d[48]*dq[48],d[56]*dq[56])
// constants scaled things up by 1<<12; let's bring them back
// down, but keep 2 extra bits of precision
x0 += 512; x1 += 512; x2 += 512; x3 += 512;
v[ 0] = (x0+t3) >> 10;
v[56] = (x0-t3) >> 10;
v[ 8] = (x1+t2) >> 10;
v[48] = (x1-t2) >> 10;
v[16] = (x2+t1) >> 10;
v[40] = (x2-t1) >> 10;
v[24] = (x3+t0) >> 10;
v[32] = (x3-t0) >> 10;
}
}
for (i=0, v=val, o=out; i < 8; ++i,v+=8,o+=out_stride) {
// no fast case since the first 1D IDCT spread components out
IDCT_1D(v[0],v[1],v[2],v[3],v[4],v[5],v[6],v[7])
// constants scaled things up by 1<<12, plus we had 1<<2 from first
// loop, plus horizontal and vertical each scale by sqrt(8) so together
// we've got an extra 1<<3, so 1<<17 total we need to remove.
x0 += 65536; x1 += 65536; x2 += 65536; x3 += 65536;
o[0] = clamp((x0+t3) >> 17);
o[7] = clamp((x0-t3) >> 17);
o[1] = clamp((x1+t2) >> 17);
o[6] = clamp((x1-t2) >> 17);
o[2] = clamp((x2+t1) >> 17);
o[5] = clamp((x2-t1) >> 17);
o[3] = clamp((x3+t0) >> 17);
o[4] = clamp((x3-t0) >> 17);
}
}
#else
static void idct_block(uint8 *out, int out_stride, short data[64], unsigned short *dequantize)
{
int i,val[64],*v=val;
uint8 *o;
unsigned short *dq = dequantize;
short *d = data;
// columns
for (i=0; i < 8; ++i,++d,++dq, ++v) {
// if all zeroes, shortcut -- this avoids dequantizing 0s and IDCTing
if (d[ 8]==0 && d[16]==0 && d[24]==0 && d[32]==0
&& d[40]==0 && d[48]==0 && d[56]==0) {
// no shortcut 0 seconds
// (1|2|3|4|5|6|7)==0 0 seconds
// all separate -0.047 seconds
// 1 && 2|3 && 4|5 && 6|7: -0.047 seconds
int dcterm = d[0] * dq[0] << 2;
v[0] = v[8] = v[16] = v[24] = v[32] = v[40] = v[48] = v[56] = dcterm;
} else {
IDCT_1D(d[ 0]*dq[ 0],d[ 8]*dq[ 8],d[16]*dq[16],d[24]*dq[24],
d[32]*dq[32],d[40]*dq[40],d[48]*dq[48],d[56]*dq[56])
// constants scaled things up by 1<<12; let's bring them back
// down, but keep 2 extra bits of precision
x0 += 512; x1 += 512; x2 += 512; x3 += 512;
v[ 0] = (x0+t3) >> 10;
v[56] = (x0-t3) >> 10;
v[ 8] = (x1+t2) >> 10;
v[48] = (x1-t2) >> 10;
v[16] = (x2+t1) >> 10;
v[40] = (x2-t1) >> 10;
v[24] = (x3+t0) >> 10;
v[32] = (x3-t0) >> 10;
}
}
for (i=0, v=val, o=out; i < 8; ++i,v+=8,o+=out_stride) {
// no fast case since the first 1D IDCT spread components out
IDCT_1D(v[0],v[1],v[2],v[3],v[4],v[5],v[6],v[7])
// constants scaled things up by 1<<12, plus we had 1<<2 from first
// loop, plus horizontal and vertical each scale by sqrt(8) so together
// we've got an extra 1<<3, so 1<<17 total we need to remove.
x0 += 65536; x1 += 65536; x2 += 65536; x3 += 65536;
o[0] = clamp((x0+t3) >> 17);
o[7] = clamp((x0-t3) >> 17);
o[1] = clamp((x1+t2) >> 17);
o[6] = clamp((x1-t2) >> 17);
o[2] = clamp((x2+t1) >> 17);
o[5] = clamp((x2-t1) >> 17);
o[3] = clamp((x3+t0) >> 17);
o[4] = clamp((x3-t0) >> 17);
}
}
static stbi_idct_8x8 stbi_idct_installed = idct_block;
extern void stbi_install_idct(stbi_idct_8x8 func)
{
stbi_idct_installed = func;
}
#endif
#define MARKER_none 0xff
// if there's a pending marker from the entropy stream, return that
// otherwise, fetch from the stream and get a marker. if there's no
// marker, return 0xff, which is never a valid marker value
static uint8 get_marker(jpeg *j)
{
uint8 x;
if (j->marker != MARKER_none) { x = j->marker; j->marker = MARKER_none; return x; }
x = get8u(&j->s);
if (x != 0xff) return MARKER_none;
while (x == 0xff)
x = get8u(&j->s);
return x;
}
// in each scan, we'll have scan_n components, and the order
// of the components is specified by order[]
#define RESTART(x) ((x) >= 0xd0 && (x) <= 0xd7)
// after a restart interval, reset the entropy decoder and
// the dc prediction
static void reset(jpeg *j)
{
j->code_bits = 0;
j->code_buffer = 0;
j->nomore = 0;
j->img_comp[0].dc_pred = j->img_comp[1].dc_pred = j->img_comp[2].dc_pred = 0;
j->marker = MARKER_none;
j->todo = j->restart_interval ? j->restart_interval : 0x7fffffff;
// no more than 1<<31 MCUs if no restart_interal? that's plenty safe,
// since we don't even allow 1<<30 pixels
}
static int parse_entropy_coded_data(jpeg *z)
{
reset(z);
if (z->scan_n == 1) {
int i,j;
#if STBI_SIMD
__declspec(align(16))
#endif
short data[64];
int n = z->order[0];
// non-interleaved data, we just need to process one block at a time,
// in trivial scanline order
// number of blocks to do just depends on how many actual "pixels" this
// component has, independent of interleaved MCU blocking and such
int w = (z->img_comp[n].x+7) >> 3;
int h = (z->img_comp[n].y+7) >> 3;
for (j=0; j < h; ++j) {
for (i=0; i < w; ++i) {
if (!decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+z->img_comp[n].ha, n)) return 0;
#if STBI_SIMD
stbi_idct_installed(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data, z->dequant2[z->img_comp[n].tq]);
#else
idct_block(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data, z->dequant[z->img_comp[n].tq]);
#endif
// every data block is an MCU, so countdown the restart interval
if (--z->todo <= 0) {
if (z->code_bits < 24) grow_buffer_unsafe(z);
// if it's NOT a restart, then just bail, so we get corrupt data
// rather than no data
if (!RESTART(z->marker)) return 1;
reset(z);
}
}
}
} else { // interleaved!
int i,j,k,x,y;
short data[64];
for (j=0; j < z->img_mcu_y; ++j) {
for (i=0; i < z->img_mcu_x; ++i) {
// scan an interleaved mcu... process scan_n components in order
for (k=0; k < z->scan_n; ++k) {
int n = z->order[k];
// scan out an mcu's worth of this component; that's just determined
// by the basic H and V specified for the component
for (y=0; y < z->img_comp[n].v; ++y) {
for (x=0; x < z->img_comp[n].h; ++x) {
int x2 = (i*z->img_comp[n].h + x)*8;
int y2 = (j*z->img_comp[n].v + y)*8;
if (!decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+z->img_comp[n].ha, n)) return 0;
#if STBI_SIMD
stbi_idct_installed(z->img_comp[n].data+z->img_comp[n].w2*y2+x2, z->img_comp[n].w2, data, z->dequant2[z->img_comp[n].tq]);
#else
idct_block(z->img_comp[n].data+z->img_comp[n].w2*y2+x2, z->img_comp[n].w2, data, z->dequant[z->img_comp[n].tq]);
#endif
}
}
}
// after all interleaved components, that's an interleaved MCU,
// so now count down the restart interval
if (--z->todo <= 0) {
if (z->code_bits < 24) grow_buffer_unsafe(z);
// if it's NOT a restart, then just bail, so we get corrupt data
// rather than no data
if (!RESTART(z->marker)) return 1;
reset(z);
}
}
}
}
return 1;
}
static int process_marker(jpeg *z, int m)
{
int L;
switch (m) {
case MARKER_none: // no marker found
return e("expected marker","Corrupt JPEG");
case 0xC2: // SOF - progressive
return e("progressive jpeg","JPEG format not supported (progressive)");
case 0xDD: // DRI - specify restart interval
if (get16(&z->s) != 4) return e("bad DRI len","Corrupt JPEG");
z->restart_interval = get16(&z->s);
return 1;
case 0xDB: // DQT - define quantization table
L = get16(&z->s)-2;
while (L > 0) {
int q = get8(&z->s);
int p = q >> 4;
int t = q & 15,i;
if (p != 0) return e("bad DQT type","Corrupt JPEG");
if (t > 3) return e("bad DQT table","Corrupt JPEG");
for (i=0; i < 64; ++i)
z->dequant[t][dezigzag[i]] = get8u(&z->s);
#if STBI_SIMD
for (i=0; i < 64; ++i)
z->dequant2[t][i] = dequant[t][i];
#endif
L -= 65;
}
return L==0;
case 0xC4: //
gitextract_7lf2bp5s/
├── .gitignore
├── CMakeLists.txt
├── Makefile
├── README.md
├── projects/
│ ├── VC6/
│ │ ├── SOIL.dsp
│ │ └── SOIL.dsw
│ ├── VC7.1/
│ │ ├── SOIL.sln
│ │ └── SOIL.vcproj
│ ├── VC8/
│ │ ├── SOIL.sln
│ │ └── SOIL.vcproj
│ ├── VC9/
│ │ ├── SOIL.sln
│ │ └── SOIL.vcproj
│ └── codeblocks/
│ └── SOIL.cbp
├── soil.html
└── src/
├── SOIL.c
├── SOIL.h
├── image_DXT.c
├── image_DXT.h
├── image_helper.c
├── image_helper.h
├── stb_image_aug.c
├── stb_image_aug.h
├── stbi_DDS_aug.h
├── stbi_DDS_aug_c.h
└── test_SOIL.cpp
SYMBOL INDEX (190 symbols across 8 files)
FILE: src/SOIL.c
function SOIL_load_OGL_texture (line 118) | unsigned int
function SOIL_load_OGL_HDR_texture (line 170) | unsigned int
function SOIL_load_OGL_texture_from_memory (line 222) | unsigned int
function SOIL_load_OGL_cubemap (line 280) | unsigned int
function SOIL_load_OGL_cubemap_from_memory (line 465) | unsigned int
function SOIL_load_OGL_single_cubemap (line 668) | unsigned int
function SOIL_load_OGL_single_cubemap_from_memory (line 753) | unsigned int
function SOIL_create_OGL_single_cubemap (line 844) | unsigned int
function SOIL_create_OGL_texture (line 955) | unsigned int
function check_for_GL_errors (line 973) | void check_for_GL_errors( const char *calling_location )
function check_for_GL_errors (line 984) | void check_for_GL_errors( const char *calling_location )
function SOIL_internal_create_OGL_texture (line 990) | unsigned int
function SOIL_save_screenshot (line 1376) | int
function SOIL_save_image (line 1476) | int
function SOIL_free_image_data (line 1523) | void
function SOIL_direct_load_DDS_from_memory (line 1541) | unsigned int SOIL_direct_load_DDS_from_memory(
function SOIL_direct_load_DDS (line 1833) | unsigned int SOIL_direct_load_DDS(
function query_NPOT_capability (line 1881) | int query_NPOT_capability( void )
function query_tex_rectangle_capability (line 1907) | int query_tex_rectangle_capability( void )
function query_cubemap_capability (line 1936) | int query_cubemap_capability( void )
function query_DXT_capability (line 1965) | int query_DXT_capability( void )
FILE: src/image_DXT.c
function save_image_as_DDS (line 42) | int
function convert_bit_range (line 278) | int convert_bit_range( int c, int from_bits, int to_bits )
function rgb_to_565 (line 284) | int rgb_to_565( int r, int g, int b )
function rgb_888_from_565 (line 292) | void rgb_888_from_565( unsigned int c, int *r, int *g, int *b )
function compute_color_line_STDEV (line 299) | void compute_color_line_STDEV(
function LSE_master_colors_max_min (line 411) | void LSE_master_colors_max_min(
function compress_DDS_color_block (line 500) | void
function compress_DDS_alpha_block (line 577) | void
FILE: src/image_DXT.h
type DDS_header (line 49) | typedef struct
FILE: src/image_helper.c
function up_scale_image (line 14) | int
function mipmap_image (line 84) | int
function scale_image_RGB_to_NTSC_safe (line 154) | int
function clamp_byte (line 191) | unsigned char clamp_byte( int x ) { return ( (x) < 0 ? (0) : ( (x) > 255...
function convert_RGB_to_YCoCg (line 200) | int
function convert_YCoCg_to_RGB (line 259) | int
function find_max_RGBE (line 312) | float
function RGBE_to_RGBdivA (line 339) | int
function RGBE_to_RGBdivA2 (line 388) | int
FILE: src/stb_image_aug.c
type uint8 (line 91) | typedef unsigned char uint8;
type uint16 (line 92) | typedef unsigned short uint16;
type int16 (line 93) | typedef signed short int16;
type uint32 (line 94) | typedef unsigned int uint32;
type int32 (line 95) | typedef signed int int32;
type uint (line 96) | typedef unsigned int uint;
function e (line 125) | static int e(char *str)
function stbi_image_free (line 142) | void stbi_image_free(void *retval_from_stbi_load)
function stbi_register_loader (line 151) | int stbi_register_loader(stbi_loader *loader)
function stbi_is_hdr_from_memory (line 291) | int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len)
function stbi_is_hdr (line 301) | extern int stbi_is_hdr (char const *filename)
function stbi_is_hdr_from_file (line 312) | extern int stbi_is_hdr_from_file(FILE *f)
function stbi_hdr_to_ldr_gamma (line 334) | void stbi_hdr_to_ldr_gamma(float gamma) { h2l_gamma_i = 1/gamma; }
function stbi_hdr_to_ldr_scale (line 335) | void stbi_hdr_to_ldr_scale(float scale) { h2l_scale_i = 1/scale; }
function stbi_ldr_to_hdr_gamma (line 337) | void stbi_ldr_to_hdr_gamma(float gamma) { l2h_gamma = gamma; }
function stbi_ldr_to_hdr_scale (line 338) | void stbi_ldr_to_hdr_scale(float scale) { l2h_scale = scale; }
type stbi (line 354) | typedef struct
function start_file (line 366) | static void start_file(stbi *s, FILE *f)
function start_mem (line 372) | static void start_mem(stbi *s, uint8 const *buffer, int len)
function get8 (line 381) | __forceinline static int get8(stbi *s)
function at_eof (line 394) | __forceinline static int at_eof(stbi *s)
function uint8 (line 403) | __forceinline static uint8 get8u(stbi *s)
function skip (line 408) | static void skip(stbi *s, int n)
function get16 (line 418) | static int get16(stbi *s)
function uint32 (line 424) | static uint32 get32(stbi *s)
function get16le (line 430) | static int get16le(stbi *s)
function uint32 (line 436) | static uint32 get32le(stbi *s)
function getn (line 442) | static void getn(stbi *s, stbi_uc *buffer, int n)
function uint8 (line 465) | static uint8 compute_y(int r, int g, int b)
function stbi_uc (line 533) | static stbi_uc *hdr_to_ldr(float *data, int x, int y, int comp)
type huffman (line 589) | typedef struct
type jpeg (line 600) | typedef struct
function build_huffman (line 639) | static int build_huffman(huffman *h, int *count)
function grow_buffer_unsafe (line 680) | static void grow_buffer_unsafe(jpeg *j)
function decode (line 701) | __forceinline static int decode(jpeg *j, huffman *h)
function extend_receive (line 752) | __forceinline static int extend_receive(jpeg *j, int n)
function decode_block (line 786) | static int decode_block(jpeg *j, short data[64], huffman *hdc, huffman *...
function uint8 (line 821) | __forceinline static uint8 clamp(int x)
function idct_block (line 875) | static void idct_block(uint8 *out, int out_stride, short data[64], uint8...
function idct_block (line 927) | static void idct_block(uint8 *out, int out_stride, short data[64], unsig...
function stbi_install_idct (line 981) | extern void stbi_install_idct(stbi_idct_8x8 func)
function uint8 (line 991) | static uint8 get_marker(jpeg *j)
function reset (line 1008) | static void reset(jpeg *j)
function parse_entropy_coded_data (line 1020) | static int parse_entropy_coded_data(jpeg *z)
function process_marker (line 1092) | static int process_marker(jpeg *z, int m)
function process_scan_header (line 1161) | static int process_scan_header(jpeg *z)
function process_frame_header (line 1186) | static int process_frame_header(jpeg *z, int scan)
function decode_jpeg_header (line 1265) | static int decode_jpeg_header(jpeg *z, int scan)
function decode_jpeg_image (line 1286) | static int decode_jpeg_image(jpeg *j)
type uint8 (line 1306) | typedef uint8 *(*resample_row_func)(uint8 *out, uint8 *in0, uint8 *in1,
function uint8 (line 1311) | static uint8 *resample_row_1(uint8 *out, uint8 *in_near, uint8 *in_far, ...
function uint8 (line 1316) | static uint8* resample_row_v_2(uint8 *out, uint8 *in_near, uint8 *in_far...
function uint8 (line 1325) | static uint8* resample_row_h_2(uint8 *out, uint8 *in_near, uint8 *in_fa...
function uint8 (line 1350) | static uint8 *resample_row_hv_2(uint8 *out, uint8 *in_near, uint8 *in_fa...
function uint8 (line 1371) | static uint8 *resample_row_generic(uint8 *out, uint8 *in_near, uint8 *in...
function YCbCr_to_RGB_row (line 1385) | static void YCbCr_to_RGB_row(uint8 *out, uint8 *y, uint8 *pcb, uint8 *pc...
function stbi_install_YCbCr_to_RGB (line 1413) | void stbi_install_YCbCr_to_RGB(stbi_YCbCr_to_RGB_run func)
function cleanup_jpeg (line 1421) | static void cleanup_jpeg(jpeg *j)
type stbi_resample (line 1436) | typedef struct
function uint8 (line 1446) | static uint8 *load_jpeg_image(jpeg *z, int *out_x, int *out_y, int *comp...
function stbi_jpeg_test_file (line 1573) | int stbi_jpeg_test_file(FILE *f)
function stbi_jpeg_test_memory (line 1585) | int stbi_jpeg_test_memory(stbi_uc const *buffer, int len)
type zhuffman (line 1612) | typedef struct
function bitreverse16 (line 1622) | __forceinline static int bitreverse16(int n)
function bit_reverse (line 1631) | __forceinline static int bit_reverse(int v, int bits)
function zbuild_huffman (line 1639) | static int zbuild_huffman(zhuffman *z, uint8 *sizelist, int num)
type zbuf (line 1690) | typedef struct
function zget8 (line 1704) | __forceinline static int zget8(zbuf *z)
function fill_bits (line 1710) | static void fill_bits(zbuf *z)
function zreceive (line 1719) | __forceinline static unsigned int zreceive(zbuf *z, int n)
function zhuffman_decode (line 1729) | __forceinline static int zhuffman_decode(zbuf *a, zhuffman *z)
function expand (line 1756) | static int expand(zbuf *z, int n) // need to make room for n bytes
function parse_huffman_block (line 1787) | static int parse_huffman_block(zbuf *a)
function compute_huffman_codes (line 1815) | static int compute_huffman_codes(zbuf *a)
function parse_uncompressed_block (line 1861) | static int parse_uncompressed_block(zbuf *a)
function parse_zlib_header (line 1890) | static int parse_zlib_header(zbuf *a)
function init_defaults (line 1905) | static void init_defaults(void)
function parse_zlib (line 1916) | static int parse_zlib(zbuf *a, int parse_header)
function do_zlib (line 1945) | static int do_zlib(zbuf *a, char *obuf, int olen, int exp, int parse_hea...
function stbi_zlib_decode_buffer (line 1976) | int stbi_zlib_decode_buffer(char *obuffer, int olen, char const *ibuffer...
function stbi_zlib_decode_noheader_buffer (line 2003) | int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char...
type chunk (line 2025) | typedef struct
function chunk (line 2033) | static chunk get_chunk_header(stbi *s)
function check_png_header (line 2041) | static int check_png_header(stbi *s)
type png (line 2050) | typedef struct
function paeth (line 2067) | static int paeth(int a, int b, int c)
function create_png_image (line 2079) | static int create_png_image(png *a, uint8 *raw, uint32 raw_len, int out_n)
function compute_transparency (line 2149) | static int compute_transparency(png *z, uint8 tc[3], int out_n)
function expand_palette (line 2174) | static int expand_palette(png *a, uint8 *palette, int len, int pal_img_n)
function parse_png_file (line 2208) | static int parse_png_file(png *z, int scan, int req_comp)
function stbi_png_test_file (line 2410) | int stbi_png_test_file(FILE *f)
function stbi_png_test_memory (line 2422) | int stbi_png_test_memory(stbi_uc const *buffer, int len)
function bmp_test (line 2438) | static int bmp_test(stbi *s)
function stbi_bmp_test_file (line 2453) | int stbi_bmp_test_file (FILE *f)
function stbi_bmp_test_memory (line 2464) | int stbi_bmp_test_memory (stbi_uc const *buffer, int len)
function high_bit (line 2472) | static int high_bit(unsigned int z)
function bitcount (line 2484) | static int bitcount(unsigned int a)
function shiftsigned (line 2494) | static int shiftsigned(int v, int shift, int bits)
function stbi_uc (line 2511) | static stbi_uc *bmp_load(stbi *s, int *x, int *y, int *comp, int req_comp)
function stbi_uc (line 2706) | stbi_uc *stbi_bmp_load (char const *filename, int ...
function stbi_uc (line 2716) | stbi_uc *stbi_bmp_load_from_file (FILE *f, int *x, in...
function stbi_uc (line 2724) | stbi_uc *stbi_bmp_load_from_memory (stbi_uc const *buffer, int len, int ...
function tga_test (line 2734) | static int tga_test(stbi *s)
function stbi_tga_test_file (line 2755) | int stbi_tga_test_file (FILE *f)
function stbi_tga_test_memory (line 2766) | int stbi_tga_test_memory (stbi_uc const *buffer, int len)
function stbi_uc (line 2773) | static stbi_uc *tga_load(stbi *s, int *x, int *y, int *comp, int req_comp)
function stbi_uc (line 2992) | stbi_uc *stbi_tga_load (char const *filename, int ...
function stbi_uc (line 3002) | stbi_uc *stbi_tga_load_from_file (FILE *f, int *x, in...
function stbi_uc (line 3010) | stbi_uc *stbi_tga_load_from_memory (stbi_uc const *buffer, int len, int ...
function psd_test (line 3021) | static int psd_test(stbi *s)
function stbi_psd_test_file (line 3028) | int stbi_psd_test_file(FILE *f)
function stbi_psd_test_memory (line 3039) | int stbi_psd_test_memory(stbi_uc const *buffer, int len)
function stbi_uc (line 3046) | static stbi_uc *psd_load(stbi *s, int *x, int *y, int *comp, int req_comp)
function stbi_uc (line 3206) | stbi_uc *stbi_psd_load(char const *filename, int *x, int *y, int *comp, ...
function stbi_uc (line 3216) | stbi_uc *stbi_psd_load_from_file(FILE *f, int *x, int *y, int *comp, int...
function stbi_uc (line 3224) | stbi_uc *stbi_psd_load_from_memory (stbi_uc const *buffer, int len, int ...
function hdr_test (line 3236) | static int hdr_test(stbi *s)
function stbi_hdr_test_memory (line 3246) | int stbi_hdr_test_memory(stbi_uc const *buffer, int len)
function stbi_hdr_test_file (line 3254) | int stbi_hdr_test_file(FILE *f)
function hdr_convert (line 3289) | static void hdr_convert(float *output, stbi_uc *input, int req_comp)
function stbi_uc (line 3424) | static stbi_uc *hdr_load_rgbe(stbi *s, int *x, int *y, int *comp, int re...
function stbi_uc (line 3539) | stbi_uc *stbi_hdr_load_rgbe_file(FILE *f, int *x, int *y, int *comp, int...
function stbi_uc (line 3546) | stbi_uc *stbi_hdr_load_rgbe (char const *filename, int ...
function stbi_uc (line 3564) | stbi_uc *stbi_hdr_load_rgbe_memory(stbi_uc *buffer, int len, int *x, int...
function write8 (line 3577) | static void write8(FILE *f, int x) { uint8 z = (uint8) x; fwrite(&z,1,1,...
function writefv (line 3579) | static void writefv(FILE *f, char *fmt, va_list v)
function writef (line 3595) | static void writef(FILE *f, char *fmt, ...)
function write_pixels (line 3603) | static void write_pixels(FILE *f, int rgb_dir, int vdir, int x, int y, i...
function outfile (line 3642) | static int outfile(char const *filename, int rgb_dir, int vdir, int x, i...
function stbi_write_bmp (line 3656) | int stbi_write_bmp(char const *filename, int x, int y, int comp, void *d...
function stbi_write_tga (line 3665) | int stbi_write_tga(char const *filename, int x, int y, int comp, void *d...
FILE: src/stb_image_aug.h
type stbi_uc (line 173) | typedef unsigned char stbi_uc;
type stbi_loader (line 313) | typedef struct
FILE: src/stbi_DDS_aug_c.h
type DDS_header (line 6) | typedef struct {
function dds_test (line 74) | static int dds_test(stbi *s)
function stbi_dds_test_file (line 86) | int stbi_dds_test_file (FILE *f)
function stbi_dds_test_memory (line 97) | int stbi_dds_test_memory (stbi_uc const *buffer, int len)
function stbi_convert_bit_range (line 105) | int stbi_convert_bit_range( int c, int from_bits, int to_bits )
function stbi_rgb_888_from_565 (line 110) | void stbi_rgb_888_from_565( unsigned int c, int *r, int *g, int *b )
function stbi_decode_DXT1_block (line 116) | void stbi_decode_DXT1_block(
function stbi_decode_DXT23_alpha_block (line 172) | void stbi_decode_DXT23_alpha_block(
function stbi_decode_DXT45_alpha_block (line 186) | void stbi_decode_DXT45_alpha_block(
function stbi_decode_DXT_color_block (line 230) | void stbi_decode_DXT_color_block(
function stbi_uc (line 268) | static stbi_uc *dds_load(stbi *s, int *x, int *y, int *comp, int req_comp)
function stbi_uc (line 488) | stbi_uc *stbi_dds_load_from_file (FILE *f, int *x, in...
function stbi_uc (line 495) | stbi_uc *stbi_dds_load (char *filename, int *x, in...
function stbi_uc (line 506) | stbi_uc *stbi_dds_load_from_memory (stbi_uc const *buffer, int len, int ...
FILE: src/test_SOIL.cpp
function WinMain (line 15) | int WINAPI WinMain(HINSTANCE hInstance,
function LRESULT (line 313) | LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM ...
function EnableOpenGL (line 342) | void EnableOpenGL(HWND hwnd, HDC* hDC, HGLRC* hRC)
function DisableOpenGL (line 373) | void DisableOpenGL (HWND hwnd, HDC hDC, HGLRC hRC)
Condensed preview — 25 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (358K chars).
[
{
"path": ".gitignore",
"chars": 358,
"preview": "# Prerequisites\n*.d\n\n# Compiled Object files\n*.slo\n*.lo\n*.o\n*.obj\n\n# Precompiled Headers\n*.gch\n*.pch\n\n# Compiled Dynamic"
},
{
"path": "CMakeLists.txt",
"chars": 795,
"preview": "cmake_minimum_required (VERSION 2.6)\nproject (SOIL)\n\nset (SOIL_BUILD_TESTS false CACHE BOOL \"Build tests\")\n\nif(ANDROID)\n"
},
{
"path": "Makefile",
"chars": 1582,
"preview": "# SOIL makefile for linux (based on the AngelScript makefile)\n# Type 'make' then 'make install' to complete the installa"
},
{
"path": "README.md",
"chars": 6219,
"preview": "This is a clone of Simple OpenGL Image Library from http://lonesock.net/soil.html which hasn't changed since July 7, 200"
},
{
"path": "projects/VC6/SOIL.dsp",
"chars": 3475,
"preview": "# Microsoft Developer Studio Project File - Name=\"SOIL\" - Package Owner=<4>\r\n# Microsoft Developer Studio Generated Buil"
},
{
"path": "projects/VC6/SOIL.dsw",
"chars": 533,
"preview": "Microsoft Developer Studio Workspace File, Format Version 6.00\r\n# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE!\r\n\r"
},
{
"path": "projects/VC7.1/SOIL.sln",
"chars": 897,
"preview": "Microsoft Visual Studio Solution File, Format Version 8.00\r\nProject(\"{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}\") = \"SOIL\", "
},
{
"path": "projects/VC7.1/SOIL.vcproj",
"chars": 3627,
"preview": "<?xml version=\"1.0\" encoding=\"Windows-1252\"?>\r\n<VisualStudioProject\r\n\tProjectType=\"Visual C++\"\r\n\tVersion=\"7.10\"\r\n\tName=\""
},
{
"path": "projects/VC8/SOIL.sln",
"chars": 870,
"preview": "\r\nMicrosoft Visual Studio Solution File, Format Version 9.00\r\n# Visual Studio 2005\r\nProject(\"{8BC9CEB8-8B4A-11D0-8D11-0"
},
{
"path": "projects/VC8/SOIL.vcproj",
"chars": 4159,
"preview": "<?xml version=\"1.0\" encoding=\"Windows-1252\"?>\r\n<VisualStudioProject\r\n\tProjectType=\"Visual C++\"\r\n\tVersion=\"8.00\"\r\n\tName=\""
},
{
"path": "projects/VC9/SOIL.sln",
"chars": 1225,
"preview": "\r\nMicrosoft Visual Studio Solution File, Format Version 10.00\r\n# Visual Studio 2008\r\nProject(\"{8BC9CEB8-8B4A-11D0-8D11-"
},
{
"path": "projects/VC9/SOIL.vcproj",
"chars": 6725,
"preview": "<?xml version=\"1.0\" encoding=\"Windows-1252\"?>\r\n<VisualStudioProject\r\n\tProjectType=\"Visual C++\"\r\n\tVersion=\"9.00\"\r\n\tName=\""
},
{
"path": "projects/codeblocks/SOIL.cbp",
"chars": 2496,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\" ?>\n<CodeBlocks_project_file>\n\t<FileVersion major=\"1\" minor=\"6\" />\n"
},
{
"path": "soil.html",
"chars": 18349,
"preview": "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">\r\n<HTML>\r\n<HEAD>\r\n\t<META HTTP-EQUIV=\"CONTENT-TYPE\" CONTENT"
},
{
"path": "src/SOIL.c",
"chars": 59226,
"preview": "/*\r\n\tJonathan Dummer\r\n\t2007-07-26-10.36\r\n\r\n\tSimple OpenGL Image Library\r\n\r\n\tPublic Domain\r\n\tusing Sean Barret's stb_imag"
},
{
"path": "src/SOIL.h",
"chars": 15545,
"preview": "/**\r\n\t@mainpage SOIL\r\n\r\n\tJonathan Dummer\r\n\t2007-07-26-10.36\r\n\r\n\tSimple OpenGL Image Library\r\n\r\n\tA tiny c library for upl"
},
{
"path": "src/image_DXT.c",
"chars": 17181,
"preview": "/*\r\n\tJonathan Dummer\r\n\t2007-07-31-10.32\r\n\r\n\tsimple DXT compression / decompression code\r\n\r\n\tpublic domain\r\n*/\r\n\r\n#includ"
},
{
"path": "src/image_DXT.h",
"chars": 3212,
"preview": "/*\r\n\tJonathan Dummer\r\n\t2007-07-31-10.32\r\n\r\n\tsimple DXT compression / decompression code\r\n\r\n\tpublic domain\r\n*/\r\n\r\n#ifndef"
},
{
"path": "src/image_helper.c",
"chars": 10511,
"preview": "/*\r\n Jonathan Dummer\r\n\r\n image helper functions\r\n\r\n MIT license\r\n*/\r\n\r\n#include \"image_helper.h\"\r\n#include <std"
},
{
"path": "src/image_helper.h",
"chars": 2287,
"preview": "/*\r\n Jonathan Dummer\r\n\r\n Image helper functions\r\n\r\n MIT license\r\n*/\r\n\r\n#ifndef HEADER_IMAGE_HELPER\r\n#define HEA"
},
{
"path": "src/stb_image_aug.c",
"chars": 117420,
"preview": "/* stbi-1.16 - public domain JPEG/PNG reader - http://nothings.org/stb_image.c\r\n when you control t"
},
{
"path": "src/stb_image_aug.h",
"chars": 16945,
"preview": "/* stbi-1.16 - public domain JPEG/PNG reader - http://nothings.org/stb_image.c\r\n when you control t"
},
{
"path": "src/stbi_DDS_aug.h",
"chars": 797,
"preview": "/*\r\n\tadding DDS loading support to stbi\r\n*/\r\n\r\n#ifndef HEADER_STB_IMAGE_DDS_AUGMENTATION\n#define HEADER_STB_IMAGE_DDS_AU"
},
{
"path": "src/stbi_DDS_aug_c.h",
"chars": 15447,
"preview": "\r\n///\tDDS file support, does decoding, _not_ direct uploading\r\n///\t(use SOIL for that ;-)\r\n\r\n///\tA bunch of DirectDraw S"
},
{
"path": "src/test_SOIL.cpp",
"chars": 11270,
"preview": "#include <string>\r\n#include <iostream>\r\n\r\n#include <windows.h>\r\n#include <shellapi.h>\r\n#include <gl/gl.h>\r\n#include <gl/"
}
]
About this extraction
This page contains the full source code of the kbranigan/Simple-OpenGL-Image-Library GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 25 files (313.6 KB), approximately 101.8k tokens, and a symbol index with 190 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.