This commit is contained in:
Henrik Rydgard 2012-03-31 11:16:13 +02:00
parent dc7c033a3c
commit 8b076c5b88
58 changed files with 136 additions and 519 deletions

View File

@ -1,11 +1,29 @@
native
======
This is my library of stuff that I use when writing C++ programs, mostly for Android. It has some basic OpenGL utility code, JSON read/write (two libraries that should be made more similar), 2D texture atlases and drawing code, ETC1 texture loading support, basic logging, etc. The associated tools to create ZIM texture files and atlases do not yet live here but I might move them here eventually.
This is my library of stuff that I use when writing C++ programs, mostly for Android but it's all written to enable easy portability between Android, Linux, Windows and MacOSX.
It contains:
* JSON read/write (two libraries that should be made more similar)
* basic OpenGL utility code, like compressed texture loading
* 2D texture atlases and drawing code
* ETC1 texture loading support
* basic logging
* Really simple audio mixer with OGG sample support
* RIFF file read/write
The associated tools to create ZIM texture files and atlases do not yet live here but I might move them here eventually.
This library is not really meant to be a public library but I see no reason not to set it free.
Note that the included VS project is probably not very useful for you and you're likely better off making your own.
Don't complain about inconsistent naming etc - this consists of code that has been cobbled together from a variety of my projects through the years. Fashions come and go.
This project incorporates code from a variety of public domain or similarly-licensed code. This is the list:
This library, for my convenience, incorporates code from a variety of public domain or similarly-licensed code. This is the list:
* glew (GL extension wrangler), MIT license. TODO: should just use a submodule.
* etcpack by Ericsson, in a cleaned up form. Has strange license but not very limiting - you can only use the code for making textures for hardware supporting ETC1, or something like that. Don't think it affects the rest of the code in any way.
* sha1, public domain implementation by Dominik Reichl
* vjson in a heavily modified form, originally by Ivan Vashchaev (TODO: break out into its own repo?)

View File

@ -17,14 +17,14 @@ struct PlayParams {
// Mixer
// ==========================
// For now, channels is required to be 2.
// For now, channels is required to be 2 (it specifies L/R, not mixing channels)
Mixer *mixer_create(int sample_rate, int channels, int fixed_channels);
void mixer_destroy(Mixer *mixer);
// Buffer must be r/w, for efficient mixing
// TODO: Use local buffer instead.
// Buffer must be r/w.
void mixer_mix(Mixer *mixer, short *buffer, int num_samples);
// Clip
// ==========================
Clip *clip_load(const char *filename);

View File

@ -55,7 +55,6 @@ short *wav_read(const char *filename,
free(data);
return NULL;
}
// ILOG("got wave data: %i", numSamples);
cf.ascend();
} else {
ELOG("Error - no data chunk in wav");

View File

@ -1,7 +0,0 @@
#include "LAME.h"
#include "LAMEString.h"
String getUserName()
{
return String("user");
}

View File

@ -1,27 +0,0 @@
#ifndef __LAME_H__
#define __LAME_H__
#include "base/basictypes.h"
#include "base/logging.h"
#include "base/color.h"
#ifndef PI
#define PI 3.141592653589793f
#endif
template <class T>
inline T MIN(T t1, T t2) {
return t1<t2 ? t1 : t2;
}
template <class T>
inline T MAX(T t1, T t2) {
return t1>t2 ? t1 : t2;
}
template <class T>
inline T ABS(T &t) {
if (t<0) return -t; else return t;
}
#endif //__LAME_H__

View File

@ -1,48 +0,0 @@
#ifndef _WIN32
#include <unistd.h>
#endif
#include "LAMEApp.h"
LAMEApp::LAMEApp() {
penDown=false;
wannaQuit=false;
active=0;
TCHAR tmp[256];
#ifdef _WIN32
hWnd=0;
GetModuleFileName(0,tmp,255);
#else
char *discard = getcwd(tmp, 256);
discard++;
#endif
path=tmp;
path=path.getPath()+String(TEXT("/"));
}
LAMEApp::~LAMEApp() {
}
bool LAMEApp::init(int width, int height) {
this->width = width;
this->height = height;
return true;
}
int LAMEApp::run() {
return -1;
}
void LAMEApp::close() {
wannaQuit = true;
}
void LAMEApp::startTimer(int ID, int interval) {
// SetTimer(hWnd, ID, interval, 0);
}
void LAMEApp::stopTimer(int ID) {
// KillTimer(hWnd, ID);
}

View File

@ -1,84 +0,0 @@
#pragma once
//LAME: the Lean And MEan Extensions.
// #include "gfx/draw_buffer.h"
#include "LAMEString.h"
class LAMEApp {
protected:
bool wannaQuit;
bool active;
int width;
int height;
#ifndef WINCE
public:
#endif
bool penDown;
protected:
String path;
public:
LAMEApp();
virtual ~LAMEApp();
bool init(int width, int height);
virtual int run();
void close();
void startTimer(int ID, int interval);
void stopTimer(int ID);
void refresh();
virtual void onLoop() { }
virtual void onButtonDown(int b) {}
virtual void onButtonUp(int b) {}
virtual void onPenDown(int x, int y) { }
virtual void onPenMove(int x, int y, bool pressed) { }
virtual void onPenUp(int x, int y) { }
virtual void onKeyDown(int key) { }
virtual void onKeyChar(int key) { }
virtual void onKeyUp(int key) { }
virtual void onLostFocus() { }
virtual void onGotFocus() { }
virtual void onCreate() { }
virtual void onDestroy() { }
virtual void onTimer(int timerID) { }
virtual void draw() { }
int getWidth() const {return width;}
int getHeight() const { return height;}
String getPath() const {
return path;
}
};
inline String getRelativePath(String temp)
{
#if defined(ANDROID) || defined(SDL)
return temp;
#else
#error TODO: check this
if (!theApp) return temp;
#ifdef WINCE
if (temp[0] != TCHAR('\\')) //if it's a relative path (assume to the program location), then let's expand it to a full path
if (temp.find(theApp->getPath(),0)==-1)
{
return theApp->getPath() + temp;
}
#else
if (temp[2] != TCHAR('\\')) //if it's a relative path (assume to the program location), then let's expand it to a full path
if (temp.find(theApp->getPath(),0)==-1)
{
return theApp->getPath() + temp;
}
#endif
return temp;
#endif
}

View File

@ -1,3 +1,6 @@
// NOTE: See warning in header.
#include <ctype.h>
#include <string.h>
#include <stdlib.h>

View File

@ -1,3 +1,7 @@
// NOTE: This is only here for legacy reasons.
// In new code, please use std::string.
#pragma once
#include <stdlib.h>

View File

@ -3,6 +3,7 @@
#include "base/error_context.h"
#include <vector>
// TODO: Fix this threadery
#ifndef _WIN32
#undef __THREAD
#define __THREAD

View File

@ -1,5 +1,10 @@
#pragma once
// Simple wrapper around Android's logging interface that also allows other
// implementations, and also some misc utilities.
// Disable annoying warnings in VS
#ifdef _MSC_VER
#pragma warning (disable:4996) //strcpy may be dangerous
#endif
@ -18,7 +23,7 @@ inline void Crash() {
*p = 1;
}
#else
// TODO: 64-bit version
inline void Crash() {
asm("int $0x3");
}
@ -30,8 +35,9 @@ inline void Crash() {
#include <android/log.h>
// Must only be used for logging
#ifndef APP_NAME
#define APP_NAME "Turboviking"
#define APP_NAME "NativeApp"
#endif
#define ILOG(...) __android_log_print(ANDROID_LOG_INFO, APP_NAME, __VA_ARGS__);
@ -43,6 +49,8 @@ inline void Crash() {
#else
// TODO: Win32 version using OutputDebugString
#include <stdio.h>
#define ILOG(...) {printf("I: %s:%i: ", __FILE__, __LINE__); printf("I: " __VA_ARGS__); printf("\n");}
@ -57,3 +65,5 @@ inline void Crash() {
#endif
#define CHECK(a) {if (!(a)) {FLOG("CHECK failed");}}
#define CHECK_EQ(a, b) CHECK((a) == (b));
#define CHECK_NE(a, b) CHECK((a) != (b));

View File

@ -1,5 +1,7 @@
#pragma once
// Trivial implementation of boost::scoped_ptr, in a way that I prefer.
template<class T>
class scoped_ptr {
public:
@ -21,7 +23,6 @@ class scoped_ptr {
const T *operator->() const { return ptr_; }
private:
// don't copy that floppy
scoped_ptr(const scoped_ptr<T> &other);
void operator=(const scoped_ptr<T> &other);
T *ptr_;

View File

@ -1,5 +1,6 @@
#pragma once
// Statistics collection. Not very developed.
#define STATS_ENABLE

View File

@ -4,6 +4,7 @@
#include <stdio.h>
#include <string>
// Dumb wrapper around itoa, providing a buffer. Declare this on the stack.
class ITOA {
public:
char buffer[16];
@ -12,7 +13,9 @@ public:
return &buffer[0];
}
};
// Other simple string utilities.
inline bool endsWith(const std::string &str, const std::string &what) {
return str.substr(str.size() - what.size()) == what;
}
}

View File

@ -11,9 +11,11 @@ void time_update();
float time_now();
double time_now_d();
// Slower than the above cached time functions
// Uncached time. Slower than the above cached time functions. Does not update cached time, call time_update for that.
double real_time_now();
int time_now_ms();
// Sleep. Does not necessarily have millisecond granularity, especially on Windows.
void sleep_ms(int ms);

View File

@ -1,18 +1,19 @@
#pragma once
// RIFF file format reader/writer. Very old code, basically a total mess but it still works.
// TO REMEMBER WHEN USING:
// EITHER a chunk contains ONLY data
// OR it contains ONLY other chunks
// otherwise the scheme breakes.
#include <string>
#include "base/basictypes.h"
#include "base/LAMEString.h"
#include "file/easy_file.h"
// TO REMEMBER WHEN USING:
// EITHER a chunk contains ONLY data
// OR it contains ONLY other chunks
// otherwise the scheme breaks...
// hm.. or come to think about it, some data at the beginning of a chunk with subchunks WOULD work..
// but not safely, so don't try
inline uint32 flipID(uint32 id) {
return ((id>>24)&0xFF) | ((id>>8)&0xFF00) | ((id<<8)&0xFF0000) | ((id<<24)&0xFF000000);
}

View File

@ -11,11 +11,6 @@ LAMEFile::LAMEFile() : file_(NULL) {
LAMEFile::~LAMEFile() { }
bool LAMEFile::open(const char *filename, eFileMode mode) {
//for easier access if we want to expand the path..
// String temp=filename;
// temp = getRelativePath(temp);
//it's time to open the file
file_ = fopen(filename, mode == FILE_READ ? "rb" : "wb");
if (!file_) {

View File

@ -1,5 +1,7 @@
#pragma once
// A dumb wrapper around stdio, for convenience. Very old.
#include <stdio.h>
#include <string>
@ -13,6 +15,7 @@ enum eFileMode {
FILE_WRITE=6
};
// TODO: Rename.
class LAMEFile {
public:
LAMEFile();

View File

@ -27,7 +27,6 @@ bool WriteStringToFile(bool text_file, const std::string &str, const char *filen
return true;
}
// Overloaded GetSize, accepts FILE*
uint64_t GetSize(FILE *f)
{
// can't use off_t here because it can be 32-bit
@ -36,7 +35,9 @@ uint64_t GetSize(FILE *f)
return 0;
}
uint64_t size = ftell(f);
// Reset the seek position to where it was when we started.
if ((size != pos) && (fseek(f, pos, SEEK_SET) != 0)) {
// Should error here
return 0;
}
return size;
@ -122,4 +123,4 @@ void deleteFile(const char *file)
}
#endif
}
#endif
#endif

View File

@ -3,9 +3,10 @@
#include <string>
#include <vector>
// Whole-file reading/writing
bool writeStringToFile(bool text_file, const std::string &str, const char *filename);
bool readFileToString(bool text_file, const char *filename, std::string &str);
// Beginnings of a directory utility system. TODO: Improve.
size_t getFilesInDir(const char *directory, std::vector<std::string> *files);
void deleteFile(const char *file);
void deleteFile(const char *file);

View File

@ -1,12 +1,15 @@
#include "base/basictypes.h"
// Basic virtual file system. Used to manage assets on Android, where we have to
// read them manually out of the APK zipfile, while being able to run on other
// platforms as well with the appropriate directory set-up.
class AssetReader;
// Virtual file system.
void VFSRegister(const char *prefix, AssetReader *reader);
void VFSShutdown();
// Use delete [] to release the memory.
// Always allocates an extra '\0' at the end, so that it
// Use delete [] to release the returned memory.
// Always allocates an extra zero byte at the end, so that it
// can be used for text like shader sources.
uint8_t *VFSReadFile(const char *filename, size_t *size);

View File

@ -1,3 +1,5 @@
// TODO: Move much of this code to vfs.cpp
#ifndef _WIN32
#include <zip.h>
#endif

View File

@ -1,9 +1,10 @@
#pragma once
// New skool debugging
void gl_log_enable();
// Utility to be able to liberally sprinkle GL error checks around your code
// and easily disable them all in release builds - just undefine DEBUG_OPENGL.
// Old skool debugging
void gl_log_enable();
#ifndef ANDROID
//#define DEBUG_OPENGL

View File

@ -1,5 +1,8 @@
#pragma once
// On Android, even OpenGL can lose allocated resources. This is a utility to keep
// track of them.
class GfxResourceHolder {
public:
virtual ~GfxResourceHolder();

View File

@ -98,8 +98,10 @@ bool Texture::Load(const char *filename) {
}
filename_ = filename;
// Currently contains many Rollerball-specific workarounds.
// Currently here are a bunch of project-specific workarounds.
// They shouldn't really hurt anything else very much though.
int len = strlen(filename);
char fn[256];
strcpy(fn, filename);

View File

@ -1,6 +1,9 @@
#ifndef _TEXTURE_H
#define _TEXTURE_H
// Load and manage OpenGL textures easily. Supports ETC1 compressed texture with mipmaps.
#include <string>
#include "gfx/gl_lost_manager.h"

View File

@ -1,3 +1,7 @@
// WIP, please ignore
#include "gfx/texture.h"
#include <d3d11_1.h>

View File

@ -1,9 +1,8 @@
// Minimal procedural texture generator to generate some usual textures like circles.
// Minimal procedural texture generator to generate some usual textures like circles and vignette textures.
// "Gen" textures have filenames like this: "gen:256:256:vignette:0.1"
//
// These must be VERY VERY fast to not slow down loading. Could multicore this in the
// future.
// TODO: Rewrite to make more portable (should not use gfx api in here)
#include <cmath>
#include <stdio.h>

View File

@ -3,9 +3,4 @@
#include "gfx/texture.h"
// Returns an OpenGL ID for now.
uint8_t *generateTexture(const char *filename, int &bpp, int &w, int &h, bool &clamp);

View File

@ -1,3 +1,5 @@
// OpenGL-based 2D primitive buffer. For GLES 1.1.
#ifndef __LAMEBUFFER_H__
#define __LAMEBUFFER_H__
@ -16,7 +18,6 @@ enum {
TEXT_RIGHT = 16,
};
// OpenGL-based 2D primitive buffer. For GLES 1.1.
// Do not inherit from this class.
class LAMEBuffer {
public:
@ -45,7 +46,6 @@ class LAMEBuffer {
void rectFillDarken(int x1, int y1, int x2, int y2);
// New drawing APIs
void MeasureImage(int atlas_image, float *w, float *h);
void DrawImage(int atlas_image, float x, float y, Color color = COLOR(0xFFFFFF));
void DrawImageCenter(int atlas_image, float x, float y, Color color = COLOR(0xFFFFFF));

View File

@ -18,9 +18,13 @@
#include "gfx/texture_atlas.h"
#include "gfx/gl_debug_log.h"
DrawBuffer::DrawBuffer() : count_(0) {
enum {
// Enough?
verts_ = new Vertex[5000];
MAX_VERTS = 5000,
};
DrawBuffer::DrawBuffer() : count_(0) {
verts_ = new Vertex[MAX_VERTS];
fontscalex = 1.0f;
fontscaley = 1.0f;
}
@ -141,7 +145,7 @@ void DrawBuffer::DrawImageStretch(int atlas_image, float x1, float y1, float x2,
V(x1, y2, color, image.u1, image.v2);
}
// TODO: make into arc
// TODO: add arc support
void DrawBuffer::Circle(float xc, float yc, float radius, float thickness, int segments, float startAngle, uint32 color, float u_mul) {
float angleDelta = PI * 2 / segments;
float uDelta = 1.0f / segments;
@ -153,7 +157,7 @@ void DrawBuffer::Circle(float xc, float yc, float radius, float thickness, int s
float angle2 = (i + 1) * angleDelta;
float u1 = u_mul * i * uDelta;
float u2 = u_mul * (i + 1) * uDelta;
// TODO: get rid of one pair of cos/sin per loop, can reuse
// TODO: get rid of one pair of cos/sin per loop, can reuse from last iteration
float c1 = cosf(angle1), s1 = sinf(angle1), c2 = cosf(angle2), s2 = sinf(angle2);
const float x[4] = {c1 * r1 + xc, c2 * r1 + xc, c1 * r2 + xc, c2 * r2 + xc};
const float y[4] = {s1 * r1 + yc, s2 * r1 + yc, s1 * r2 + yc, s2 * r2 + yc};
@ -284,4 +288,4 @@ void DrawBuffer::EnableBlend(bool enable) {
glEnable(GL_BLEND);
else
glDisable(GL_BLEND);
}
}

View File

@ -1,5 +1,7 @@
#pragma once
// "Immediate mode"-lookalike buffered drawing. Very fast way to draw 2D.
#include "base/basictypes.h"
#include "base/color.h"
@ -33,15 +35,13 @@ struct GradientStop
uint32_t color;
};
// Similar to QuadBuffer but only uses a vertex array that it keeps
// around.
class DrawBuffer {
public:
DrawBuffer();
~DrawBuffer();
void Begin(DrawBufferMode mode = DBMODE_NORMAL);
void End(); // Currently does nothing, but call it!
void End();
int Count() const { return count_; }

View File

@ -1,3 +1,6 @@
// Utility code for loading GLSL shaders.
// Has support for auto-reload, see glsl_refresh
#ifndef _RENDER_UTIL
#define _RENDER_UTIL

View File

@ -1,5 +1,7 @@
#pragma once
// TODO: Actually use for something :)
#include "base/basictypes.h"
// Vertex format flags

View File

@ -1,15 +0,0 @@
# Bring in the environment to use for this component (boilerplate).
Import('env')
# This is the list of input source files to the mandelbrot_gen library. Headers
# will be detected automatically.
inputs = ['png_load.cpp',
'zim_load.cpp',
]
# Build these into a library.
env.ComponentLibrary('image', inputs)
env.Append(LIBS = [ 'base', 'png', 'image', 'z', 'glog' ])
inputs = ['zimagetool.cpp']
env.ComponentProgram('zimagetool', inputs)

View File

@ -1,6 +1,9 @@
#ifndef _GFX_SURFACE
#define _GFX_SURFACE
// UNUSED
enum SurfaceFormats {
SURF_ARGB,
SURF_YUV,

View File

@ -13,7 +13,7 @@
// 4 byte width
// 4 byte height
// 4 byte flags
// The rest is zlibbed data. If multiple mips, they are zlibbed separately.
// Uncompressed or ZLibbed data. If multiple mips, zlibbed separately.
// Defined flags:

View File

@ -182,7 +182,7 @@ uint8_t *DownsampleBy2(const uint8_t *image, int width, int height, int pitch) {
gamma[i] = powf((float)i / 32764.0f, 2.2f) * 255.0f;
}
// Let's start with something really stupid.
// Really stupid mipmap downsampling - at least it does gamma though.
for (int y = 0; y < height; y+=2) {
for (int x = 0; x < width; x+=2) {
const uint8_t *tl = image + pitch * y + x*4;

View File

@ -65,4 +65,4 @@ bool dragDelta(int i, float *xdelta, float *ydelta) {
*ydelta = fingers[i].Y - fingers[i].lastY;
}
}
}

View File

@ -1,5 +1,6 @@
#include "input/input_state.h"
// WIP - doesn't do much yet
// Mainly for detecting (multi-)touch gestures but also useable for left button mouse dragging etc.
namespace GestureDetector
@ -17,4 +18,4 @@ namespace GestureDetector
bool dragDelta(int finger, float *xdelta, float *ydelta);
};
};

View File

@ -41,6 +41,8 @@ struct InputState {
int mouse_buttons_up;
int mouse_last_buttons;
// TODO: Multitouch
// Accelerometer
bool accelerometer_valid;
Vec3 acc;

View File

@ -4,7 +4,6 @@ JsonWriter::JsonWriter() {
}
JsonWriter::~JsonWriter() {
}
void JsonWriter::begin() {

View File

@ -1,14 +1,14 @@
// Minimal-state ultra-minimal JSON writer. Consumes almost no memory
// Minimal-state JSON writer. Consumes almost no memory
// apart from the string being built-up, which could easily be replaced
// with a file stream (although I've chosen not to do that just yet).
//
// Writes nicely 2-spade indented output with correct comma-placement
// Writes nicely 2-space indented output with correct comma-placement
// in arrays and dictionaries.
//
// Does not deal with encodings in any way.
//
// Zero dependencies apart from stdlib.
// Public domain by Henrik Rydgård.
// See json_writer_test.cpp for usage.
#include <string>
#include <vector>

View File

@ -1,8 +0,0 @@
Import('env')
inputs = [
'math_util.cc',
]
env.Append(LIBS = ['gflags', 'glog', ])
env.ComponentLibrary('math_util', inputs, COMPONENT_STATIC=True)

View File

@ -1,5 +1,6 @@
#pragma once
// Delta encoding/decoding - many formats benefit from a pass of this before zlibbing.
// WARNING : Do not use these with floating point data, especially not float16...
template <class T>

View File

@ -1,12 +0,0 @@
Import('env')
inputs = [
'aabb.cc',
'matrix4x4.cc',
'vec3.cc',
'quat.cc',
'ray_intersections.cc',
]
env.Append(LIBS = ['gflags', 'glog', ])
env.ComponentLibrary('lin', inputs, COMPONENT_STATIC=True)

View File

@ -141,7 +141,6 @@ void Matrix4x4::setViewLookAtD3D(const Vec3 &vFrom, const Vec3 &vAt, const Vec3
float Length = vUp.length();
if (1e-6f > Length) {
// EMERGENCY
vUp = Vec3(0.0f, 1.0f, 0.0f) - vView * vView.y;
// If we still have near-zero length, resort to a different axis.
Length = vUp.length();

View File

@ -76,6 +76,7 @@ Quaternion Quaternion::fromMatrix(Matrix4x4 &m)
return q;
};
// TODO: Allegedly, lerp + normalize can achieve almost as good results.
Quaternion Quaternion::slerp(const Quaternion &to, const float a) const {
Quaternion to2;
float angle, cos_angle, scale_from, scale_to, sin_angle;

View File

@ -112,13 +112,6 @@ public:
(*this) = (*this)/len;
return len;
}
/*
float &operator [] (int i) { //allow vector[2] = 3 (vector.z=3)
return *((&x) + i);
}
const float operator [] (const int i) const {
return *((&x) + i);
}*/
bool operator == (const Vec3 &other) const {
if (x==other.x && y==other.y && z==other.z)
return true;

View File

@ -6,8 +6,8 @@
typedef unsigned short float16;
// This ain't a 1.5.10 float16, no sire, it's a stupid hack format where we chop 16 bits off a float.
// This choice is subject to change.
// This ain't a 1.5.10 float16, it's a stupid hack format where we chop 16 bits off a float.
// This choice is subject to change. Don't think I'm using this for anything at all now anyway.
inline float16 FloatToFloat16(float x) {
int ix;
memcpy(&ix, &x, sizeof(float));
@ -26,6 +26,7 @@ inline float Float16ToFloat(float16 ix) {
// The stuff in this file is from all over the web, esp. dspmusic.org. I think it's all public domain.
// In any case, very little of it is used anywhere at the moment.
// PM modulated sine
inline float sine(float t,float f,float ph,float fm) {
return sinf((t*f+ph)*2*PI + 0.5f*PI*fm*(1 - sqrt(f*2)));
}

View File

@ -176,4 +176,4 @@
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>
</Project>

View File

@ -1,5 +1,6 @@
#pragma once
// WIP - very preliminary.
// #define USE_PROFILER
#ifdef USE_PROFILER

View File

@ -1,40 +0,0 @@
#include "util/bits/bits.h"
namespace bits {
// See http://graphics.stanford.edu/~seander/bithacks.html
static const unsigned char BitsSetTable256[] = {
0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4,
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8
};
int CountBits8(uint8 v) {
return BitsSetTable256[v];
}
int CountBits16(uint16 v) {
return BitsSetTable256[v & 0xFF] + BitsSetTable256[v >> 8];
}
int CountBits32(uint32 v) {
v = v - ((v >> 1) & 0x55555555); // reuse input as temporary
v = (v & 0x33333333) + ((v >> 2) & 0x33333333); // temp
return ((v + (v >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; // count
}
} // namespace bits

View File

@ -1,35 +0,0 @@
#include "util/bits/varint.h"
namespace varint {
void Encode32(uint32 value, char **dest) {
// Simple varint
char *p = *dest;
while (value > 127) {
*p++ = (value & 127);
value >>= 7;
}
*p++ = value | 0x80;
*dest = p;
}
uint32 Decode32(const char **ptr) {
uint32 value = 0;
const char *p = *ptr;
while (true) {
uint8 b = *p++;
if (b & 0x80) {
*ptr = p;
return value | (b & 0x7F);
} else {
value |= *p++;
value <<= 7;
}
}
*ptr = p;
return value;
}
} // namespace varint

View File

@ -1,20 +0,0 @@
# Bring in the environment to use for this component (boilerplate).
Import('env')
# This is the list of input source files to the mandelbrot_gen library. Headers
# will be detected automatically.
inputs = ['hash/hash.cc',
'hash/minhash.cc']
# Build these into a library.
env.ComponentLibrary('hash', inputs)
inputs = ['bits/varint.cc',
'bits/bits.cc' ]
env.ComponentLibrary('bits', inputs)
inputs = ['random/perlin.cc',
]
env.ComponentLibrary('random', inputs)

View File

@ -1,65 +0,0 @@
#include "base/base.h"
#include "util/hash/hash.h"
namespace hash {
// uint32_t
// WARNING - may read one more byte!
// Implementation from Wikipedia.
uint32 HashFletcher(const uint8 *data_uint8, size_t length) {
const uint16 *data = (const uint16 *)data_uint8;
size_t len = (length + 1) / 2;
uint32 sum1 = 0xffff, sum2 = 0xffff;
while (len) {
size_t tlen = len > 360 ? 360 : len;
len -= tlen;
do {
sum1 += *data++;
sum2 += sum1;
} while (--tlen);
sum1 = (sum1 & 0xffff) + (sum1 >> 16);
sum2 = (sum2 & 0xffff) + (sum2 >> 16);
}
/* Second reduction step to reduce sums to 16 bits */
sum1 = (sum1 & 0xffff) + (sum1 >> 16);
sum2 = (sum2 & 0xffff) + (sum2 >> 16);
return sum2 << 16 | sum1;
}
// Implementation from Wikipedia
// Slightly slower than Fletcher above, but slighly more reliable.
#define MOD_ADLER 65521
// data: Pointer to the data to be summed; len is in bytes
uint32 HashAdler32(const uint8 *data, size_t len) {
uint32 a = 1, b = 0;
while (len) {
size_t tlen = len > 5550 ? 5550 : len;
len -= tlen;
do {
a += *data++;
b += a;
} while (--tlen);
a = (a & 0xffff) + (a >> 16) * (65536 - MOD_ADLER);
b = (b & 0xffff) + (b >> 16) * (65536 - MOD_ADLER);
}
// It can be shown that a <= 0x1013a here, so a single subtract will do.
if (a >= MOD_ADLER) {
a -= MOD_ADLER;
}
// It can be shown that b can reach 0xfff87 here.
b = (b & 0xffff) + (b >> 16) * (65536 - MOD_ADLER);
if (b >= MOD_ADLER) {
b -= MOD_ADLER;
}
return (b << 16) | a;
}
} // namespace hash

View File

@ -10,21 +10,6 @@ namespace hash {
uint32 Fletcher(const uint8 *data_u8, size_t length); // FAST. Length & 1 == 0.
uint32 Adler32(const uint8 *data, size_t len); // Fairly accurate, slightly slower
// WTF is this for?
class ConsistentHasher {
public:
ConsistentHasher() {
// TODO: really need a better seed here.
uint32 orig_seed = rand();
seed = Fletcher((const uint8 *)&orig_seed, 4);
}
uint32 Hash(uint32 value) {
return value ^ seed;
}
private:
uint32 seed;
};
} // namespace hash
#endif

View File

@ -1,72 +0,0 @@
#include "util/random/perlin.h"
#include <math.h>
// This should go in the const section of the binary.
static const int p[512] = {
151,160,137,91,90,15,
131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23,
190, 6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33,
88,237,149,56,87,174,20,125,136,171,168, 68,175,74,165,71,134,139,48,27,166,
77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244,
102,143,54, 65,25,63,161, 1,216,80,73,209,76,132,187,208, 89,18,169,200,196,
135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,250,124,123,
5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42,
223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167, 43,172,9,
129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218,246,97,228,
251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107,
49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254,
138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180,
151,160,137,91,90,15,
131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23,
190, 6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33,
88,237,149,56,87,174,20,125,136,171,168, 68,175,74,165,71,134,139,48,27,166,
77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244,
102,143,54, 65,25,63,161, 1,216,80,73,209,76,132,187,208, 89,18,169,200,196,
135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,250,124,123,
5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42,
223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167, 43,172,9,
129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218,246,97,228,
251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107,
49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254,
138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180,
};
inline float fade(float t) {
return t * t * t * (t * (t * 6 - 15) + 10);
}
inline float lerp(float t, float a, float b) {
return a + t * (b - a);
}
inline float grad(int hash, float x, float y, float z) {
int h = hash & 15; // CONVERT LO 4 BITS OF HASH CODE
float u = h < 8 ? x : y; // INTO 12 GRADIENT DIRECTIONS.
float v = h < 4 ? y : (h == 12 || h == 14 ? x : z);
return ((h & 1) == 0 ? u : -u) + ((h & 2) == 0 ? v : -v);
}
float Noise(double z, double y, double x) {
double fx = floor(x), fy = floor(y), fz = floor(z);
int X = (int)fx & 255, // FIND UNIT CUBE THAT
Y = (int)fy & 255, // CONTAINS POINT.
Z = (int)fz & 255;
x -= fx; // FIND RELATIVE X,Y,Z
y -= fy; // OF POINT IN CUBE.
z -= fz;
float u = fade(x); // COMPUTE FADE CURVES
float v = fade(y); // FOR EACH OF X,Y,Z.
float w = fade(z);
int A = p[X ]+Y, B = p[X+1]+Y;
int AA = p[A]+Z, AB = p[A+1]+Z; // HASH COORDINATES OF
int BA = p[B]+Z, BB = p[B+1]+Z; // THE 8 CUBE CORNERS,
return lerp(w, lerp(v, lerp(u, grad(p[AA ], x , y , z ), // AND ADD
grad(p[BA ], x-1, y , z )), // BLENDED
lerp(u, grad(p[AB ], x , y-1, z ), // RESULTS
grad(p[BB ], x-1, y-1, z ))), // FROM 8
lerp(v, lerp(u, grad(p[AA+1], x , y , z-1 ), // CORNERS
grad(p[BA+1], x-1, y , z-1 )), // OF CUBE
lerp(u, grad(p[AB+1], x , y-1, z-1 ),
grad(p[BB+1], x-1, y-1, z-1 ))));
}