Started to merge @ZobyTwo cmake branch

This commit is contained in:
xawotihs
2015-09-26 21:52:07 +02:00
parent 9e77899535
commit 85f4a4c36a
3112 changed files with 4615 additions and 9 deletions

View File

@@ -15,7 +15,7 @@
#include "../include/JSprite.h"
#include "../include/JAnimator.h"
#include "tinyxml/tinyxml.h"
#include "tinyxml.h"
//////////////////////////////////////////////////////////////////////////

View File

@@ -19,7 +19,7 @@
#include "../include/JFileSystem.h"
#include "../include/JResourceManager.h"
#include "tinyxml/tinyxml.h"
#include "tinyxml.h"
//-------------------------------------------------------------------------------------

View File

@@ -14,7 +14,7 @@
#include "../include/JResourceManager.h"
#include "../include/JFileSystem.h"
#include "../include/JLBFont.h"
#include "tinyxml/tinyxml.h"
#include "tinyxml.h"
#if defined (_DEBUG) && defined (WIN32) && (!defined LINUX)
#include "crtdbg.h"

View File

@@ -13,7 +13,7 @@
#include "../include/JFileSystem.h"
#include "../include/JSpline.h"
#include "tinyxml/tinyxml.h"
#include "tinyxml.h"
#define SMALL_NUMBER 0.0001f

View File

@@ -1,105 +0,0 @@
#include "../include/JGE.h"
#include "../include/JTypes.h"
#include "../include/JApp.h"
#include "../include/JFileSystem.h"
#include "../include/JRenderer.h"
#include "../include/JGameLauncher.h"
#include "TestSuiteAI.h"
#include "GameOptions.h"
#include "MTGDeck.h"
#include "DebugRoutines.h"
#include <QCoreApplication>
#include <QElapsedTimer>
class WagicWrapper
{
public:
WagicWrapper();
virtual ~WagicWrapper();
public:
// used mainly to mesure the delta between 2 updates
static QElapsedTimer g_startTimer;
private:
JGE* m_engine;
JApp* m_app;
JGameLauncher* m_launcher;
};
QElapsedTimer WagicWrapper::g_startTimer;
int JGEGetTime()
{
return (int)WagicWrapper::g_startTimer.elapsed();
}
bool JGEToggleFullscreen()
{
return true;
}
void JGECreateDefaultBindings()
{
}
WagicWrapper::WagicWrapper()
{
m_launcher = new JGameLauncher();
u32 flags = m_launcher->GetInitFlags();
if ((flags&JINIT_FLAG_ENABLE3D)!=0)
{
JRenderer::Set3DFlag(true);
}
JGECreateDefaultBindings();
m_engine = JGE::GetInstance();
m_app = m_launcher->GetGameApp();
m_app->Create();
m_engine->SetApp(m_app);
JRenderer::GetInstance()->Enable2D();
g_startTimer.restart();
}
WagicWrapper::~WagicWrapper()
{
if(m_launcher)
{
delete m_launcher;
m_launcher = NULL;
}
if(m_engine)
m_engine->SetApp(NULL);
if (m_app)
{
m_app->Destroy();
delete m_app;
m_app = NULL;
}
JGE::Destroy();
m_engine = NULL;
}
int main(int argc, char* argv[])
{
QCoreApplication a(argc, argv);
int result = 0;
WagicWrapper* wagicCore = new WagicWrapper();
MTGCollection()->loadFolder("sets/primitives/");
MTGCollection()->loadFolder("sets/", "_cards.dat");
options.reloadProfile();
TestSuite testSuite("test/_tests.txt");
result = testSuite.run();
delete wagicCore;
DebugTrace("TestSuite done: failed test: " << result << " out of " << testSuite.nbTests + testSuite.nbAITests << " total");
#ifdef CAPTURE_STDERR
OutputCapturer::debugAndClear();
#endif
return result;
}

View File

@@ -1,109 +0,0 @@
#define GL_GLEXT_PROTOTYPES
#include <QtOpenGL>
#include <QTime>
#include <QApplication>
#include <QScopedPointer>
#ifdef QT_WIDGET
#include <QWidget>
#else
#include <QtDeclarative>
#include "qmlapplicationviewer.h"
#endif //QT_WIDGET
#include "Downloader.h"
#include "GameApp.h"
#include "corewrapper.h"
WagicCore* g_glwidget = NULL;
static const struct { LocalKeySym keysym; JButton keycode; } gDefaultBindings[] =
{
{ Qt::Key_Enter, JGE_BTN_MENU },
{ Qt::Key_Return, JGE_BTN_MENU },
{ Qt::Key_Escape, JGE_BTN_MENU },
{ Qt::Key_Backspace, JGE_BTN_CTRL },
{ Qt::Key_Up, JGE_BTN_UP },
{ Qt::Key_Down, JGE_BTN_DOWN },
{ Qt::Key_Left, JGE_BTN_LEFT },
{ Qt::Key_Right, JGE_BTN_RIGHT },
{ Qt::Key_Space, JGE_BTN_OK },
{ Qt::Key_Tab, JGE_BTN_CANCEL },
{ Qt::Key_J, JGE_BTN_PRI },
{ Qt::Key_K, JGE_BTN_SEC },
{ Qt::Key_Q, JGE_BTN_PREV },
{ Qt::Key_A, JGE_BTN_NEXT },
// fullscreen management seems somehow broken in JGE, it works fine with Qt directly
// { Qt::Key_F, JGE_BTN_FULLSCREEN },
};
void JGECreateDefaultBindings()
{
for (signed int i = sizeof(gDefaultBindings)/sizeof(gDefaultBindings[0]) - 1; i >= 0; --i)
JGE::BindKey(gDefaultBindings[i].keysym, gDefaultBindings[i].keycode);
}
bool JGEToggleFullscreen()
{
if(g_glwidget->isFullScreen())
{
g_glwidget->showNormal();
}
else
{
g_glwidget->showFullScreen();
}
return true;
}
int JGEGetTime()
{
return (int)WagicCore::g_startTimer.elapsed();
}
int main(int argc, char* argv[])
{
QScopedPointer<QApplication> app
#ifdef QT_WIDGET
(new QApplication(argc, argv));
#else
(createApplication(argc, argv));
#endif //QT_WIDGET
app->setApplicationName(WagicCore::getApplicationName());
DownloadRequest* downloadRequest = NULL;
#ifdef WAGIC_RESOURCE_URL
Downloader*downloader = Downloader::GetInstance();
downloadRequest = downloader->Get(
"core.zip",
WAGIC_RESOURCE_URL
);
#endif
#ifdef QT_WIDGET
g_glwidget = new WagicCore();
if(!downloadRequest || downloadRequest->getDownloadStatus() == DownloadRequest::DOWNLOADED)
{
g_glwidget->start(0);
}
else
{
g_glwidget->connect(downloadRequest, SIGNAL(statusChanged(int)), SLOT(start(int)));
}
#else
qmlRegisterType<WagicCore>("CustomComponents", 1, 0, "WagicCore");
QScopedPointer<QmlApplicationViewer> viewer(QmlApplicationViewer::create());
g_glwidget = viewer.data();
viewer->rootContext()->setContextProperty("fileDownloader", &fileDownloader);
viewer->setMainQmlFile(QLatin1String("qml/QmlWagic/main.qml"));
viewer->setOrientation(QmlApplicationViewer::ScreenOrientationAuto);
QGLWidget *glWidget = new QGLWidget;
viewer->setViewport(glWidget);
viewer->showExpanded();
viewer->setResizeMode(QDeclarativeView::SizeRootObjectToView);
#endif //QT_WIDGET
return app->exec();
}

View File

@@ -1,771 +0,0 @@
#include <SDL.h>
#if (defined ANDROID)
#include <SDL_opengles.h>
#else
#include <SDL_opengl.h>
#ifdef WIN32
#undef GL_VERSION_2_0
#endif
#endif
#include "../include/JGE.h"
#include "../include/JTypes.h"
#include "../include/JApp.h"
#include "../include/JFileSystem.h"
#include "../include/JRenderer.h"
#include "../include/JGameLauncher.h"
#include "DebugRoutines.h"
#include <stdexcept>
#include <iostream>
#include <math.h>
#if (defined FORCE_GLES)
#undef GL_ES_VERSION_2_0
#undef GL_VERSION_2_0
#define GL_VERSION_ES_CM_1_1 1
#define glOrthof glOrtho
#define glClearDepthf glClearDepth
#endif
#define ACTUAL_SCREEN_WIDTH (SCREEN_WIDTH)
#define ACTUAL_SCREEN_HEIGHT (SCREEN_HEIGHT)
#define ACTUAL_RATIO ((GLfloat)ACTUAL_SCREEN_WIDTH / (GLfloat)ACTUAL_SCREEN_HEIGHT)
enum eDisplayMode
{
DisplayMode_lowRes = 0,
DisplayMode_hiRes,
DisplayMode_fullscreen
};
unsigned int gDisplayMode = DisplayMode_lowRes;
const int kHitzonePliancy = 50;
// tick value equates to ms
const int kTapEventTimeout = 250;
uint64_t lastTickCount;
JGE* g_engine = NULL;
JApp* g_app = NULL;
JGameLauncher* g_launcher = NULL;
#ifdef ANDROID
JNIEnv * mJNIEnv = NULL;
jclass * mJNIClass = NULL;
#endif
class SdlApp;
SdlApp *g_SdlApp = NULL;
#ifdef ANDROID
// Pause
extern "C" void Java_org_libsdl_app_SDLActivity_nativePause(
JNIEnv* env, jclass cls)
{
DebugTrace("Attempt pause");
if (!g_engine)
return;
g_engine->Pause();
DebugTrace("Pause done");
}
// Resume
extern "C" void Java_org_libsdl_app_SDLActivity_nativeResume(
JNIEnv* env, jclass cls)
{
if (!g_engine)
return;
g_engine->Resume();
}
#include "Wagic_Version.h"
extern "C" jstring Java_org_libsdl_app_SDLActivity_getResourceName(
JNIEnv* env, jclass cls)
{
return env->NewStringUTF (WAGIC_RESOURCE_NAME);
}
extern "C" jstring Java_org_libsdl_app_SDLActivity_getResourceUrl(
JNIEnv* env, jclass cls)
{
return env->NewStringUTF (WAGIC_RESOURCE_URL);
}
#endif
class SdlApp
{
public: /* For easy interfacing with JGE static functions */
bool Running;
SDL_Window* window;
SDL_Surface* Surf_Display;
SDL_Rect viewPort;
Uint32 lastMouseUpTime;
Uint32 lastFingerDownTime;
int windowed_w;
int windowed_h;
int windowed_pos_x;
int windowed_pos_y;
int mMouseDownX;
int mMouseDownY;
public:
SdlApp() : Surf_Display(NULL), window(NULL), lastMouseUpTime(0), lastFingerDownTime(0), Running(true), mMouseDownX(0), mMouseDownY(0)
{
}
int OnExecute()
{
if (OnInit() == false)
{
return -1;
}
SDL_Event Event;
while(Running)
{
if (g_engine)
{
for (int x = 0; x < 5 && SDL_WaitEventTimeout(&Event, 10); ++x)
{
if(!g_engine->IsPaused())
OnEvent(&Event);
}
if(!g_engine->IsPaused())
OnUpdate();
}
}
OnCleanup();
return 0;
};
public:
bool OnInit();
void OnResize(int width, int height)
{
DebugTrace("OnResize Width " << width << " height " << height);
if ((GLfloat)width / (GLfloat)height <= ACTUAL_RATIO)
{
viewPort.x = 0;
viewPort.y = -(static_cast<int>(width / ACTUAL_RATIO) - height) / 2;
viewPort.w = width;
viewPort.h = static_cast<int>(width / ACTUAL_RATIO);
}
else
{
viewPort.x = -(static_cast<int>(height * ACTUAL_RATIO) - width) / 2;
viewPort.y = 0;
viewPort.w = static_cast<int>(height * ACTUAL_RATIO);
viewPort.h = height;
}
glViewport(viewPort.x, viewPort.y, viewPort.w, viewPort.h);
JRenderer::GetInstance()->SetActualWidth(static_cast<float>(viewPort.w));
JRenderer::GetInstance()->SetActualHeight(static_cast<float>(viewPort.h));
glScissor(0, 0, width, height);
#if (!defined GL_ES_VERSION_2_0) && (!defined GL_VERSION_2_0)
glMatrixMode (GL_PROJECTION); // Select The Projection Matrix
glLoadIdentity (); // Reset The Projection Matrix
#if (defined GL_VERSION_ES_CM_1_1)
glOrthof(0.0f, (float) (viewPort.w)-1.0f, 0.0f, (float) (viewPort.h)-1.0f, -1.0f, 1.0f);
#else
gluOrtho2D(0.0f, (float) (viewPort.w)-1.0f, 0.0f, (float) (viewPort.h)-1.0f);
#endif
glMatrixMode (GL_MODELVIEW); // Select The Modelview Matrix
glLoadIdentity (); // Reset The Modelview Matrix
glDisable (GL_DEPTH_TEST);
#endif
}
void OnKeyPressed(const SDL_KeyboardEvent& event);
void OnMouseDoubleClicked(const SDL_MouseButtonEvent& event);
void OnMouseClicked(const SDL_MouseButtonEvent& event);
void OnMouseMoved(const SDL_MouseMotionEvent& event);
void OnMouseWheel(int x, int y);
void OnTouchEvent(const SDL_TouchFingerEvent& event);
void OnEvent(SDL_Event* Event)
{
/* if(Event->type < SDL_USEREVENT)
DebugTrace("Event received" << Event->type);*/
switch(Event->type)
{
case SDL_QUIT:
Running = false;
break;
/* On Android, this is triggered when the device orientation changed */
case SDL_WINDOWEVENT:
window = SDL_GetWindowFromID(Event->window.windowID);
int h,w;
SDL_GetWindowSize(window, &w, &h);
OnResize(w, h);
break;
case SDL_KEYDOWN:
case SDL_KEYUP:
OnKeyPressed(Event->key);
break;
case SDL_MOUSEMOTION:
OnMouseMoved(Event->motion);
break;
case SDL_MOUSEBUTTONDOWN:
OnMouseClicked(Event->button);
break;
case SDL_MOUSEBUTTONUP:
{
Uint32 eventTime = SDL_GetTicks();
if (eventTime - lastMouseUpTime <= 500)
{
OnMouseDoubleClicked(Event->button);
}
else
{
OnMouseClicked(Event->button);
}
lastMouseUpTime = eventTime;
}
break;
case SDL_MOUSEWHEEL:
OnMouseWheel(Event->wheel.x, Event->wheel.y);
break;
case SDL_FINGERMOTION:
case SDL_FINGERDOWN:
case SDL_FINGERUP:
DebugTrace("Finger Up/Down/Motion detected:" );
OnTouchEvent(Event->tfinger);
break;
case SDL_MULTIGESTURE:
DebugTrace("Multigesture : touchId " << Event->mgesture.touchId
<< ", x " << Event->mgesture.x
<< ", y " << Event->mgesture.y
<< ", dTheta " << Event->mgesture.dTheta
<< ", dDist " << Event->mgesture.dDist
<< ", numFingers " << Event->mgesture.numFingers);
break;
case SDL_JOYBALLMOTION:
DebugTrace("Flick gesture detected, x: " << Event->jball.xrel << ", y: " << Event->jball.yrel);
g_engine->Scroll(Event->jball.xrel, Event->jball.yrel);
break;
}
}
void OnUpdate();
void OnCleanup()
{
SDL_FreeSurface(Surf_Display);
SDL_Quit();
}
};
static const struct { LocalKeySym keysym; JButton keycode; } gDefaultBindings[] =
{
/* windows controls */
{ SDLK_LCTRL, JGE_BTN_CTRL },
{ SDLK_RCTRL, JGE_BTN_CTRL },
{ SDLK_RETURN, JGE_BTN_MENU },
{ SDLK_KP_ENTER, JGE_BTN_MENU },
{ SDLK_ESCAPE, JGE_BTN_MENU },
{ SDLK_UP, JGE_BTN_UP },
{ SDLK_DOWN, JGE_BTN_DOWN },
{ SDLK_LEFT, JGE_BTN_LEFT },
{ SDLK_RIGHT, JGE_BTN_RIGHT },
{ SDLK_z, JGE_BTN_UP },
{ SDLK_d, JGE_BTN_RIGHT },
{ SDLK_s, JGE_BTN_DOWN },
{ SDLK_q, JGE_BTN_LEFT },
{ SDLK_a, JGE_BTN_PREV },
{ SDLK_e, JGE_BTN_NEXT },
{ SDLK_i, JGE_BTN_CANCEL },
{ SDLK_l, JGE_BTN_OK },
{ SDLK_SPACE, JGE_BTN_OK },
{ SDLK_k, JGE_BTN_SEC },
{ SDLK_j, JGE_BTN_PRI },
{ SDLK_f, JGE_BTN_FULLSCREEN },
/* old Qt ones, basically modified to comply with the N900 keyboard
{ SDLK_a, JGE_BTN_NEXT },
{ SDLK_TAB, JGE_BTN_CANCEL },
{ SDLK_q, JGE_BTN_PREV },
{ SDLK_BACKSPACE, JGE_BTN_CTRL },
*/
/* Android customs */
{ SDLK_AC_BACK, JGE_BTN_MENU },
/* Android/maemo volume button mapping */
{ SDLK_VOLUMEUP, JGE_BTN_PREV },
{ SDLK_VOLUMEDOWN, JGE_BTN_SEC},
};
void JGECreateDefaultBindings()
{
for (signed int i = sizeof(gDefaultBindings)/sizeof(gDefaultBindings[0]) - 1; i >= 0; --i)
g_engine->BindKey(gDefaultBindings[i].keysym, gDefaultBindings[i].keycode);
}
int JGEGetTime()
{
return (int)SDL_GetTicks();
}
bool JGEToggleFullscreen()
{
//cycle between the display modes
++gDisplayMode;
if (gDisplayMode > DisplayMode_fullscreen)
gDisplayMode = DisplayMode_lowRes;
SDL_DisplayMode mode;
SDL_GetCurrentDisplayMode(0, &mode);
int width = 0;
int height = 0;
switch (gDisplayMode)
{
case DisplayMode_fullscreen:
SDL_SetWindowSize(g_SdlApp->window, mode.w, mode.h);
return (SDL_SetWindowFullscreen(g_SdlApp->window, SDL_TRUE) == 0);
break;
case DisplayMode_hiRes:
width = SCREEN_WIDTH * 2;
height = SCREEN_HEIGHT * 2;
break;
case DisplayMode_lowRes:
default:
width = SCREEN_WIDTH;
height = SCREEN_HEIGHT;
break;
}
if (SDL_SetWindowFullscreen(g_SdlApp->window, SDL_FALSE) < 0)
{
return false;
}
int x = (mode.w - width) / 2;
int y = (mode.h - height) / 2;
SDL_SetWindowPosition(g_SdlApp->window, x, y);
SDL_SetWindowSize(g_SdlApp->window, width, height);
return true;
}
bool InitGame(void)
{
g_engine = JGE::GetInstance();
g_app = g_launcher->GetGameApp();
g_app->Create();
g_engine->SetApp(g_app);
#ifdef ANDROID
DebugTrace("Can I Set JNI Params ?");
if (mJNIEnv)
DebugTrace("mJNIEnv is ok");
if (mJNIEnv && mJNIClass)
{
DebugTrace("Setting JNI Params");
g_engine->SetJNIEnv(mJNIEnv, *mJNIClass);
}
#endif
JRenderer::GetInstance()->Enable2D();
lastTickCount = JGEGetTime();
return true;
}
void DestroyGame(void)
{
g_engine->SetApp(NULL);
if (g_app)
{
g_app->Destroy();
delete g_app;
g_app = NULL;
}
JGE::Destroy();
g_engine = NULL;
}
void SdlApp::OnUpdate()
{
static int tickCount = 0;
tickCount = JGEGetTime();
int64_t dt = (tickCount - lastTickCount);
lastTickCount = tickCount;
if(g_engine->IsDone())
{
SDL_Event event;
event.user.type = SDL_QUIT;
SDL_PushEvent(&event);
}
try
{
g_engine->SetDelta((float)dt / 1000.0f);
g_engine->Update((float)dt / 1000.0f);
}
catch(out_of_range& oor)
{
cerr << oor.what();
}
if(g_engine)
g_engine->Render();
SDL_GL_SwapBuffers();
}
void SdlApp::OnKeyPressed(const SDL_KeyboardEvent& event)
{
if (event.type == SDL_KEYDOWN)
{
g_engine->HoldKey_NoRepeat((LocalKeySym)event.keysym.sym);
}
else if(event.type == SDL_KEYUP)
{
g_engine->ReleaseKey((LocalKeySym)event.keysym.sym);
}
}
void SdlApp::OnMouseMoved(const SDL_MouseMotionEvent& event)
{
int actualWidth = (int) JRenderer::GetInstance()->GetActualWidth();
int actualHeight = (int) JRenderer::GetInstance()->GetActualHeight();
if (event.y >= viewPort.y &&
event.y <= viewPort.y + viewPort.h &&
event.x >= viewPort.x &&
event.x <= viewPort.x + viewPort.w)
{
g_engine->LeftClicked(
((event.x-viewPort.x)*SCREEN_WIDTH)/actualWidth,
((event.y-viewPort.y)*SCREEN_HEIGHT)/actualHeight);
}
}
void SdlApp::OnMouseDoubleClicked(const SDL_MouseButtonEvent& event)
{
#if (defined ANDROID) || (defined IOS)
if(event.button == SDL_BUTTON_LEFT) /* Left button */
{
g_engine->HoldKey_NoRepeat(JGE_BTN_OK);
}
#endif
}
void SdlApp::OnMouseWheel(int x, int y)
{
if(!x && y)
{ // Vertical wheel
if(y > 0)
{
g_engine->HoldKey_NoRepeat(JGE_BTN_UP);
}
else
{
g_engine->HoldKey_NoRepeat(JGE_BTN_DOWN);
}
}
else if(x && !y)
{ // Horizontal wheel
g_engine->HoldKey_NoRepeat(JGE_BTN_LEFT);
}
else
{
g_engine->HoldKey_NoRepeat(JGE_BTN_RIGHT);
}
}
void SdlApp::OnMouseClicked(const SDL_MouseButtonEvent& event)
{
if (event.type == SDL_MOUSEBUTTONDOWN)
{
if (event.button == SDL_BUTTON_LEFT) /* Left button */
{
// this is intended to convert window coordinate into game coordinate.
// this is correct only if the game and window have the same aspect ratio, otherwise, it's just wrong
int actualWidth = (int) JRenderer::GetInstance()->GetActualWidth();
int actualHeight = (int) JRenderer::GetInstance()->GetActualHeight();
if (event.y >= viewPort.y &&
event.y <= viewPort.y + viewPort.h &&
event.x >= viewPort.x &&
event.x <= viewPort.x + viewPort.w)
{
g_engine->LeftClicked(
((event.x-viewPort.x)*SCREEN_WIDTH)/actualWidth,
((event.y-viewPort.y)*SCREEN_HEIGHT)/actualHeight);
#if (!defined ANDROID) && (!defined IOS)
g_engine->HoldKey_NoRepeat(JGE_BTN_OK);
#endif
}
else if(event.y < viewPort.y)
{
g_engine->HoldKey_NoRepeat(JGE_BTN_MENU);
}
else if(event.y > viewPort.y + viewPort.h)
{
g_engine->HoldKey_NoRepeat(JGE_BTN_NEXT);
}
}
else if(event.button == SDL_BUTTON_RIGHT) /* Right button */
{ /* next phase please */
g_engine->HoldKey_NoRepeat(JGE_BTN_PREV);
}
else if(event.button == SDL_BUTTON_MIDDLE) /* Middle button */
{ /* interrupt please */
g_engine->HoldKey_NoRepeat(JGE_BTN_SEC);
}
}
else if (event.type == SDL_MOUSEBUTTONUP)
{
if(event.button == SDL_BUTTON_LEFT)
{
if (event.y >= viewPort.y &&
event.y <= viewPort.y + viewPort.h &&
event.x >= viewPort.x &&
event.x <= viewPort.x + viewPort.w)
{
#if (!defined ANDROID) && (!defined IOS)
g_engine->ReleaseKey(JGE_BTN_OK);
#endif
}
else if(event.y < viewPort.y)
{
g_engine->ReleaseKey(JGE_BTN_MENU);
}
else if(event.y > viewPort.y + viewPort.h)
{
g_engine->ReleaseKey(JGE_BTN_NEXT);
}
}
else if(event.button == SDL_BUTTON_RIGHT)
{ /* next phase please */
g_engine->ReleaseKey(JGE_BTN_PREV);
}
else if(event.button == SDL_BUTTON_MIDDLE)
{ /* interrupt please */
g_engine->ReleaseKey(JGE_BTN_SEC);
}
}
}
void SdlApp::OnTouchEvent(const SDL_TouchFingerEvent& event)
{
// only respond to the first finger for mouse type movements - any additional finger
// should be ignored, and will come through instead as a multigesture event
if (event.fingerId == 0)
{
if (event.y >= viewPort.y &&
event.y <= viewPort.y + viewPort.h &&
event.x >= viewPort.x &&
event.x <= viewPort.x + viewPort.w)
{
int actualWidth = (int) JRenderer::GetInstance()->GetActualWidth();
int actualHeight = (int) JRenderer::GetInstance()->GetActualHeight();
Uint32 eventTime = SDL_GetTicks();
if (event.type == SDL_FINGERDOWN)
{
mMouseDownX = event.x;
mMouseDownY = event.y;
lastFingerDownTime = eventTime;
}
#if (defined ANDROID) || (defined IOS)
if (event.type == SDL_FINGERUP)
{
if (eventTime - lastFingerDownTime <= kTapEventTimeout)
{
// treat an up finger within 50 pixels of the down finger coords as a double click event
if (abs(mMouseDownX - event.x) < kHitzonePliancy && abs(mMouseDownY - event.y) < kHitzonePliancy)
{
DebugTrace("Pressing OK BUtton");
g_engine->HoldKey_NoRepeat(JGE_BTN_OK);
}
}
}
else
#endif
g_engine->LeftClicked(
((event.x - viewPort.x) * SCREEN_WIDTH) / actualWidth,
((event.y - viewPort.y) * SCREEN_HEIGHT) / actualHeight);
}
}
}
bool SdlApp::OnInit()
{
int window_w, window_h;
if(SDL_Init(SDL_INIT_EVERYTHING) < 0)
{
return false;
}
const SDL_VideoInfo *pVideoInfo = SDL_GetVideoInfo();
DebugTrace("Video Display : h " << pVideoInfo->current_h << ", w " << pVideoInfo->current_w);
#if (defined ANDROID) || (defined IOS)
window_w = pVideoInfo->current_w;
window_h = pVideoInfo->current_h;
#else
window_w = ACTUAL_SCREEN_WIDTH;
window_h = ACTUAL_SCREEN_HEIGHT;
#endif
SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);
SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, 32);
SDL_GL_SetAttribute(SDL_GL_ACCUM_RED_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_ACCUM_GREEN_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_ACCUM_BLUE_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_ACCUM_ALPHA_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 2);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 1);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
if((Surf_Display = SDL_SetVideoMode(window_w, window_h, 32,
#ifdef ANDROID
SDL_OPENGL | SDL_FULLSCREEN | SDL_WINDOW_BORDERLESS)) == NULL)
{
#else
SDL_OPENGL | SDL_RESIZABLE )) == NULL)
{
#endif
return false;
}
SDL_WM_SetCaption(g_launcher->GetName(), "");
glClearColor(0.0f, 0.0f, 0.0f, 0.0f); // Black Background (yes that's the way fuckers)
#if (defined GL_ES_VERSION_2_0) || (defined GL_VERSION_2_0)
#if (defined GL_ES_VERSION_2_0)
glClearDepthf(1.0f); // Depth Buffer Setup
#else
glClearDepth(1.0f); // Depth Buffer Setup
#endif// (defined GL_ES_VERSION_2_0)
glDepthFunc(GL_LEQUAL); // The Type Of Depth Testing (Less Or Equal)
glEnable(GL_DEPTH_TEST); // Enable Depth Testing
#else
#if (defined GL_VERSION_ES_CM_1_1)
glClearDepthf(1.0f); // Depth Buffer Setup
#else
glClearDepth(1.0f); // Depth Buffer Setup
#endif
glDepthFunc(GL_LEQUAL); // The Type Of Depth Testing (Less Or Equal)
glEnable(GL_DEPTH_TEST); // Enable Depth Testing
glShadeModel(GL_SMOOTH); // Select Smooth Shading
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); // Set Perspective Calculations To Most Accurate
glHint(GL_LINE_SMOOTH_HINT, GL_NICEST); // Set Line Antialiasing
glEnable(GL_LINE_SMOOTH); // Enable it!
glEnable(GL_TEXTURE_2D);
#endif
glEnable(GL_CULL_FACE); // do not calculate inside of poly's
glFrontFace(GL_CCW); // counter clock-wise polygons are out
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_SCISSOR_TEST); // Enable Clipping
JGECreateDefaultBindings();
if (!InitGame())
{
cerr << "Could not init the game\n";
return false;
}
OnResize(window_w, window_h);
return true;
};
#if (defined ANDROID) || (defined WIN32)
int SDL_main(int argc, char * argv[])
#else
int main(int argc, char* argv[])
#endif //ANDROID
{
#if (defined ANDROID)
if (argc > 2)
{
mJNIEnv = (JNIEnv * )argv[1];
mJNIClass = (jclass * )argv[2];
}
#endif
DebugTrace("I R in da native");
g_launcher = new JGameLauncher();
u32 flags = g_launcher->GetInitFlags();
if ((flags&JINIT_FLAG_ENABLE3D)!=0)
{
JRenderer::Set3DFlag(true);
}
g_SdlApp = new SdlApp();
int result = g_SdlApp->OnExecute();
if (g_launcher)
delete g_launcher;
if(g_SdlApp)
delete g_SdlApp;
// Shutdown
DestroyGame();
return result;
}

View File

@@ -1,414 +0,0 @@
#include <unistd.h>
#include <GL/gl.h> // Header File For The OpenGL32 Library
#include <GL/glu.h> // Header File For The GLu32 Library
#include <GL/glx.h>
#include <X11/XKBlib.h>
#include <sys/time.h>
#include <queue>
#include <map>
#include <set>
#include <iostream>
#include "../../JGE/include/JGE.h"
#include "../../JGE/include/JTypes.h"
#include "../../JGE/include/JApp.h"
#include "../../JGE/include/JFileSystem.h"
#include "../../JGE/include/JRenderer.h"
#include "../../JGE/include/JGameLauncher.h"
#define ACTUAL_SCREEN_WIDTH (SCREEN_WIDTH)
#define ACTUAL_SCREEN_HEIGHT (SCREEN_HEIGHT)
#define ACTUAL_RATIO ((GLfloat)ACTUAL_SCREEN_WIDTH / (GLfloat)ACTUAL_SCREEN_HEIGHT)
struct window_state_t
{
bool fullscreen;
int width;
int height;
int x;
int y;
} window_state = { false, ACTUAL_SCREEN_WIDTH, ACTUAL_SCREEN_HEIGHT, 0, 0 };
enum
{
_NET_WM_STATE_REMOVE =0,
_NET_WM_STATE_ADD = 1,
_NET_WM_STATE_TOGGLE =2
};
uint64_t lastTickCount;
//------------------------------------------------------------------------
JGE* g_engine = NULL;
JApp* g_app = NULL;
JGameLauncher* g_launcher = NULL;
//------------------------------------------------------------------------
Display* gXDisplay = NULL;
Window gXWindow = (Window)NULL;
GLXWindow glxWin = (GLXWindow)NULL;
static std::multiset<JButton> gControllerState;
static std::multiset<JButton> gPrevControllerState;
static const struct { LocalKeySym keysym; JButton keycode; } gDefaultBindings[] =
{
{ XK_Escape, JGE_BTN_MENU },
{ XK_Return, JGE_BTN_MENU },
{ XK_BackSpace, JGE_BTN_CTRL },
{ XK_Up, JGE_BTN_UP },
{ XK_KP_Up, JGE_BTN_UP },
{ XK_Down, JGE_BTN_DOWN },
{ XK_KP_Down, JGE_BTN_DOWN },
{ XK_Left, JGE_BTN_LEFT },
{ XK_KP_Left, JGE_BTN_LEFT },
{ XK_Right, JGE_BTN_RIGHT },
{ XK_KP_Right, JGE_BTN_RIGHT },
{ XK_space, JGE_BTN_OK },
{ XK_Control_L, JGE_BTN_OK },
{ XK_Control_R, JGE_BTN_OK },
{ XK_Tab, JGE_BTN_CANCEL },
{ XK_Mode_switch, JGE_BTN_PRI },
{ XK_Caps_Lock, JGE_BTN_SEC },
{ XK_Shift_L, JGE_BTN_PREV },
{ XK_Shift_R, JGE_BTN_NEXT },
{ XK_F, JGE_BTN_FULLSCREEN },
};
GLvoid ReSizeGLScene(GLsizei width, GLsizei height) // Resize The GL Window
{
if ((GLfloat)width / (GLfloat)height < ACTUAL_RATIO)
glViewport(0, -((width/ACTUAL_RATIO)-height)/2, width, width / ACTUAL_RATIO); // Reset The Current Viewport
else
glViewport(-(height*ACTUAL_RATIO-width)/2, 0, height * ACTUAL_RATIO, height);
glScissor(0, 0, width, height);
}
GLvoid SizeGLScene(GLsizei width, GLsizei height) // Initialize The GL Window
{
if (0 == height) // Prevent A Divide By Zero By
height=1; // Making Height Equal One
glViewport(0, 0, width, height); // Reset The Current Viewport
glMatrixMode(GL_PROJECTION); // Select The Projection Matrix
glLoadIdentity(); // Reset The Projection Matrix
// Calculate The Aspect Ratio Of The Window
gluPerspective(75.0f, ACTUAL_RATIO, 0.5f, 1000.0f);
glMatrixMode(GL_MODELVIEW); // Select The Modelview Matrix
glLoadIdentity(); // Reset The Modelview Matrix
// glutReshapeWindow(width, height);
ReSizeGLScene(width, height);
}
int InitGL(void) // All Setup For OpenGL Goes Here
{
glClearColor(0.0f, 0.0f, 0.0f, 0.0f); // Black Background (yes that's the way fuckers)
glClearDepth(1.0f); // Depth Buffer Setup
glDepthFunc(GL_LEQUAL); // The Type Of Depth Testing (Less Or Equal)
glEnable(GL_DEPTH_TEST); // Enable Depth Testing
glShadeModel(GL_SMOOTH); // Select Smooth Shading
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); // Set Perspective Calculations To Most Accurate
glHint(GL_LINE_SMOOTH_HINT, GL_NICEST); // Set Line Antialiasing
glEnable(GL_LINE_SMOOTH); // Enable it!
glEnable(GL_CULL_FACE); // do not calculate inside of poly's
glFrontFace(GL_CCW); // counter clock-wise polygons are out
glEnable(GL_TEXTURE_2D);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_SCISSOR_TEST); // Enable Clipping
return true; // Initialization Went OK
}
bool InitGame(void)
{
g_engine = JGE::GetInstance();
g_app = g_launcher->GetGameApp();
JGECreateDefaultBindings();
g_app->Create();
g_engine->SetApp(g_app);
JRenderer::GetInstance()->Enable2D();
struct timeval tv;
gettimeofday(&tv, NULL);
lastTickCount = tv.tv_sec * 1000 + tv.tv_usec / 1000;
return true;
}
void DestroyGame(void)
{
g_engine->SetApp(NULL);
if (g_app)
{
g_app->Destroy();
delete g_app;
g_app = NULL;
}
JGE::Destroy();
g_engine = NULL;
}
void KillGLWindow(void) // Properly Kill The Window
{
if (gXWindow && gXDisplay)
XDestroyWindow(gXDisplay, gXWindow);
gXWindow = (Window)NULL;
}
// Some parameters we wanna give to XGl
static const int doubleBufferAttributes[] = {
GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT,
GLX_RENDER_TYPE, GLX_RGBA_BIT,
GLX_DOUBLEBUFFER, True, /* Request a double-buffered color buffer with */
GLX_RED_SIZE, 1, /* the maximum number of bits per component */
GLX_GREEN_SIZE, 1,
GLX_BLUE_SIZE, 1,
None
};
static Bool WaitForNotify(Display *dpy, XEvent *event, XPointer arg)
{
return (event->type == MapNotify) && (event->xmap.window == (Window) arg);
}
/* This Code Creates Our OpenGL Window. Parameters Are: *
* title - Title To Appear At The Top Of The Window *
* width - Width Of The GL Window Or Fullscreen Mode *
* height - Height Of The GL Window Or Fullscreen Mode *
* bits - Number Of Bits To Use For Color (8/16/24/32) *
* fullscreenflag - Use Fullscreen Mode (true) Or Windowed Mode (false) */
BOOL CreateGLWindow(char* title, int width, int height, int bits __attribute__((unused)), bool fullscreenflag __attribute__((unused)))
{
// Open a connection to the X server
gXDisplay = XOpenDisplay(NULL);
if (NULL == gXDisplay)
{
printf("Unable to open a connection to the X server\n");
return false;
}
// Get a suitable framebuffer config
int numReturned;
GLXFBConfig *fbConfigs = glXChooseFBConfig(gXDisplay, DefaultScreen(gXDisplay), doubleBufferAttributes, &numReturned);
if (NULL == fbConfigs)
{
printf("Unable to get a double buffered configuration\n");
return false;
}
// Create an X colormap and window with a visual matching the framebuffer config
XVisualInfo *vInfo = glXGetVisualFromFBConfig(gXDisplay, fbConfigs[0]);
// We must create a color map - I didn't understand why very well since we require TrueColor
XSetWindowAttributes swa;
swa.border_pixel = 0;
swa.event_mask = StructureNotifyMask;
swa.colormap = XCreateColormap(gXDisplay, RootWindow(gXDisplay, vInfo->screen), vInfo->visual, AllocNone);
// Create the window itself
gXWindow = XCreateWindow(gXDisplay, RootWindow(gXDisplay, vInfo->screen), 0, 0, width, height,
0, vInfo->depth, InputOutput, vInfo->visual,
CWBorderPixel | CWColormap | CWEventMask, &swa);
// Create a GLX context for OpenGL rendering
GLXContext context = glXCreateNewContext(gXDisplay, fbConfigs[0], GLX_RGBA_TYPE, NULL, True);
// Associate the frame buffer configuration with the created X window
glxWin = glXCreateWindow(gXDisplay, fbConfigs[0], gXWindow, NULL);
// Map the window to the screen
XMapWindow(gXDisplay, gXWindow);
// Wait for the window to appear
XEvent event;
XIfEvent(gXDisplay, &event, WaitForNotify, (XPointer) gXWindow);
// Bind the GLX context to the Window
glXMakeContextCurrent(gXDisplay, glxWin, glxWin, context);
free(vInfo);
free(fbConfigs);
SizeGLScene(width, height);
if (!InitGL())
{
KillGLWindow();
printf("Initializing GL failed.");
return false;
}
return true;
}
void Update(float dt)
{
gPrevControllerState = gControllerState;
g_engine->SetDelta(dt);
g_engine->Update(dt);
}
int DrawGLScene(void)
{
g_engine->Render();
return true;
}
template <typename T>
static inline bool include(multiset<T> set, T button)
{
return set.end() != set.find(button);
}
void JGECreateDefaultBindings()
{
for (signed int i = sizeof(gDefaultBindings)/sizeof(gDefaultBindings[0]) - 1; i >= 0; --i)
g_engine->BindKey(gDefaultBindings[i].keysym, gDefaultBindings[i].keycode);
}
int JGEGetTime()
{
struct timeval tv;
gettimeofday(&tv, NULL);
return tv.tv_sec * 1000 + tv.tv_usec / 1000;
}
void reshapeFunc(int width, int height)
{
ReSizeGLScene(width, height);
}
bool JGEToggleFullscreen()
{
Atom wmState = XInternAtom(gXDisplay, "_NET_WM_STATE", False);
Atom fullScreen = XInternAtom(gXDisplay, "_NET_WM_STATE_FULLSCREEN", False);
XEvent xev;
xev.xclient.type = ClientMessage;
xev.xclient.serial = 0;
xev.xclient.send_event = True;
xev.xclient.window = gXWindow;
xev.xclient.message_type = wmState;
xev.xclient.format = 32;
xev.xclient.data.l[0] = _NET_WM_STATE_TOGGLE;
xev.xclient.data.l[1] = fullScreen;
xev.xclient.data.l[2] = 0;
if (window_state.fullscreen)
{
XSendEvent(gXDisplay, DefaultRootWindow(gXDisplay), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev);
XMoveResizeWindow(gXDisplay, gXWindow, window_state.x, window_state.y, window_state.width, window_state.height);
window_state.fullscreen = false;
}
else
{
XWindowAttributes xwa;
Window child_return;
int x, y;
XGetWindowAttributes(gXDisplay, gXWindow, &xwa);
XTranslateCoordinates(gXDisplay, gXWindow, DefaultRootWindow(gXDisplay), xwa.x, xwa.y, &window_state.x, &window_state.y, &child_return);
window_state.width = xwa.width; window_state.height = xwa.height;
window_state.fullscreen = true;
XSendEvent(gXDisplay, DefaultRootWindow(gXDisplay), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev);
XGetWindowAttributes(gXDisplay, DefaultRootWindow(gXDisplay), &xwa);
XMoveResizeWindow(gXDisplay, gXWindow, 0, 0, xwa.width, xwa.height);
}
return true;
}
int main(int argc, char* argv[])
{
char* path = argv[0];
while (*path) ++path;
while ((*path != '/') && (path > argv[0])) --path;
if ('/' == *path) *path = 0;
if (strlen(argv[0]) != 0) chdir(argv[0]);
g_launcher = new JGameLauncher();
u32 flags = g_launcher->GetInitFlags();
if ((flags&JINIT_FLAG_ENABLE3D)!=0)
JRenderer::Set3DFlag(true);
// Create Our OpenGL Window
if (!CreateGLWindow(g_launcher->GetName(), ACTUAL_SCREEN_WIDTH, ACTUAL_SCREEN_HEIGHT, 32, window_state.fullscreen))
{
printf("Could not create the window\n");
return 1; // Quit If Window Was Not Created
}
if (!InitGame())
{
printf("Could not init the game\n");
return 1;
}
XSelectInput(gXDisplay, gXWindow, KeyPressMask | KeyReleaseMask | StructureNotifyMask);
XkbSetDetectableAutoRepeat(gXDisplay, True, NULL);
static uint64_t tickCount;
while (!g_engine->IsDone())
{
struct timeval tv;
uint dt;
XEvent event;
gettimeofday(&tv, NULL);
tickCount = tv.tv_sec * 1000 + tv.tv_usec / 1000;
dt = (tickCount - lastTickCount);
lastTickCount = tickCount;
Update((float)dt / 1000.0f); // Update frame
DrawGLScene(); // Draw The Scene
glXSwapBuffers(gXDisplay, glxWin);
if (XCheckWindowEvent(gXDisplay, gXWindow, KeyPressMask | KeyReleaseMask | StructureNotifyMask, &event))
switch (event.type)
{
case KeyPress:
{
const KeySym sym = XKeycodeToKeysym(gXDisplay, event.xkey.keycode, 1);
g_engine->HoldKey_NoRepeat(sym);
}
break;
case KeyRelease:
g_engine->ReleaseKey(XKeycodeToKeysym(gXDisplay, event.xkey.keycode, 1));
break;
case ConfigureNotify:
ReSizeGLScene(event.xconfigure.width, event.xconfigure.height);
break;
default:
break;
}
}
if (g_launcher)
delete g_launcher;
// Shutdown
DestroyGame();
KillGLWindow(); // Kill The Window
return 0;
}

View File

@@ -1,596 +0,0 @@
#include <qplatformdefs.h>
#include <QtOpenGL>
#include "corewrapper.h"
#include <QElapsedTimer>
#ifdef TESTSUITE
#include "TestSuiteAI.h"
#include "GameOptions.h"
#include "MTGDeck.h"
#endif
#include "DebugRoutines.h"
#if (defined FORCE_GLES)
#undef GL_ES_VERSION_2_0
#undef GL_VERSION_2_0
#define GL_VERSION_ES_CM_1_1 1
#ifndef GL_OES_VERSION_1_1
#define glOrthof glOrtho
#define glClearDepthf glClearDepth
#endif
#endif
#if (defined FORCE_GLES)
#undef GL_ES_VERSION_2_0
#undef GL_VERSION_2_0
#define GL_VERSION_ES_CM_1_1 1
#define glOrthof glOrtho
#define glClearDepthf glClearDepth
#endif
#define ACTUAL_SCREEN_WIDTH (SCREEN_WIDTH)
#define ACTUAL_SCREEN_HEIGHT (SCREEN_HEIGHT)
#define ACTUAL_RATIO ((GLfloat)ACTUAL_SCREEN_WIDTH / (GLfloat)ACTUAL_SCREEN_HEIGHT)
// in pixels
#define kHitzonePliancy 50
// tick value equates to ms
#define kTapEventTimeout 250
// swipe duration
#define kSwipeEventMinDuration 250
// swipe distance in pixel (from top to down)
#define kSwipeMinDistance 200
QElapsedTimer WagicCore::g_startTimer;
WagicCore::WagicCore(super *parent) :
super(parent), m_engine(0), m_app(0), m_launcher(0), m_active(false)
#ifdef Q_WS_MAEMO_5
, dBusConnection(QDBusConnection::systemBus()), dBusInterface(0)
#endif //Q_WS_MAEMO_5
{
#ifdef QT_WIDGET
#if (defined Q_WS_MAEMO_5)
setAttribute(Qt::WA_Maemo5AutoOrientation);
setAttribute(Qt::WA_Maemo5NonComposited);
#endif //Q_WS_MAEMO_5
setAttribute(Qt::WA_AcceptTouchEvents);
// setAttribute(Qt::WA_InputMethodEnabled);
setMouseTracking(true);
grabGesture(Qt::TapAndHoldGesture);
resize(ACTUAL_SCREEN_WIDTH, ACTUAL_SCREEN_HEIGHT);
#else
setWidth(480);
setHeight(272);
setFlag(QGraphicsItem::ItemHasNoContents, false);
#endif //QT_WIDGET
g_startTimer.restart();
m_lastTickCount = g_startTimer.elapsed();
#ifdef Q_WS_MAEMO_5
dBusInterface = new QDBusInterface(MCE_SERVICE, MCE_REQUEST_PATH,
MCE_REQUEST_IF, dBusConnection);
// Handle screen state on / off
dBusConnection.connect(MCE_SERVICE, MCE_SIGNAL_PATH, MCE_SIGNAL_IF, MCE_DISPLAY_SIG, this, SLOT(displayStateChanged(const QDBusMessage &)));
#endif
}
WagicWrapper::WagicWrapper()
{
m_launcher = new JGameLauncher();
u32 flags = m_launcher->GetInitFlags();
if ((flags&JINIT_FLAG_ENABLE3D)!=0)
{
JRenderer::Set3DFlag(true);
}
JGECreateDefaultBindings();
m_engine = JGE::GetInstance();
m_app = m_launcher->GetGameApp();
m_app->Create();
m_engine->SetApp(m_app);
JRenderer::GetInstance()->Enable2D();
}
WagicWrapper::~WagicWrapper()
{
if(m_launcher)
{
delete m_launcher;
m_launcher = NULL;
}
if(m_engine)
m_engine->SetApp(NULL);
if (m_app)
{
m_app->Destroy();
delete m_app;
m_app = NULL;
}
JGE::Destroy();
m_engine = NULL;
}
int WagicCore::runTestSuite()
{
int result = 0;
#ifdef TESTSUITE
WagicWrapper* wagicCore = new WagicWrapper();
MTGCollection()->loadFolder("sets/primitives/");
MTGCollection()->loadFolder("sets/", "_cards.dat");
options.reloadProfile();
TestSuite testSuite("test/_tests.txt");
result = testSuite.run();
delete wagicCore;
#endif
DebugTrace("TestSuite done: failed test: " << result);
return result;
}
void WagicCore::initApp()
{
if(!m_engine)
{
m_launcher = new JGameLauncher();
u32 flags = m_launcher->GetInitFlags();
if ((flags&JINIT_FLAG_ENABLE3D)!=0)
{
JRenderer::Set3DFlag(true);
}
JGECreateDefaultBindings();
m_engine = JGE::GetInstance();
m_app = m_launcher->GetGameApp();
m_app->Create();
m_engine->SetApp(m_app);
JRenderer::GetInstance()->Enable2D();
setActive(true);
}
}
WagicCore::~WagicCore()
{
#ifdef Q_WS_MAEMO_5
if(dBusInterface)
delete dBusInterface;
#endif //Q_WS_MAEMO_5
if(m_launcher)
{
delete m_launcher;
m_launcher = NULL;
}
if(m_engine)
m_engine->SetApp(NULL);
if (m_app)
{
m_app->Destroy();
delete m_app;
m_app = NULL;
}
JGE::Destroy();
m_engine = NULL;
}
void WagicCore::pixelInput(int x, int y)
{
if(m_engine)
m_engine->LeftClicked(x, y);
}
void WagicCore::timerEvent( QTimerEvent* )
{
qint64 tickCount;
quint32 dt;
tickCount = g_startTimer.elapsed();
dt = (tickCount - m_lastTickCount);
m_lastTickCount = tickCount;
if(!m_engine)
return;
if(m_engine->IsDone())
QApplication::instance()->quit();
m_engine->SetDelta((float)dt / 1000.0f);
m_engine->Update((float)dt / 1000.0f);
done();
update();
}
void WagicCore::setActive(bool active)
{
if(!m_engine) return;
if(!m_active && active)
{
m_engine->Resume();
#if (defined Q_WS_MAEMO_5) || defined(MEEGO_EDITION_HARMATTAN) || (defined Q_WS_ANDROID)
// 30 fps max on mobile
m_timerId = startTimer(33);
#else
// 200 fps max on desktop
m_timerId = startTimer(5);
#endif //Q_WS_MAEMO_5
m_active = active;
emit activeChanged();
}
else if(m_active && !active)
{
m_engine->Pause();
#if (defined Q_WS_MAEMO_5) || defined(MEEGO_EDITION_HARMATTAN) || (defined Q_WS_ANDROID)
killTimer(m_timerId);
#endif
m_active = active;
emit activeChanged();
}
}
void WagicCore::initializeGL()
{
glClearColor(0.0f, 0.0f, 0.0f, 0.0f); // Black Background (yes that's the way fuckers)
#if (defined GL_ES_VERSION_2_0) || (defined GL_VERSION_2_0)
#if (defined GL_ES_VERSION_2_0)
glClearDepthf(1.0f); // Depth Buffer Setup
#else
glClearDepth(1.0f); // Depth Buffer Setup
#endif// (defined GL_ES_VERSION_2_0)
glDepthFunc(GL_LEQUAL); // The Type Of Depth Testing (Less Or Equal)
glEnable(GL_DEPTH_TEST); // Enable Depth Testing
#else
#if (defined GL_VERSION_ES_CM_1_1 || defined GL_OES_VERSION_1_1)
glClearDepthf(1.0f); // Depth Buffer Setup
#else
glClearDepth(1.0f); // Depth Buffer Setup
#endif
glDepthFunc(GL_LEQUAL); // The Type Of Depth Testing (Less Or Equal)
glEnable(GL_DEPTH_TEST); // Enable Depth Testing
glShadeModel(GL_SMOOTH); // Select Smooth Shading
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); // Set Perspective Calculations To Most Accurate
glHint(GL_LINE_SMOOTH_HINT, GL_NICEST); // Set Line Antialiasing
glEnable(GL_LINE_SMOOTH); // Enable it!
glEnable(GL_TEXTURE_2D);
#endif
glEnable(GL_CULL_FACE); // do not calculate inside of poly's
glFrontFace(GL_CCW); // counter clock-wise polygons are out
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_SCISSOR_TEST); // Enable Clipping
}
#ifndef QT_WIDGET
void WagicCore::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
painter->beginNativePainting();
initApp();
resizeGL ( boundingRect().size().width(), boundingRect().size().height());
initializeGL();
paintGL();
painter->endNativePainting();
}
#endif //QT_WIDGET
void WagicCore::paintGL()
{
if(m_engine)
m_engine->Render();
}
void WagicCore::resizeGL(int width, int height)
{
if ((GLfloat)width / (GLfloat)height <= ACTUAL_RATIO)
{
m_viewPort.setLeft(0);
m_viewPort.setTop(-((width/ACTUAL_RATIO)-height)/2);
m_viewPort.setRight(width);
m_viewPort.setBottom(-((width/ACTUAL_RATIO)-height)/2 + width / ACTUAL_RATIO);
}
else
{
m_viewPort.setLeft(-(height*ACTUAL_RATIO-width)/2);
m_viewPort.setTop(0);
m_viewPort.setRight(-(height*ACTUAL_RATIO-width)/2 + height * ACTUAL_RATIO);
m_viewPort.setBottom(height);
}
glViewport(m_viewPort.left(), m_viewPort.top(), m_viewPort.right()-m_viewPort.left(), m_viewPort.bottom()-m_viewPort.top());
JRenderer::GetInstance()->SetActualWidth(m_viewPort.right()-m_viewPort.left());
JRenderer::GetInstance()->SetActualHeight(m_viewPort.bottom()-m_viewPort.top());
glScissor(0, 0, width, height);
#if (!defined GL_ES_VERSION_2_0) && (!defined GL_VERSION_2_0)
glMatrixMode (GL_PROJECTION); // Select The Projection Matrix
glLoadIdentity (); // Reset The Projection Matrix
#if (defined GL_VERSION_ES_CM_1_1 || defined GL_OES_VERSION_1_1)
glOrthof(0.0f, (float) (m_viewPort.right()-m_viewPort.left())-1.0f, 0.0f, (float) (m_viewPort.bottom()-m_viewPort.top())-1.0f, -1.0f, 1.0f);
#else
glOrtho(0.0f, (float) (m_viewPort.right()-m_viewPort.left())-1.0f, 0.0f, (float) (m_viewPort.bottom()-m_viewPort.top())-1.0f, -1.0f, 1.0f);
#endif
glMatrixMode (GL_MODELVIEW); // Select The Modelview Matrix
glLoadIdentity (); // Reset The Modelview Matrix
glDisable (GL_DEPTH_TEST);
#endif
}
void WagicCore::keyPressEvent(QKeyEvent *event)
{
switch(event->key())
{
#if (defined Q_WS_MAEMO_5)
case Qt::Key_F7:
/* interrupt please */
m_engine->HoldKey_NoRepeat(JGE_BTN_SEC);
break;
case Qt::Key_F8:
/* next phase please */
m_engine->HoldKey_NoRepeat(JGE_BTN_PREV);
break;
#endif // Q_WS_MAEMO_5
case Qt::Key_F:
JGEToggleFullscreen();
break;
default:
m_engine->HoldKey_NoRepeat((LocalKeySym)event->key());
}
event->accept();
super::keyPressEvent(event);
}
void WagicCore::keyReleaseEvent(QKeyEvent *event)
{
switch(event->key())
{
#if (defined Q_WS_MAEMO_5)
case Qt::Key_F7:
/* interrupt please */
m_engine->ReleaseKey(JGE_BTN_SEC);
break;
case Qt::Key_F8:
/* next phase please */
m_engine->ReleaseKey(JGE_BTN_PREV);
break;
#endif // Q_WS_MAEMO_5
default:
m_engine->ReleaseKey((LocalKeySym)event->key());
}
event->accept();
super::keyReleaseEvent(event);
}
#ifdef QT_WIDGET
void WagicCore::wheelEvent(QWheelEvent *event)
#else
void WagicCore::wheelEvent ( QGraphicsSceneWheelEvent * event)
#endif
{
if(event->orientation() == Qt::Vertical)
m_engine->Scroll(0, 3*event->delta());
else
m_engine->Scroll(3*event->delta(), 0);
event->accept();
}
#ifdef QT_WIDGET
void WagicCore::tapAndHoldTriggered(QTapAndHoldGesture* gesture)
{
if (gesture->state() == Qt::GestureFinished) {
m_engine->HoldKey_NoRepeat(JGE_BTN_MENU);
}
}
void WagicCore::mousePressEvent(QMouseEvent *event)
{
if(event->button() == Qt::LeftButton)
{
m_lastPos = event->pos();
// this is intended to convert window coordinate into game coordinate.
// this is correct only if the game and window have the same aspect ratio, otherwise, it's just wrong
int actualWidth = (int) JRenderer::GetInstance()->GetActualWidth();
int actualHeight = (int) JRenderer::GetInstance()->GetActualHeight();
if (lastPosy() >= m_viewPort.top() &&
lastPosy() <= m_viewPort.bottom() &&
lastPosx() <= m_viewPort.right() &&
lastPosx() >= m_viewPort.left()) {
m_engine->LeftClicked(
((lastPosx()-m_viewPort.left())*SCREEN_WIDTH)/actualWidth,
((lastPosy()-m_viewPort.top())*SCREEN_HEIGHT)/actualHeight);
#if (!defined Q_WS_MAEMO_5) && (!defined MEEGO_EDITION_HARMATTAN) && (!defined Q_WS_ANDROID)
m_engine->HoldKey_NoRepeat(JGE_BTN_OK);
#else
mMouseDownX = lastPosx();
mMouseDownY = lastPosy();
mLastFingerDownTime = g_startTimer.elapsed();
#endif
} else if(lastPosy()<m_viewPort.top()) {
m_engine->HoldKey_NoRepeat(JGE_BTN_MENU);
} else if(lastPosy()>m_viewPort.bottom()) {
m_engine->HoldKey_NoRepeat(JGE_BTN_NEXT);
}
event->accept();
}
else if(event->button() == Qt::RightButton)
{ /* next phase please */
m_engine->HoldKey_NoRepeat(JGE_BTN_PREV);
event->accept();
}
else if(event->button() == Qt::MidButton)
{ /* interrupt please */
m_engine->HoldKey_NoRepeat(JGE_BTN_SEC);
event->accept();
}
else
{
super::mousePressEvent(event);
}
}
void WagicCore::mouseReleaseEvent(QMouseEvent *event)
{
if(event->button() == Qt::LeftButton)
{
m_lastPos = event->pos();
if (lastPosy() >= m_viewPort.top() &&
lastPosy() <= m_viewPort.bottom() &&
lastPosx() <= m_viewPort.right() &&
lastPosx() >= m_viewPort.left()) {
#if (defined Q_WS_MAEMO_5) || (defined MEEGO_EDITION_HARMATTAN) || (defined Q_WS_ANDROID)
if(g_startTimer.elapsed() - mLastFingerDownTime <= kTapEventTimeout )
{
if(abs(mMouseDownX - lastPosx()) < kHitzonePliancy &&
abs(mMouseDownY - lastPosy()) < kHitzonePliancy)
{
m_engine->HoldKey_NoRepeat(JGE_BTN_OK);
}
}
else if (g_startTimer.elapsed() - mLastFingerDownTime >= kSwipeEventMinDuration)
{ // Let's swipe
m_engine->Scroll(lastPosx()-mMouseDownX, lastPosy()-mMouseDownY);
}
#else
//#if (!defined Q_WS_MAEMO_5) && (!defined MEEGO_EDITION_HARMATTAN)
m_engine->ReleaseKey(JGE_BTN_OK);
#endif
m_engine->ReleaseKey(JGE_BTN_MENU);
} else if(lastPosy() < m_viewPort.top()) {
m_engine->ReleaseKey(JGE_BTN_MENU);
} else if(lastPosy() > m_viewPort.bottom()) {
m_engine->ReleaseKey(JGE_BTN_NEXT);
}
event->accept();
}
else if(event->button() == Qt::RightButton)
{ /* next phase please */
m_engine->ReleaseKey(JGE_BTN_PREV);
event->accept();
}
else if(event->button() == Qt::MidButton)
{ /* interrupt please */
m_engine->ReleaseKey(JGE_BTN_SEC);
event->accept();
}
else
{
super::mouseReleaseEvent(event);
}
}
void WagicCore::mouseMoveEvent(QMouseEvent *event)
{
int actualWidth = (int) JRenderer::GetInstance()->GetActualWidth();
int actualHeight = (int) JRenderer::GetInstance()->GetActualHeight();
m_lastPos = event->pos();
if (lastPosy() >= m_viewPort.top() &&
lastPosy() <= m_viewPort.bottom() &&
lastPosx() <= m_viewPort.right() &&
lastPosx() >= m_viewPort.left()) {
m_engine->LeftClicked(
((lastPosx()-m_viewPort.left())*SCREEN_WIDTH)/actualWidth,
((lastPosy()-m_viewPort.top())*SCREEN_HEIGHT)/actualHeight);
event->accept();
} else {
super::mouseMoveEvent(event);
}
}
void WagicCore::showEvent ( QShowEvent * )
{
setActive(true);
}
void WagicCore::hideEvent ( QHideEvent * )
{
setActive(false);
}
bool WagicCore::event(QEvent *event)
{
if (event->type() == QEvent::Gesture)
return gestureEvent(static_cast<QGestureEvent*>(event));
#if (defined Q_WS_MAEMO_5) || (defined MEEGO_EDITION_HARMATTAN) || (defined Q_WS_ANDROID)
else if (event->type() == QEvent::WindowActivate)
{
showEvent(NULL);
}
else if (event->type() == QEvent::WindowDeactivate)
{
hideEvent(NULL);
}
#endif
return QGLWidget::event(event);
}
bool WagicCore::gestureEvent(QGestureEvent* event)
{
if (QGesture *tapAndHold = event->gesture(Qt::TapAndHoldGesture))
tapAndHoldTriggered(static_cast<QTapAndHoldGesture *>(tapAndHold));
return true;
}
void WagicCore::start(int)
{
#if (defined Q_WS_MAEMO_5) || (defined MEEGO_EDITION_HARMATTAN) || (defined Q_WS_ANDROID)
showFullScreen();
#else
show();
#endif
initApp();
}
#endif //QT_WIDGET
#ifdef Q_WS_MAEMO_5
void WagicCore::displayStateChanged(const QDBusMessage &message)
{
QString state = message.arguments().at(0).toString();
if (!state.isEmpty()) {
if (state == MCE_DISPLAY_ON_STRING && isActiveWindow()) {
setActive(true);
}
else if (state == MCE_DISPLAY_OFF_STRING) {
setActive(false);
}
}
}
#endif

View File

@@ -1,115 +0,0 @@
#include "filedownloader.h"
#include <QDir>
#include <QCryptographicHash>
FileDownloader::FileDownloader(QString localPath, QString targetFile, QObject *parent) :
#ifdef QT_WIDGET
QProgressDialog("Downloading resources", "", 0, 100, (QWidget*)parent, 0),
#else
QObject(parent),
#endif //QT_WIDGET
m_state(NETWORK_ERROR), m_received(0), m_targetFile(targetFile), m_localHash(""), m_OK(false)
{
#ifdef QT_WIDGET
setCancelButton(0);
connect(this, SIGNAL(receivedChanged(int)), SLOT(setValue(int)));
connect(this, SIGNAL(canceled()), SLOT(handleCancel()));
#endif //QT_WIDGET
connect(this, SIGNAL(stateChanged(DownloadState)), SLOT(handleStateChange(DownloadState)));
QDir dir(QDir::homePath());
if(!dir.mkpath(localPath))
{
m_OK = false;
return;
}
dir.cd(localPath);
m_localPath = dir.filePath("core.zip");
QFile local(m_localPath);
if(local.exists()) {
/* a file is already present in the local path */
computeLocalHash(local);
m_state = DOWNLOADED;
}
if(m_WebCtrl.networkAccessible()) {
/* Network is OK, we request the remote hash file */
m_state = DOWNLOADING_HASH;
requestHash(QUrl("http://code.google.com/p/wagic/downloads/detail?name="+m_targetFile));
}
emit stateChanged(m_state);
}
void FileDownloader::setDownloadUrl(QUrl url)
{
if((!url.isEmpty()))
{
if(!m_WebCtrl.networkAccessible()) {
m_status = "Network not accessible, press retry when the network is accessible.";
emit statusChanged();
return;
}
QNetworkRequest request(url);
m_downloadReply = m_WebCtrl.get(request);
connect(m_downloadReply, SIGNAL(downloadProgress(qint64, qint64)),
SLOT(downloadProgress(qint64, qint64)));
connect(m_downloadReply, SIGNAL(finished()), SLOT(fileDownloaded()));
m_status = "Downloading Resources";
m_OK = m_tmp.open();
}
}
FileDownloader::~FileDownloader()
{
}
void FileDownloader::requestHash(QUrl url)
{
QNetworkRequest request(url);
m_hashReply = m_WebCtrl.get(request);
connect(m_hashReply, SIGNAL(finished()), SLOT(computeRemoteHash()));
}
void FileDownloader::computeRemoteHash()
{
if(m_hashReply->error() != QNetworkReply::NoError) {
m_state = NETWORK_ERROR;
} else {
QString aString = m_hashReply->readAll();
int index = aString.indexOf("<span id=\"sha1\">");
m_remoteHash = aString.mid(index+16, 40);
if(m_localHash != m_remoteHash)
{ /* We download the real file */
m_state = DOWNLOADING_FILE;
setDownloadUrl(QUrl("http://wagic.googlecode.com/files/" + m_targetFile));
}
else
{
m_state = DOWNLOADED;
}
}
emit stateChanged(m_state);
}
void FileDownloader::computeLocalHash(QFile& file)
{
QCryptographicHash crypto(QCryptographicHash::Sha1);
QFile myFile(file.fileName());
myFile.open(QFile::ReadOnly);
while(!myFile.atEnd()){
crypto.addData(myFile.read(8192));
}
QByteArray hash = crypto.result();
m_localHash = hash.toHex();
}

View File

@@ -1,115 +0,0 @@
/*
www.sourceforge.net/projects/tinyxml
Original file by Yves Berquin.
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any
damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it and
redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must
not claim that you wrote the original software. If you use this
software in a product, an acknowledgment in the product documentation
would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
/*
* THIS FILE WAS ALTERED BY Tyge Løvset, 7. April 2005.
*/
#ifndef TIXML_USE_STL
#include "tinystr.h"
// Error value for find primitive
const TiXmlString::size_type TiXmlString::npos = static_cast< size_type >(-1);
// Null rep.
TiXmlString::Rep TiXmlString::nullrep_ = { 0, 0, { '\0' } };
void TiXmlString::reserve (size_type cap)
{
if (cap > capacity())
{
TiXmlString tmp;
tmp.init(length(), cap);
memcpy(tmp.start(), data(), length());
swap(tmp);
}
}
TiXmlString& TiXmlString::assign(const char* str, size_type len)
{
size_type cap = capacity();
if (len > cap || cap > 3*(len + 8))
{
TiXmlString tmp;
tmp.init(len);
memcpy(tmp.start(), str, len);
swap(tmp);
}
else
{
memmove(start(), str, len);
set_size(len);
}
return *this;
}
TiXmlString& TiXmlString::append(const char* str, size_type len)
{
size_type newsize = length() + len;
if (newsize > capacity())
{
reserve (newsize + capacity());
}
memmove(finish(), str, len);
set_size(newsize);
return *this;
}
TiXmlString operator + (const TiXmlString & a, const TiXmlString & b)
{
TiXmlString tmp;
tmp.reserve(a.length() + b.length());
tmp += a;
tmp += b;
return tmp;
}
TiXmlString operator + (const TiXmlString & a, const char* b)
{
TiXmlString tmp;
TiXmlString::size_type b_len = static_cast<TiXmlString::size_type>( strlen(b) );
tmp.reserve(a.length() + b_len);
tmp += a;
tmp.append(b, b_len);
return tmp;
}
TiXmlString operator + (const char* a, const TiXmlString & b)
{
TiXmlString tmp;
TiXmlString::size_type a_len = static_cast<TiXmlString::size_type>( strlen(a) );
tmp.reserve(a_len + b.length());
tmp.append(a, a_len);
tmp += b;
return tmp;
}
#endif // TIXML_USE_STL

View File

@@ -1,319 +0,0 @@
/*
www.sourceforge.net/projects/tinyxml
Original file by Yves Berquin.
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any
damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it and
redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must
not claim that you wrote the original software. If you use this
software in a product, an acknowledgment in the product documentation
would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
/*
* THIS FILE WAS ALTERED BY Tyge Lovset, 7. April 2005.
*
* - completely rewritten. compact, clean, and fast implementation.
* - sizeof(TiXmlString) = pointer size (4 bytes on 32-bit systems)
* - fixed reserve() to work as per specification.
* - fixed buggy compares operator==(), operator<(), and operator>()
* - fixed operator+=() to take a const ref argument, following spec.
* - added "copy" constructor with length, and most compare operators.
* - added swap(), clear(), size(), capacity(), operator+().
*/
#ifndef TIXML_USE_STL
#ifndef TIXML_STRING_INCLUDED
#define TIXML_STRING_INCLUDED
#include <assert.h>
#include <string.h>
/* The support for explicit isn't that universal, and it isn't really
required - it is used to check that the TiXmlString class isn't incorrectly
used. Be nice to old compilers and macro it here:
*/
#if defined(_MSC_VER) && (_MSC_VER >= 1200 )
// Microsoft visual studio, version 6 and higher.
#define TIXML_EXPLICIT explicit
#elif defined(__GNUC__) && (__GNUC__ >= 3 )
// GCC version 3 and higher.s
#define TIXML_EXPLICIT explicit
#else
#define TIXML_EXPLICIT
#endif
/*
TiXmlString is an emulation of a subset of the std::string template.
Its purpose is to allow compiling TinyXML on compilers with no or poor STL support.
Only the member functions relevant to the TinyXML project have been implemented.
The buffer allocation is made by a simplistic power of 2 like mechanism : if we increase
a string and there's no more room, we allocate a buffer twice as big as we need.
*/
class TiXmlString
{
public :
// The size type used
typedef size_t size_type;
// Error value for find primitive
static const size_type npos; // = -1;
// TiXmlString empty constructor
TiXmlString () : rep_(&nullrep_)
{
}
// TiXmlString copy constructor
TiXmlString ( const TiXmlString & copy)
{
init(copy.length());
memcpy(start(), copy.data(), length());
}
// TiXmlString constructor, based on a string
TIXML_EXPLICIT TiXmlString ( const char * copy)
{
init( static_cast<size_type>( strlen(copy) ));
memcpy(start(), copy, length());
}
// TiXmlString constructor, based on a string
TIXML_EXPLICIT TiXmlString ( const char * str, size_type len)
{
init(len);
memcpy(start(), str, len);
}
// TiXmlString destructor
~TiXmlString ()
{
quit();
}
// = operator
TiXmlString& operator = (const char * copy)
{
return assign( copy, (size_type)strlen(copy));
}
// = operator
TiXmlString& operator = (const TiXmlString & copy)
{
return assign(copy.start(), copy.length());
}
// += operator. Maps to append
TiXmlString& operator += (const char * suffix)
{
return append(suffix, static_cast<size_type>( strlen(suffix) ));
}
// += operator. Maps to append
TiXmlString& operator += (char single)
{
return append(&single, 1);
}
// += operator. Maps to append
TiXmlString& operator += (const TiXmlString & suffix)
{
return append(suffix.data(), suffix.length());
}
// Convert a TiXmlString into a null-terminated char *
const char * c_str () const { return rep_->str; }
// Convert a TiXmlString into a char * (need not be null terminated).
const char * data () const { return rep_->str; }
// Return the length of a TiXmlString
size_type length () const { return rep_->size; }
// Alias for length()
size_type size () const { return rep_->size; }
// Checks if a TiXmlString is empty
bool empty () const { return rep_->size == 0; }
// Return capacity of string
size_type capacity () const { return rep_->capacity; }
// single char extraction
const char& at (size_type index) const
{
assert( index < length() );
return rep_->str[ index ];
}
// [] operator
char& operator [] (size_type index) const
{
assert( index < length() );
return rep_->str[ index ];
}
// find a char in a string. Return TiXmlString::npos if not found
size_type find (char lookup) const
{
return find(lookup, 0);
}
// find a char in a string from an offset. Return TiXmlString::npos if not found
size_type find (char tofind, size_type offset) const
{
if (offset >= length()) return npos;
for (const char* p = c_str() + offset; *p != '\0'; ++p)
{
if (*p == tofind) return static_cast< size_type >( p - c_str() );
}
return npos;
}
void clear ()
{
//Lee:
//The original was just too strange, though correct:
// TiXmlString().swap(*this);
//Instead use the quit & re-init:
quit();
init(0,0);
}
/* Function to reserve a big amount of data when we know we'll need it. Be aware that this
function DOES NOT clear the content of the TiXmlString if any exists.
*/
void reserve (size_type cap);
TiXmlString& assign (const char* str, size_type len);
TiXmlString& append (const char* str, size_type len);
void swap (TiXmlString& other)
{
Rep* r = rep_;
rep_ = other.rep_;
other.rep_ = r;
}
private:
void init(size_type sz) { init(sz, sz); }
void set_size(size_type sz) { rep_->str[ rep_->size = sz ] = '\0'; }
char* start() const { return rep_->str; }
char* finish() const { return rep_->str + rep_->size; }
struct Rep
{
size_type size, capacity;
char str[1];
};
void init(size_type sz, size_type cap)
{
if (cap)
{
// Lee: the original form:
// rep_ = static_cast<Rep*>(operator new(sizeof(Rep) + cap));
// doesn't work in some cases of new being overloaded. Switching
// to the normal allocation, although use an 'int' for systems
// that are overly picky about structure alignment.
const size_type bytesNeeded = sizeof(Rep) + cap;
const size_type intsNeeded = ( bytesNeeded + sizeof(int) - 1 ) / sizeof( int );
rep_ = reinterpret_cast<Rep*>( new int[ intsNeeded ] );
rep_->str[ rep_->size = sz ] = '\0';
rep_->capacity = cap;
}
else
{
rep_ = &nullrep_;
}
}
void quit()
{
if (rep_ != &nullrep_)
{
// The rep_ is really an array of ints. (see the allocator, above).
// Cast it back before delete, so the compiler won't incorrectly call destructors.
delete [] ( reinterpret_cast<int*>( rep_ ) );
}
}
Rep * rep_;
static Rep nullrep_;
} ;
inline bool operator == (const TiXmlString & a, const TiXmlString & b)
{
return ( a.length() == b.length() ) // optimization on some platforms
&& ( strcmp(a.c_str(), b.c_str()) == 0 ); // actual compare
}
inline bool operator < (const TiXmlString & a, const TiXmlString & b)
{
return strcmp(a.c_str(), b.c_str()) < 0;
}
inline bool operator != (const TiXmlString & a, const TiXmlString & b) { return !(a == b); }
inline bool operator > (const TiXmlString & a, const TiXmlString & b) { return b < a; }
inline bool operator <= (const TiXmlString & a, const TiXmlString & b) { return !(b < a); }
inline bool operator >= (const TiXmlString & a, const TiXmlString & b) { return !(a < b); }
inline bool operator == (const TiXmlString & a, const char* b) { return strcmp(a.c_str(), b) == 0; }
inline bool operator == (const char* a, const TiXmlString & b) { return b == a; }
inline bool operator != (const TiXmlString & a, const char* b) { return !(a == b); }
inline bool operator != (const char* a, const TiXmlString & b) { return !(b == a); }
TiXmlString operator + (const TiXmlString & a, const TiXmlString & b);
TiXmlString operator + (const TiXmlString & a, const char* b);
TiXmlString operator + (const char* a, const TiXmlString & b);
/*
TiXmlOutStream is an emulation of std::ostream. It is based on TiXmlString.
Only the operators that we need for TinyXML have been developped.
*/
class TiXmlOutStream : public TiXmlString
{
public :
// TiXmlOutStream << operator.
TiXmlOutStream & operator << (const TiXmlString & in)
{
*this += in;
return *this;
}
// TiXmlOutStream << operator.
TiXmlOutStream & operator << (const char * in)
{
*this += in;
return *this;
}
} ;
#endif // TIXML_STRING_INCLUDED
#endif // TIXML_USE_STL

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -1,52 +0,0 @@
/*
www.sourceforge.net/projects/tinyxml
Original code (2.0 and earlier )copyright (c) 2000-2002 Lee Thomason (www.grinninglizard.com)
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any
damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it and
redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must
not claim that you wrote the original software. If you use this
software in a product, an acknowledgment in the product documentation
would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#include "tinyxml.h"
// The goal of the seperate error file is to make the first
// step towards localization. tinyxml (currently) only supports
// english error messages, but the could now be translated.
//
// It also cleans up the code a bit.
//
const char* TiXmlBase::errorString[ TIXML_ERROR_STRING_COUNT ] =
{
"No error",
"Error",
"Failed to open file",
"Memory allocation failed.",
"Error parsing Element.",
"Failed to read Element name",
"Error reading Element value.",
"Error reading Attributes.",
"Error: empty tag.",
"Error reading end tag.",
"Error parsing Unknown.",
"Error parsing Comment.",
"Error parsing Declaration.",
"Error document empty.",
"Error null (0) or unexpected EOF found in input stream.",
"Error parsing CDATA.",
};

File diff suppressed because it is too large Load Diff

View File

@@ -1,67 +0,0 @@
Change in 1.01e (12 feb 05)
- Fix in zipOpen2 for globalcomment (Rolf Kalbermatter)
- Fix possible memory leak in unzip.c (Zoran Stevanovic)
Change in 1.01b (20 may 04)
- Integrate patch from Debian package (submited by Mark Brown)
- Add tools mztools from Xavier Roche
Change in 1.01 (8 may 04)
- fix buffer overrun risk in unzip.c (Xavier Roche)
- fix a minor buffer insecurity in minizip.c (Mike Whittaker)
Change in 1.00: (10 sept 03)
- rename to 1.00
- cosmetic code change
Change in 0.22: (19 May 03)
- crypting support (unless you define NOCRYPT)
- append file in existing zipfile
Change in 0.21: (10 Mar 03)
- bug fixes
Change in 0.17: (27 Jan 02)
- bug fixes
Change in 0.16: (19 Jan 02)
- Support of ioapi for virtualize zip file access
Change in 0.15: (19 Mar 98)
- fix memory leak in minizip.c
Change in 0.14: (10 Mar 98)
- fix bugs in minizip.c sample for zipping big file
- fix problem in month in date handling
- fix bug in unzlocal_GetCurrentFileInfoInternal in unzip.c for
comment handling
Change in 0.13: (6 Mar 98)
- fix bugs in zip.c
- add real minizip sample
Change in 0.12: (4 Mar 98)
- add zip.c and zip.h for creates .zip file
- fix change_file_date in miniunz.c for Unix (Jean-loup Gailly)
- fix miniunz.c for file without specific record for directory
Change in 0.11: (3 Mar 98)
- fix bug in unzGetCurrentFileInfo for get extra field and comment
- enhance miniunz sample, remove the bad unztst.c sample
Change in 0.10: (2 Mar 98)
- fix bug in unzReadCurrentFile
- rename unzip* to unz* function and structure
- remove Windows-like hungary notation variable name
- modify some structure in unzip.h
- add somes comment in source
- remove unzipGetcCurrentFile function
- replace ZUNZEXPORT by ZEXPORT
- add unzGetLocalExtrafield for get the local extrafield info
- add a new sample, miniunz.c
Change in 0.4: (25 Feb 98)
- suppress the type unzipFileInZip.
Only on file in the zipfile can be open at the same time
- fix somes typo in code
- added tm_unz structure in unzip_file_info (date/time in readable format)

View File

@@ -1,25 +0,0 @@
CC=cc
CFLAGS=-O -I../..
UNZ_OBJS = miniunz.o unzip.o ioapi.o ../../libz.a
ZIP_OBJS = minizip.o zip.o ioapi.o ../../libz.a
.c.o:
$(CC) -c $(CFLAGS) $*.c
all: miniunz minizip
miniunz: $(UNZ_OBJS)
$(CC) $(CFLAGS) -o $@ $(UNZ_OBJS)
minizip: $(ZIP_OBJS)
$(CC) $(CFLAGS) -o $@ $(ZIP_OBJS)
test: miniunz minizip
./minizip test readme.txt
./miniunz -l test.zip
mv readme.txt readme.old
./miniunz test.zip
clean:
/bin/rm -f *.o *~ minizip miniunz

View File

@@ -1,132 +0,0 @@
/* crypt.h -- base code for crypt/uncrypt ZIPfile
Version 1.01e, February 12th, 2005
Copyright (C) 1998-2005 Gilles Vollant
This code is a modified version of crypting code in Infozip distribution
The encryption/decryption parts of this source code (as opposed to the
non-echoing password parts) were originally written in Europe. The
whole source package can be freely distributed, including from the USA.
(Prior to January 2000, re-export from the US was a violation of US law.)
This encryption code is a direct transcription of the algorithm from
Roger Schlafly, described by Phil Katz in the file appnote.txt. This
file (appnote.txt) is distributed with the PKZIP program (even in the
version without encryption capabilities).
If you don't need crypting in your application, just define symbols
NOCRYPT and NOUNCRYPT.
This code support the "Traditional PKWARE Encryption".
The new AES encryption added on Zip format by Winzip (see the page
http://www.winzip.com/aes_info.htm ) and PKWare PKZip 5.x Strong
Encryption is not supported.
*/
#define CRC32(c, b) ((*(pcrc_32_tab+(((int)(c) ^ (b)) & 0xff))) ^ ((c) >> 8))
/***********************************************************************
* Return the next byte in the pseudo-random sequence
*/
static int decrypt_byte(unsigned long* pkeys, const unsigned long* pcrc_32_tab)
{
unsigned temp; /* POTENTIAL BUG: temp*(temp^1) may overflow in an
* unpredictable manner on 16-bit systems; not a problem
* with any known compiler so far, though */
temp = ((unsigned)(*(pkeys+2)) & 0xffff) | 2;
return (int)(((temp * (temp ^ 1)) >> 8) & 0xff);
}
/***********************************************************************
* Update the encryption keys with the next byte of plain text
*/
static int update_keys(unsigned long* pkeys,const unsigned long* pcrc_32_tab,int c)
{
(*(pkeys+0)) = CRC32((*(pkeys+0)), c);
(*(pkeys+1)) += (*(pkeys+0)) & 0xff;
(*(pkeys+1)) = (*(pkeys+1)) * 134775813L + 1;
{
register int keyshift = (int)((*(pkeys+1)) >> 24);
(*(pkeys+2)) = CRC32((*(pkeys+2)), keyshift);
}
return c;
}
/***********************************************************************
* Initialize the encryption keys and the random header according to
* the given password.
*/
static void init_keys(const char* passwd,unsigned long* pkeys,const unsigned long* pcrc_32_tab)
{
*(pkeys+0) = 305419896L;
*(pkeys+1) = 591751049L;
*(pkeys+2) = 878082192L;
while (*passwd != '\0') {
update_keys(pkeys,pcrc_32_tab,(int)*passwd);
passwd++;
}
}
#define zdecode(pkeys,pcrc_32_tab,c) \
(update_keys(pkeys,pcrc_32_tab,c ^= decrypt_byte(pkeys,pcrc_32_tab)))
#define zencode(pkeys,pcrc_32_tab,c,t) \
(t=decrypt_byte(pkeys,pcrc_32_tab), update_keys(pkeys,pcrc_32_tab,c), t^(c))
#ifdef INCLUDECRYPTINGCODE_IFCRYPTALLOWED
#define RAND_HEAD_LEN 12
/* "last resort" source for second part of crypt seed pattern */
# ifndef ZCR_SEED2
# define ZCR_SEED2 3141592654UL /* use PI as default pattern */
# endif
static int crypthead(
const char *passwd, /* password string */
unsigned char *buf, /* where to write header */
int bufSize,
unsigned long* pkeys,
const unsigned long* pcrc_32_tab,
unsigned long crcForCrypting)
{
int n; /* index in random header */
int t; /* temporary */
int c; /* random byte */
unsigned char header[RAND_HEAD_LEN-2]; /* random header */
static unsigned calls = 0; /* ensure different random header each time */
if (bufSize<RAND_HEAD_LEN)
return 0;
/* First generate RAND_HEAD_LEN-2 random bytes. We encrypt the
* output of rand() to get less predictability, since rand() is
* often poorly implemented.
*/
if (++calls == 1)
{
srand((unsigned)(time(NULL) ^ ZCR_SEED2));
}
init_keys(passwd, pkeys, pcrc_32_tab);
for (n = 0; n < RAND_HEAD_LEN-2; n++)
{
c = (rand() >> 7) & 0xff;
header[n] = (unsigned char)zencode(pkeys, pcrc_32_tab, c, t);
}
/* Encrypt random header (last two bytes is high word of crc) */
init_keys(passwd, pkeys, pcrc_32_tab);
for (n = 0; n < RAND_HEAD_LEN-2; n++)
{
buf[n] = (unsigned char)zencode(pkeys, pcrc_32_tab, header[n], t);
}
buf[n++] = zencode(pkeys, pcrc_32_tab, (int)(crcForCrypting >> 16) & 0xff, t);
buf[n++] = zencode(pkeys, pcrc_32_tab, (int)(crcForCrypting >> 24) & 0xff, t);
return n;
}
#endif

View File

@@ -1,177 +0,0 @@
/* ioapi.c -- IO base function header for compress/uncompress .zip
files using zlib + zip or unzip API
Version 1.01e, February 12th, 2005
Copyright (C) 1998-2005 Gilles Vollant
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "zlib.h"
#include "ioapi.h"
/* I've found an old Unix (a SunOS 4.1.3_U1) without all SEEK_* defined.... */
#ifndef SEEK_CUR
#define SEEK_CUR 1
#endif
#ifndef SEEK_END
#define SEEK_END 2
#endif
#ifndef SEEK_SET
#define SEEK_SET 0
#endif
voidpf ZCALLBACK fopen_file_func OF((
voidpf opaque,
const char* filename,
int mode));
uLong ZCALLBACK fread_file_func OF((
voidpf opaque,
voidpf stream,
void* buf,
uLong size));
uLong ZCALLBACK fwrite_file_func OF((
voidpf opaque,
voidpf stream,
const void* buf,
uLong size));
long ZCALLBACK ftell_file_func OF((
voidpf opaque,
voidpf stream));
long ZCALLBACK fseek_file_func OF((
voidpf opaque,
voidpf stream,
uLong offset,
int origin));
int ZCALLBACK fclose_file_func OF((
voidpf opaque,
voidpf stream));
int ZCALLBACK ferror_file_func OF((
voidpf opaque,
voidpf stream));
voidpf ZCALLBACK fopen_file_func (
voidpf opaque,
const char* filename,
int mode)
{
FILE* file = NULL;
const char* mode_fopen = NULL;
if ((mode & ZLIB_FILEFUNC_MODE_READWRITEFILTER)==ZLIB_FILEFUNC_MODE_READ)
mode_fopen = "rb";
else
if (mode & ZLIB_FILEFUNC_MODE_EXISTING)
mode_fopen = "r+b";
else
if (mode & ZLIB_FILEFUNC_MODE_CREATE)
mode_fopen = "wb";
if ((filename!=NULL) && (mode_fopen != NULL))
file = fopen(filename, mode_fopen);
return file;
}
uLong ZCALLBACK fread_file_func (
voidpf opaque,
voidpf stream,
void* buf,
uLong size)
{
uLong ret;
ret = (uLong)fread(buf, 1, (size_t)size, (FILE *)stream);
return ret;
}
uLong ZCALLBACK fwrite_file_func (
voidpf opaque,
voidpf stream,
const void* buf,
uLong size)
{
uLong ret;
ret = (uLong)fwrite(buf, 1, (size_t)size, (FILE *)stream);
return ret;
}
long ZCALLBACK ftell_file_func (
voidpf opaque,
voidpf stream)
{
long ret;
ret = ftell((FILE *)stream);
return ret;
}
long ZCALLBACK fseek_file_func (
voidpf opaque,
voidpf stream,
uLong offset,
int origin)
{
int fseek_origin=0;
long ret;
switch (origin)
{
case ZLIB_FILEFUNC_SEEK_CUR :
fseek_origin = SEEK_CUR;
break;
case ZLIB_FILEFUNC_SEEK_END :
fseek_origin = SEEK_END;
break;
case ZLIB_FILEFUNC_SEEK_SET :
fseek_origin = SEEK_SET;
break;
default: return -1;
}
ret = 0;
fseek((FILE *)stream, offset, fseek_origin);
return ret;
}
int ZCALLBACK fclose_file_func (
voidpf opaque,
voidpf stream)
{
int ret;
ret = fclose((FILE *)stream);
return ret;
}
int ZCALLBACK ferror_file_func (
voidpf opaque,
voidpf stream)
{
int ret;
ret = ferror((FILE *)stream);
return ret;
}
void fill_fopen_filefunc (
zlib_filefunc_def* pzlib_filefunc_def)
{
pzlib_filefunc_def->zopen_file = fopen_file_func;
pzlib_filefunc_def->zread_file = fread_file_func;
pzlib_filefunc_def->zwrite_file = fwrite_file_func;
pzlib_filefunc_def->ztell_file = ftell_file_func;
pzlib_filefunc_def->zseek_file = fseek_file_func;
pzlib_filefunc_def->zclose_file = fclose_file_func;
pzlib_filefunc_def->zerror_file = ferror_file_func;
pzlib_filefunc_def->opaque = NULL;
}

View File

@@ -1,75 +0,0 @@
/* ioapi.h -- IO base function header for compress/uncompress .zip
files using zlib + zip or unzip API
Version 1.01e, February 12th, 2005
Copyright (C) 1998-2005 Gilles Vollant
*/
#ifndef _ZLIBIOAPI_H
#define _ZLIBIOAPI_H
#define ZLIB_FILEFUNC_SEEK_CUR (1)
#define ZLIB_FILEFUNC_SEEK_END (2)
#define ZLIB_FILEFUNC_SEEK_SET (0)
#define ZLIB_FILEFUNC_MODE_READ (1)
#define ZLIB_FILEFUNC_MODE_WRITE (2)
#define ZLIB_FILEFUNC_MODE_READWRITEFILTER (3)
#define ZLIB_FILEFUNC_MODE_EXISTING (4)
#define ZLIB_FILEFUNC_MODE_CREATE (8)
#ifndef ZCALLBACK
#if (defined(WIN32) || defined (WINDOWS) || defined (_WINDOWS)) && defined(CALLBACK) && defined (USEWINDOWS_CALLBACK)
#define ZCALLBACK CALLBACK
#else
#define ZCALLBACK
#endif
#endif
#ifdef __cplusplus
extern "C" {
#endif
typedef voidpf (ZCALLBACK *open_file_func) OF((voidpf opaque, const char* filename, int mode));
typedef uLong (ZCALLBACK *read_file_func) OF((voidpf opaque, voidpf stream, void* buf, uLong size));
typedef uLong (ZCALLBACK *write_file_func) OF((voidpf opaque, voidpf stream, const void* buf, uLong size));
typedef long (ZCALLBACK *tell_file_func) OF((voidpf opaque, voidpf stream));
typedef long (ZCALLBACK *seek_file_func) OF((voidpf opaque, voidpf stream, uLong offset, int origin));
typedef int (ZCALLBACK *close_file_func) OF((voidpf opaque, voidpf stream));
typedef int (ZCALLBACK *testerror_file_func) OF((voidpf opaque, voidpf stream));
typedef struct zlib_filefunc_def_s
{
open_file_func zopen_file;
read_file_func zread_file;
write_file_func zwrite_file;
tell_file_func ztell_file;
seek_file_func zseek_file;
close_file_func zclose_file;
testerror_file_func zerror_file;
voidpf opaque;
} zlib_filefunc_def;
void fill_fopen_filefunc OF((zlib_filefunc_def* pzlib_filefunc_def));
#define ZREAD(filefunc,filestream,buf,size) ((*((filefunc).zread_file))((filefunc).opaque,filestream,buf,size))
#define ZWRITE(filefunc,filestream,buf,size) ((*((filefunc).zwrite_file))((filefunc).opaque,filestream,buf,size))
#define ZTELL(filefunc,filestream) ((*((filefunc).ztell_file))((filefunc).opaque,filestream))
#define ZSEEK(filefunc,filestream,pos,mode) ((*((filefunc).zseek_file))((filefunc).opaque,filestream,pos,mode))
#define ZCLOSE(filefunc,filestream) ((*((filefunc).zclose_file))((filefunc).opaque,filestream))
#define ZERROR(filefunc,filestream) ((*((filefunc).zerror_file))((filefunc).opaque,filestream))
#ifdef __cplusplus
}
#endif
#endif

View File

@@ -1,270 +0,0 @@
/* iowin32.c -- IO base function header for compress/uncompress .zip
files using zlib + zip or unzip API
This IO API version uses the Win32 API (for Microsoft Windows)
Version 1.01e, February 12th, 2005
Copyright (C) 1998-2005 Gilles Vollant
*/
#include <stdlib.h>
#include "zlib.h"
#include "ioapi.h"
#include "iowin32.h"
#ifndef INVALID_HANDLE_VALUE
#define INVALID_HANDLE_VALUE (0xFFFFFFFF)
#endif
#ifndef INVALID_SET_FILE_POINTER
#define INVALID_SET_FILE_POINTER ((DWORD)-1)
#endif
voidpf ZCALLBACK win32_open_file_func OF((
voidpf opaque,
const char* filename,
int mode));
uLong ZCALLBACK win32_read_file_func OF((
voidpf opaque,
voidpf stream,
void* buf,
uLong size));
uLong ZCALLBACK win32_write_file_func OF((
voidpf opaque,
voidpf stream,
const void* buf,
uLong size));
long ZCALLBACK win32_tell_file_func OF((
voidpf opaque,
voidpf stream));
long ZCALLBACK win32_seek_file_func OF((
voidpf opaque,
voidpf stream,
uLong offset,
int origin));
int ZCALLBACK win32_close_file_func OF((
voidpf opaque,
voidpf stream));
int ZCALLBACK win32_error_file_func OF((
voidpf opaque,
voidpf stream));
typedef struct
{
HANDLE hf;
int error;
} WIN32FILE_IOWIN;
voidpf ZCALLBACK win32_open_file_func (opaque, filename, mode)
voidpf opaque;
const char* filename;
int mode;
{
const char* mode_fopen = NULL;
DWORD dwDesiredAccess,dwCreationDisposition,dwShareMode,dwFlagsAndAttributes ;
HANDLE hFile = 0;
voidpf ret=NULL;
dwDesiredAccess = dwShareMode = dwFlagsAndAttributes = 0;
if ((mode & ZLIB_FILEFUNC_MODE_READWRITEFILTER)==ZLIB_FILEFUNC_MODE_READ)
{
dwDesiredAccess = GENERIC_READ;
dwCreationDisposition = OPEN_EXISTING;
dwShareMode = FILE_SHARE_READ;
}
else
if (mode & ZLIB_FILEFUNC_MODE_EXISTING)
{
dwDesiredAccess = GENERIC_WRITE | GENERIC_READ;
dwCreationDisposition = OPEN_EXISTING;
}
else
if (mode & ZLIB_FILEFUNC_MODE_CREATE)
{
dwDesiredAccess = GENERIC_WRITE | GENERIC_READ;
dwCreationDisposition = CREATE_ALWAYS;
}
if ((filename!=NULL) && (dwDesiredAccess != 0))
hFile = CreateFile((LPCTSTR)filename, dwDesiredAccess, dwShareMode, NULL,
dwCreationDisposition, dwFlagsAndAttributes, NULL);
if (hFile == INVALID_HANDLE_VALUE)
hFile = NULL;
if (hFile != NULL)
{
WIN32FILE_IOWIN w32fiow;
w32fiow.hf = hFile;
w32fiow.error = 0;
ret = malloc(sizeof(WIN32FILE_IOWIN));
if (ret==NULL)
CloseHandle(hFile);
else *((WIN32FILE_IOWIN*)ret) = w32fiow;
}
return ret;
}
uLong ZCALLBACK win32_read_file_func (opaque, stream, buf, size)
voidpf opaque;
voidpf stream;
void* buf;
uLong size;
{
uLong ret=0;
HANDLE hFile = NULL;
if (stream!=NULL)
hFile = ((WIN32FILE_IOWIN*)stream) -> hf;
if (hFile != NULL)
if (!ReadFile(hFile, buf, size, &ret, NULL))
{
DWORD dwErr = GetLastError();
if (dwErr == ERROR_HANDLE_EOF)
dwErr = 0;
((WIN32FILE_IOWIN*)stream) -> error=(int)dwErr;
}
return ret;
}
uLong ZCALLBACK win32_write_file_func (opaque, stream, buf, size)
voidpf opaque;
voidpf stream;
const void* buf;
uLong size;
{
uLong ret=0;
HANDLE hFile = NULL;
if (stream!=NULL)
hFile = ((WIN32FILE_IOWIN*)stream) -> hf;
if (hFile !=NULL)
if (!WriteFile(hFile, buf, size, &ret, NULL))
{
DWORD dwErr = GetLastError();
if (dwErr == ERROR_HANDLE_EOF)
dwErr = 0;
((WIN32FILE_IOWIN*)stream) -> error=(int)dwErr;
}
return ret;
}
long ZCALLBACK win32_tell_file_func (opaque, stream)
voidpf opaque;
voidpf stream;
{
long ret=-1;
HANDLE hFile = NULL;
if (stream!=NULL)
hFile = ((WIN32FILE_IOWIN*)stream) -> hf;
if (hFile != NULL)
{
DWORD dwSet = SetFilePointer(hFile, 0, NULL, FILE_CURRENT);
if (dwSet == INVALID_SET_FILE_POINTER)
{
DWORD dwErr = GetLastError();
((WIN32FILE_IOWIN*)stream) -> error=(int)dwErr;
ret = -1;
}
else
ret=(long)dwSet;
}
return ret;
}
long ZCALLBACK win32_seek_file_func (opaque, stream, offset, origin)
voidpf opaque;
voidpf stream;
uLong offset;
int origin;
{
DWORD dwMoveMethod=0xFFFFFFFF;
HANDLE hFile = NULL;
long ret=-1;
if (stream!=NULL)
hFile = ((WIN32FILE_IOWIN*)stream) -> hf;
switch (origin)
{
case ZLIB_FILEFUNC_SEEK_CUR :
dwMoveMethod = FILE_CURRENT;
break;
case ZLIB_FILEFUNC_SEEK_END :
dwMoveMethod = FILE_END;
break;
case ZLIB_FILEFUNC_SEEK_SET :
dwMoveMethod = FILE_BEGIN;
break;
default: return -1;
}
if (hFile != NULL)
{
DWORD dwSet = SetFilePointer(hFile, offset, NULL, dwMoveMethod);
if (dwSet == INVALID_SET_FILE_POINTER)
{
DWORD dwErr = GetLastError();
((WIN32FILE_IOWIN*)stream) -> error=(int)dwErr;
ret = -1;
}
else
ret=0;
}
return ret;
}
int ZCALLBACK win32_close_file_func (opaque, stream)
voidpf opaque;
voidpf stream;
{
int ret=-1;
if (stream!=NULL)
{
HANDLE hFile;
hFile = ((WIN32FILE_IOWIN*)stream) -> hf;
if (hFile != NULL)
{
CloseHandle(hFile);
ret=0;
}
free(stream);
}
return ret;
}
int ZCALLBACK win32_error_file_func (opaque, stream)
voidpf opaque;
voidpf stream;
{
int ret=-1;
if (stream!=NULL)
{
ret = ((WIN32FILE_IOWIN*)stream) -> error;
}
return ret;
}
void fill_win32_filefunc (pzlib_filefunc_def)
zlib_filefunc_def* pzlib_filefunc_def;
{
pzlib_filefunc_def->zopen_file = win32_open_file_func;
pzlib_filefunc_def->zread_file = win32_read_file_func;
pzlib_filefunc_def->zwrite_file = win32_write_file_func;
pzlib_filefunc_def->ztell_file = win32_tell_file_func;
pzlib_filefunc_def->zseek_file = win32_seek_file_func;
pzlib_filefunc_def->zclose_file = win32_close_file_func;
pzlib_filefunc_def->zerror_file = win32_error_file_func;
pzlib_filefunc_def->opaque=NULL;
}

View File

@@ -1,21 +0,0 @@
/* iowin32.h -- IO base function header for compress/uncompress .zip
files using zlib + zip or unzip API
This IO API version uses the Win32 API (for Microsoft Windows)
Version 1.01e, February 12th, 2005
Copyright (C) 1998-2005 Gilles Vollant
*/
#include <windows.h>
#ifdef __cplusplus
extern "C" {
#endif
void fill_win32_filefunc OF((zlib_filefunc_def* pzlib_filefunc_def));
#ifdef __cplusplus
}
#endif

View File

@@ -1,585 +0,0 @@
/*
miniunz.c
Version 1.01e, February 12th, 2005
Copyright (C) 1998-2005 Gilles Vollant
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <errno.h>
#include <fcntl.h>
#ifdef unix
# include <unistd.h>
# include <utime.h>
#else
# include <direct.h>
# include <io.h>
#endif
#include "unzip.h"
#define CASESENSITIVITY (0)
#define WRITEBUFFERSIZE (8192)
#define MAXFILENAME (256)
#ifdef WIN32
#define USEWIN32IOAPI
#include "iowin32.h"
#endif
/*
mini unzip, demo of unzip package
usage :
Usage : miniunz [-exvlo] file.zip [file_to_extract] [-d extractdir]
list the file in the zipfile, and print the content of FILE_ID.ZIP or README.TXT
if it exists
*/
/* change_file_date : change the date/time of a file
filename : the filename of the file where date/time must be modified
dosdate : the new date at the MSDos format (4 bytes)
tmu_date : the SAME new date at the tm_unz format */
void change_file_date(filename,dosdate,tmu_date)
const char *filename;
uLong dosdate;
tm_unz tmu_date;
{
#ifdef WIN32
HANDLE hFile;
FILETIME ftm,ftLocal,ftCreate,ftLastAcc,ftLastWrite;
hFile = CreateFile(filename,GENERIC_READ | GENERIC_WRITE,
0,NULL,OPEN_EXISTING,0,NULL);
GetFileTime(hFile,&ftCreate,&ftLastAcc,&ftLastWrite);
DosDateTimeToFileTime((WORD)(dosdate>>16),(WORD)dosdate,&ftLocal);
LocalFileTimeToFileTime(&ftLocal,&ftm);
SetFileTime(hFile,&ftm,&ftLastAcc,&ftm);
CloseHandle(hFile);
#else
#ifdef unix
struct utimbuf ut;
struct tm newdate;
newdate.tm_sec = tmu_date.tm_sec;
newdate.tm_min=tmu_date.tm_min;
newdate.tm_hour=tmu_date.tm_hour;
newdate.tm_mday=tmu_date.tm_mday;
newdate.tm_mon=tmu_date.tm_mon;
if (tmu_date.tm_year > 1900)
newdate.tm_year=tmu_date.tm_year - 1900;
else
newdate.tm_year=tmu_date.tm_year ;
newdate.tm_isdst=-1;
ut.actime=ut.modtime=mktime(&newdate);
utime(filename,&ut);
#endif
#endif
}
/* mymkdir and change_file_date are not 100 % portable
As I don't know well Unix, I wait feedback for the unix portion */
int mymkdir(dirname)
const char* dirname;
{
int ret=0;
#ifdef WIN32
ret = mkdir(dirname);
#else
#ifdef unix
ret = mkdir (dirname,0775);
#endif
#endif
return ret;
}
int makedir (newdir)
char *newdir;
{
char *buffer ;
char *p;
int len = (int)strlen(newdir);
if (len <= 0)
return 0;
buffer = (char*)malloc(len+1);
strcpy(buffer,newdir);
if (buffer[len-1] == '/') {
buffer[len-1] = '\0';
}
if (mymkdir(buffer) == 0)
{
free(buffer);
return 1;
}
p = buffer+1;
while (1)
{
char hold;
while(*p && *p != '\\' && *p != '/')
p++;
hold = *p;
*p = 0;
if ((mymkdir(buffer) == -1) && (errno == ENOENT))
{
printf("couldn't create directory %s\n",buffer);
free(buffer);
return 0;
}
if (hold == 0)
break;
*p++ = hold;
}
free(buffer);
return 1;
}
void do_banner()
{
printf("MiniUnz 1.01b, demo of zLib + Unz package written by Gilles Vollant\n");
printf("more info at http://www.winimage.com/zLibDll/unzip.html\n\n");
}
void do_help()
{
printf("Usage : miniunz [-e] [-x] [-v] [-l] [-o] [-p password] file.zip [file_to_extr.] [-d extractdir]\n\n" \
" -e Extract without pathname (junk paths)\n" \
" -x Extract with pathname\n" \
" -v list files\n" \
" -l list files\n" \
" -d directory to extract into\n" \
" -o overwrite files without prompting\n" \
" -p extract crypted file using password\n\n");
}
int do_list(uf)
unzFile uf;
{
uLong i;
unz_global_info gi;
int err;
err = unzGetGlobalInfo (uf,&gi);
if (err!=UNZ_OK)
printf("error %d with zipfile in unzGetGlobalInfo \n",err);
printf(" Length Method Size Ratio Date Time CRC-32 Name\n");
printf(" ------ ------ ---- ----- ---- ---- ------ ----\n");
for (i=0;i<gi.number_entry;i++)
{
char filename_inzip[256];
unz_file_info file_info;
uLong ratio=0;
const char *string_method;
char charCrypt=' ';
err = unzGetCurrentFileInfo(uf,&file_info,filename_inzip,sizeof(filename_inzip),NULL,0,NULL,0);
if (err!=UNZ_OK)
{
printf("error %d with zipfile in unzGetCurrentFileInfo\n",err);
break;
}
if (file_info.uncompressed_size>0)
ratio = (file_info.compressed_size*100)/file_info.uncompressed_size;
/* display a '*' if the file is crypted */
if ((file_info.flag & 1) != 0)
charCrypt='*';
if (file_info.compression_method==0)
string_method="Stored";
else
if (file_info.compression_method==Z_DEFLATED)
{
uInt iLevel=(uInt)((file_info.flag & 0x6)/2);
if (iLevel==0)
string_method="Defl:N";
else if (iLevel==1)
string_method="Defl:X";
else if ((iLevel==2) || (iLevel==3))
string_method="Defl:F"; /* 2:fast , 3 : extra fast*/
}
else
string_method="Unkn. ";
printf("%7lu %6s%c%7lu %3lu%% %2.2lu-%2.2lu-%2.2lu %2.2lu:%2.2lu %8.8lx %s\n",
file_info.uncompressed_size,string_method,
charCrypt,
file_info.compressed_size,
ratio,
(uLong)file_info.tmu_date.tm_mon + 1,
(uLong)file_info.tmu_date.tm_mday,
(uLong)file_info.tmu_date.tm_year % 100,
(uLong)file_info.tmu_date.tm_hour,(uLong)file_info.tmu_date.tm_min,
(uLong)file_info.crc,filename_inzip);
if ((i+1)<gi.number_entry)
{
err = unzGoToNextFile(uf);
if (err!=UNZ_OK)
{
printf("error %d with zipfile in unzGoToNextFile\n",err);
break;
}
}
}
return 0;
}
int do_extract_currentfile(uf,popt_extract_without_path,popt_overwrite,password)
unzFile uf;
const int* popt_extract_without_path;
int* popt_overwrite;
const char* password;
{
char filename_inzip[256];
char* filename_withoutpath;
char* p;
int err=UNZ_OK;
FILE *fout=NULL;
void* buf;
uInt size_buf;
unz_file_info file_info;
uLong ratio=0;
err = unzGetCurrentFileInfo(uf,&file_info,filename_inzip,sizeof(filename_inzip),NULL,0,NULL,0);
if (err!=UNZ_OK)
{
printf("error %d with zipfile in unzGetCurrentFileInfo\n",err);
return err;
}
size_buf = WRITEBUFFERSIZE;
buf = (void*)malloc(size_buf);
if (buf==NULL)
{
printf("Error allocating memory\n");
return UNZ_INTERNALERROR;
}
p = filename_withoutpath = filename_inzip;
while ((*p) != '\0')
{
if (((*p)=='/') || ((*p)=='\\'))
filename_withoutpath = p+1;
p++;
}
if ((*filename_withoutpath)=='\0')
{
if ((*popt_extract_without_path)==0)
{
printf("creating directory: %s\n",filename_inzip);
mymkdir(filename_inzip);
}
}
else
{
const char* write_filename;
int skip=0;
if ((*popt_extract_without_path)==0)
write_filename = filename_inzip;
else
write_filename = filename_withoutpath;
err = unzOpenCurrentFilePassword(uf,password);
if (err!=UNZ_OK)
{
printf("error %d with zipfile in unzOpenCurrentFilePassword\n",err);
}
if (((*popt_overwrite)==0) && (err==UNZ_OK))
{
char rep=0;
FILE* ftestexist;
ftestexist = fopen(write_filename,"rb");
if (ftestexist!=NULL)
{
fclose(ftestexist);
do
{
char answer[128];
int ret;
printf("The file %s exists. Overwrite ? [y]es, [n]o, [A]ll: ",write_filename);
ret = scanf("%1s",answer);
if (ret != 1)
{
exit(EXIT_FAILURE);
}
rep = answer[0] ;
if ((rep>='a') && (rep<='z'))
rep -= 0x20;
}
while ((rep!='Y') && (rep!='N') && (rep!='A'));
}
if (rep == 'N')
skip = 1;
if (rep == 'A')
*popt_overwrite=1;
}
if ((skip==0) && (err==UNZ_OK))
{
fout=fopen(write_filename,"wb");
/* some zipfile don't contain directory alone before file */
if ((fout==NULL) && ((*popt_extract_without_path)==0) &&
(filename_withoutpath!=(char*)filename_inzip))
{
char c=*(filename_withoutpath-1);
*(filename_withoutpath-1)='\0';
makedir(write_filename);
*(filename_withoutpath-1)=c;
fout=fopen(write_filename,"wb");
}
if (fout==NULL)
{
printf("error opening %s\n",write_filename);
}
}
if (fout!=NULL)
{
printf(" extracting: %s\n",write_filename);
do
{
err = unzReadCurrentFile(uf,buf,size_buf);
if (err<0)
{
printf("error %d with zipfile in unzReadCurrentFile\n",err);
break;
}
if (err>0)
if (fwrite(buf,err,1,fout)!=1)
{
printf("error in writing extracted file\n");
err=UNZ_ERRNO;
break;
}
}
while (err>0);
if (fout)
fclose(fout);
if (err==0)
change_file_date(write_filename,file_info.dosDate,
file_info.tmu_date);
}
if (err==UNZ_OK)
{
err = unzCloseCurrentFile (uf);
if (err!=UNZ_OK)
{
printf("error %d with zipfile in unzCloseCurrentFile\n",err);
}
}
else
unzCloseCurrentFile(uf); /* don't lose the error */
}
free(buf);
return err;
}
int do_extract(uf,opt_extract_without_path,opt_overwrite,password)
unzFile uf;
int opt_extract_without_path;
int opt_overwrite;
const char* password;
{
uLong i;
unz_global_info gi;
int err;
FILE* fout=NULL;
err = unzGetGlobalInfo (uf,&gi);
if (err!=UNZ_OK)
printf("error %d with zipfile in unzGetGlobalInfo \n",err);
for (i=0;i<gi.number_entry;i++)
{
if (do_extract_currentfile(uf,&opt_extract_without_path,
&opt_overwrite,
password) != UNZ_OK)
break;
if ((i+1)<gi.number_entry)
{
err = unzGoToNextFile(uf);
if (err!=UNZ_OK)
{
printf("error %d with zipfile in unzGoToNextFile\n",err);
break;
}
}
}
return 0;
}
int do_extract_onefile(uf,filename,opt_extract_without_path,opt_overwrite,password)
unzFile uf;
const char* filename;
int opt_extract_without_path;
int opt_overwrite;
const char* password;
{
int err = UNZ_OK;
if (unzLocateFile(uf,filename,CASESENSITIVITY)!=UNZ_OK)
{
printf("file %s not found in the zipfile\n",filename);
return 2;
}
if (do_extract_currentfile(uf,&opt_extract_without_path,
&opt_overwrite,
password) == UNZ_OK)
return 0;
else
return 1;
}
int main(argc,argv)
int argc;
char *argv[];
{
const char *zipfilename=NULL;
const char *filename_to_extract=NULL;
const char *password=NULL;
char filename_try[MAXFILENAME+16] = "";
int i;
int opt_do_list=0;
int opt_do_extract=1;
int opt_do_extract_withoutpath=0;
int opt_overwrite=0;
int opt_extractdir=0;
const char *dirname=NULL;
unzFile uf=NULL;
do_banner();
if (argc==1)
{
do_help();
return 0;
}
else
{
for (i=1;i<argc;i++)
{
if ((*argv[i])=='-')
{
const char *p=argv[i]+1;
while ((*p)!='\0')
{
char c=*(p++);;
if ((c=='l') || (c=='L'))
opt_do_list = 1;
if ((c=='v') || (c=='V'))
opt_do_list = 1;
if ((c=='x') || (c=='X'))
opt_do_extract = 1;
if ((c=='e') || (c=='E'))
opt_do_extract = opt_do_extract_withoutpath = 1;
if ((c=='o') || (c=='O'))
opt_overwrite=1;
if ((c=='d') || (c=='D'))
{
opt_extractdir=1;
dirname=argv[i+1];
}
if (((c=='p') || (c=='P')) && (i+1<argc))
{
password=argv[i+1];
i++;
}
}
}
else
{
if (zipfilename == NULL)
zipfilename = argv[i];
else if ((filename_to_extract==NULL) && (!opt_extractdir))
filename_to_extract = argv[i] ;
}
}
}
if (zipfilename!=NULL)
{
# ifdef USEWIN32IOAPI
zlib_filefunc_def ffunc;
# endif
strncpy(filename_try, zipfilename,MAXFILENAME-1);
/* strncpy doesnt append the trailing NULL, of the string is too long. */
filename_try[ MAXFILENAME ] = '\0';
# ifdef USEWIN32IOAPI
fill_win32_filefunc(&ffunc);
uf = unzOpen2(zipfilename,&ffunc);
# else
uf = unzOpen(zipfilename);
# endif
if (uf==NULL)
{
strcat(filename_try,".zip");
# ifdef USEWIN32IOAPI
uf = unzOpen2(filename_try,&ffunc);
# else
uf = unzOpen(filename_try);
# endif
}
}
if (uf==NULL)
{
printf("Cannot open %s or %s.zip\n",zipfilename,zipfilename);
return 1;
}
printf("%s opened\n",filename_try);
if (opt_do_list==1)
return do_list(uf);
else if (opt_do_extract==1)
{
if (opt_extractdir && chdir(dirname))
{
printf("Error changing into %s, aborting\n", dirname);
exit(-1);
}
if (filename_to_extract == NULL)
return do_extract(uf,opt_do_extract_withoutpath,opt_overwrite,password);
else
return do_extract_onefile(uf,filename_to_extract,
opt_do_extract_withoutpath,opt_overwrite,password);
}
unzCloseCurrentFile(uf);
return 0;
}

View File

@@ -1,420 +0,0 @@
/*
minizip.c
Version 1.01e, February 12th, 2005
Copyright (C) 1998-2005 Gilles Vollant
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <errno.h>
#include <fcntl.h>
#ifdef unix
# include <unistd.h>
# include <utime.h>
# include <sys/types.h>
# include <sys/stat.h>
#else
# include <direct.h>
# include <io.h>
#endif
#include "zip.h"
#ifdef WIN32
#define USEWIN32IOAPI
#include "iowin32.h"
#endif
#define WRITEBUFFERSIZE (16384)
#define MAXFILENAME (256)
#ifdef WIN32
uLong filetime(f, tmzip, dt)
char *f; /* name of file to get info on */
tm_zip *tmzip; /* return value: access, modific. and creation times */
uLong *dt; /* dostime */
{
int ret = 0;
{
FILETIME ftLocal;
HANDLE hFind;
WIN32_FIND_DATA ff32;
hFind = FindFirstFile(f,&ff32);
if (hFind != INVALID_HANDLE_VALUE)
{
FileTimeToLocalFileTime(&(ff32.ftLastWriteTime),&ftLocal);
FileTimeToDosDateTime(&ftLocal,((LPWORD)dt)+1,((LPWORD)dt)+0);
FindClose(hFind);
ret = 1;
}
}
return ret;
}
#else
#ifdef unix
uLong filetime(f, tmzip, dt)
char *f; /* name of file to get info on */
tm_zip *tmzip; /* return value: access, modific. and creation times */
uLong *dt; /* dostime */
{
int ret=0;
struct stat s; /* results of stat() */
struct tm* filedate;
time_t tm_t=0;
if (strcmp(f,"-")!=0)
{
char name[MAXFILENAME+1];
int len = strlen(f);
if (len > MAXFILENAME)
len = MAXFILENAME;
strncpy(name, f,MAXFILENAME-1);
/* strncpy doesnt append the trailing NULL, of the string is too long. */
name[ MAXFILENAME ] = '\0';
if (name[len - 1] == '/')
name[len - 1] = '\0';
/* not all systems allow stat'ing a file with / appended */
if (stat(name,&s)==0)
{
tm_t = s.st_mtime;
ret = 1;
}
}
filedate = localtime(&tm_t);
tmzip->tm_sec = filedate->tm_sec;
tmzip->tm_min = filedate->tm_min;
tmzip->tm_hour = filedate->tm_hour;
tmzip->tm_mday = filedate->tm_mday;
tmzip->tm_mon = filedate->tm_mon ;
tmzip->tm_year = filedate->tm_year;
return ret;
}
#else
uLong filetime(f, tmzip, dt)
char *f; /* name of file to get info on */
tm_zip *tmzip; /* return value: access, modific. and creation times */
uLong *dt; /* dostime */
{
return 0;
}
#endif
#endif
int check_exist_file(filename)
const char* filename;
{
FILE* ftestexist;
int ret = 1;
ftestexist = fopen(filename,"rb");
if (ftestexist==NULL)
ret = 0;
else
fclose(ftestexist);
return ret;
}
void do_banner()
{
printf("MiniZip 1.01b, demo of zLib + Zip package written by Gilles Vollant\n");
printf("more info at http://www.winimage.com/zLibDll/unzip.html\n\n");
}
void do_help()
{
printf("Usage : minizip [-o] [-a] [-0 to -9] [-p password] file.zip [files_to_add]\n\n" \
" -o Overwrite existing file.zip\n" \
" -a Append to existing file.zip\n" \
" -0 Store only\n" \
" -1 Compress faster\n" \
" -9 Compress better\n\n");
}
/* calculate the CRC32 of a file,
because to encrypt a file, we need known the CRC32 of the file before */
int getFileCrc(const char* filenameinzip,void*buf,unsigned long size_buf,unsigned long* result_crc)
{
unsigned long calculate_crc=0;
int err=ZIP_OK;
FILE * fin = fopen(filenameinzip,"rb");
unsigned long size_read = 0;
unsigned long total_read = 0;
if (fin==NULL)
{
err = ZIP_ERRNO;
}
if (err == ZIP_OK)
do
{
err = ZIP_OK;
size_read = (int)fread(buf,1,size_buf,fin);
if (size_read < size_buf)
if (feof(fin)==0)
{
printf("error in reading %s\n",filenameinzip);
err = ZIP_ERRNO;
}
if (size_read>0)
calculate_crc = crc32(calculate_crc,buf,size_read);
total_read += size_read;
} while ((err == ZIP_OK) && (size_read>0));
if (fin)
fclose(fin);
*result_crc=calculate_crc;
printf("file %s crc %x\n",filenameinzip,calculate_crc);
return err;
}
int main(argc,argv)
int argc;
char *argv[];
{
int i;
int opt_overwrite=0;
int opt_compress_level=Z_DEFAULT_COMPRESSION;
int zipfilenamearg = 0;
char filename_try[MAXFILENAME+16];
int zipok;
int err=0;
int size_buf=0;
void* buf=NULL;
const char* password=NULL;
do_banner();
if (argc==1)
{
do_help();
return 0;
}
else
{
for (i=1;i<argc;i++)
{
if ((*argv[i])=='-')
{
const char *p=argv[i]+1;
while ((*p)!='\0')
{
char c=*(p++);;
if ((c=='o') || (c=='O'))
opt_overwrite = 1;
if ((c=='a') || (c=='A'))
opt_overwrite = 2;
if ((c>='0') && (c<='9'))
opt_compress_level = c-'0';
if (((c=='p') || (c=='P')) && (i+1<argc))
{
password=argv[i+1];
i++;
}
}
}
else
if (zipfilenamearg == 0)
zipfilenamearg = i ;
}
}
size_buf = WRITEBUFFERSIZE;
buf = (void*)malloc(size_buf);
if (buf==NULL)
{
printf("Error allocating memory\n");
return ZIP_INTERNALERROR;
}
if (zipfilenamearg==0)
zipok=0;
else
{
int i,len;
int dot_found=0;
zipok = 1 ;
strncpy(filename_try, argv[zipfilenamearg],MAXFILENAME-1);
/* strncpy doesnt append the trailing NULL, of the string is too long. */
filename_try[ MAXFILENAME ] = '\0';
len=(int)strlen(filename_try);
for (i=0;i<len;i++)
if (filename_try[i]=='.')
dot_found=1;
if (dot_found==0)
strcat(filename_try,".zip");
if (opt_overwrite==2)
{
/* if the file don't exist, we not append file */
if (check_exist_file(filename_try)==0)
opt_overwrite=1;
}
else
if (opt_overwrite==0)
if (check_exist_file(filename_try)!=0)
{
char rep=0;
do
{
char answer[128];
int ret;
printf("The file %s exists. Overwrite ? [y]es, [n]o, [a]ppend : ",filename_try);
ret = scanf("%1s",answer);
if (ret != 1)
{
exit(EXIT_FAILURE);
}
rep = answer[0] ;
if ((rep>='a') && (rep<='z'))
rep -= 0x20;
}
while ((rep!='Y') && (rep!='N') && (rep!='A'));
if (rep=='N')
zipok = 0;
if (rep=='A')
opt_overwrite = 2;
}
}
if (zipok==1)
{
zipFile zf;
int errclose;
# ifdef USEWIN32IOAPI
zlib_filefunc_def ffunc;
fill_win32_filefunc(&ffunc);
zf = zipOpen2(filename_try,(opt_overwrite==2) ? 2 : 0,NULL,&ffunc);
# else
zf = zipOpen(filename_try,(opt_overwrite==2) ? 2 : 0);
# endif
if (zf == NULL)
{
printf("error opening %s\n",filename_try);
err= ZIP_ERRNO;
}
else
printf("creating %s\n",filename_try);
for (i=zipfilenamearg+1;(i<argc) && (err==ZIP_OK);i++)
{
if (!((((*(argv[i]))=='-') || ((*(argv[i]))=='/')) &&
((argv[i][1]=='o') || (argv[i][1]=='O') ||
(argv[i][1]=='a') || (argv[i][1]=='A') ||
(argv[i][1]=='p') || (argv[i][1]=='P') ||
((argv[i][1]>='0') || (argv[i][1]<='9'))) &&
(strlen(argv[i]) == 2)))
{
FILE * fin;
int size_read;
const char* filenameinzip = argv[i];
zip_fileinfo zi;
unsigned long crcFile=0;
zi.tmz_date.tm_sec = zi.tmz_date.tm_min = zi.tmz_date.tm_hour =
zi.tmz_date.tm_mday = zi.tmz_date.tm_mon = zi.tmz_date.tm_year = 0;
zi.dosDate = 0;
zi.internal_fa = 0;
zi.external_fa = 0;
filetime(filenameinzip,&zi.tmz_date,&zi.dosDate);
/*
err = zipOpenNewFileInZip(zf,filenameinzip,&zi,
NULL,0,NULL,0,NULL / * comment * /,
(opt_compress_level != 0) ? Z_DEFLATED : 0,
opt_compress_level);
*/
if ((password != NULL) && (err==ZIP_OK))
err = getFileCrc(filenameinzip,buf,size_buf,&crcFile);
err = zipOpenNewFileInZip3(zf,filenameinzip,&zi,
NULL,0,NULL,0,NULL /* comment*/,
(opt_compress_level != 0) ? Z_DEFLATED : 0,
opt_compress_level,0,
/* -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, */
-MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY,
password,crcFile);
if (err != ZIP_OK)
printf("error in opening %s in zipfile\n",filenameinzip);
else
{
fin = fopen(filenameinzip,"rb");
if (fin==NULL)
{
err=ZIP_ERRNO;
printf("error in opening %s for reading\n",filenameinzip);
}
}
if (err == ZIP_OK)
do
{
err = ZIP_OK;
size_read = (int)fread(buf,1,size_buf,fin);
if (size_read < size_buf)
if (feof(fin)==0)
{
printf("error in reading %s\n",filenameinzip);
err = ZIP_ERRNO;
}
if (size_read>0)
{
err = zipWriteInFileInZip (zf,buf,size_read);
if (err<0)
{
printf("error in writing %s in the zipfile\n",
filenameinzip);
}
}
} while ((err == ZIP_OK) && (size_read>0));
if (fin)
fclose(fin);
if (err<0)
err=ZIP_ERRNO;
else
{
err = zipCloseFileInZip(zf);
if (err!=ZIP_OK)
printf("error in closing %s in the zipfile\n",
filenameinzip);
}
}
}
errclose = zipClose(zf,NULL);
if (errclose != ZIP_OK)
printf("error in closing %s\n",filename_try);
}
else
{
do_help();
}
free(buf);
return 0;
}

View File

@@ -1,281 +0,0 @@
/*
Additional tools for Minizip
Code: Xavier Roche '2004
License: Same as ZLIB (www.gzip.org)
*/
/* Code */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "zlib.h"
#include "unzip.h"
#define READ_8(adr) ((unsigned char)*(adr))
#define READ_16(adr) ( READ_8(adr) | (READ_8(adr+1) << 8) )
#define READ_32(adr) ( READ_16(adr) | (READ_16((adr)+2) << 16) )
#define WRITE_8(buff, n) do { \
*((unsigned char*)(buff)) = (unsigned char) ((n) & 0xff); \
} while(0)
#define WRITE_16(buff, n) do { \
WRITE_8((unsigned char*)(buff), n); \
WRITE_8(((unsigned char*)(buff)) + 1, (n) >> 8); \
} while(0)
#define WRITE_32(buff, n) do { \
WRITE_16((unsigned char*)(buff), (n) & 0xffff); \
WRITE_16((unsigned char*)(buff) + 2, (n) >> 16); \
} while(0)
extern int ZEXPORT unzRepair(file, fileOut, fileOutTmp, nRecovered, bytesRecovered)
const char* file;
const char* fileOut;
const char* fileOutTmp;
uLong* nRecovered;
uLong* bytesRecovered;
{
int err = Z_OK;
FILE* fpZip = fopen(file, "rb");
FILE* fpOut = fopen(fileOut, "wb");
FILE* fpOutCD = fopen(fileOutTmp, "wb");
if (fpZip != NULL && fpOut != NULL) {
int entries = 0;
uLong totalBytes = 0;
char header[30];
char filename[256];
char extra[1024];
int offset = 0;
int offsetCD = 0;
while ( fread(header, 1, 30, fpZip) == 30 ) {
int currentOffset = offset;
/* File entry */
if (READ_32(header) == 0x04034b50) {
unsigned int version = READ_16(header + 4);
unsigned int gpflag = READ_16(header + 6);
unsigned int method = READ_16(header + 8);
unsigned int filetime = READ_16(header + 10);
unsigned int filedate = READ_16(header + 12);
unsigned int crc = READ_32(header + 14); /* crc */
unsigned int cpsize = READ_32(header + 18); /* compressed size */
unsigned int uncpsize = READ_32(header + 22); /* uncompressed sz */
unsigned int fnsize = READ_16(header + 26); /* file name length */
unsigned int extsize = READ_16(header + 28); /* extra field length */
filename[0] = extra[0] = '\0';
/* Header */
if (fwrite(header, 1, 30, fpOut) == 30) {
offset += 30;
} else {
err = Z_ERRNO;
break;
}
/* Filename */
if (fnsize > 0) {
if (fread(filename, 1, fnsize, fpZip) == fnsize) {
if (fwrite(filename, 1, fnsize, fpOut) == fnsize) {
offset += fnsize;
} else {
err = Z_ERRNO;
break;
}
} else {
err = Z_ERRNO;
break;
}
} else {
err = Z_STREAM_ERROR;
break;
}
/* Extra field */
if (extsize > 0) {
if (fread(extra, 1, extsize, fpZip) == extsize) {
if (fwrite(extra, 1, extsize, fpOut) == extsize) {
offset += extsize;
} else {
err = Z_ERRNO;
break;
}
} else {
err = Z_ERRNO;
break;
}
}
/* Data */
{
int dataSize = cpsize;
if (dataSize == 0) {
dataSize = uncpsize;
}
if (dataSize > 0) {
char* data = malloc(dataSize);
if (data != NULL) {
if ((int)fread(data, 1, dataSize, fpZip) == dataSize) {
if ((int)fwrite(data, 1, dataSize, fpOut) == dataSize) {
offset += dataSize;
totalBytes += dataSize;
} else {
err = Z_ERRNO;
}
} else {
err = Z_ERRNO;
}
free(data);
if (err != Z_OK) {
break;
}
} else {
err = Z_MEM_ERROR;
break;
}
}
}
/* Central directory entry */
{
char header[46];
char* comment = "";
int comsize = (int) strlen(comment);
WRITE_32(header, 0x02014b50);
WRITE_16(header + 4, version);
WRITE_16(header + 6, version);
WRITE_16(header + 8, gpflag);
WRITE_16(header + 10, method);
WRITE_16(header + 12, filetime);
WRITE_16(header + 14, filedate);
WRITE_32(header + 16, crc);
WRITE_32(header + 20, cpsize);
WRITE_32(header + 24, uncpsize);
WRITE_16(header + 28, fnsize);
WRITE_16(header + 30, extsize);
WRITE_16(header + 32, comsize);
WRITE_16(header + 34, 0); /* disk # */
WRITE_16(header + 36, 0); /* int attrb */
WRITE_32(header + 38, 0); /* ext attrb */
WRITE_32(header + 42, currentOffset);
/* Header */
if (fwrite(header, 1, 46, fpOutCD) == 46) {
offsetCD += 46;
/* Filename */
if (fnsize > 0) {
if (fwrite(filename, 1, fnsize, fpOutCD) == fnsize) {
offsetCD += fnsize;
} else {
err = Z_ERRNO;
break;
}
} else {
err = Z_STREAM_ERROR;
break;
}
/* Extra field */
if (extsize > 0) {
if (fwrite(extra, 1, extsize, fpOutCD) == extsize) {
offsetCD += extsize;
} else {
err = Z_ERRNO;
break;
}
}
/* Comment field */
if (comsize > 0) {
if ((int)fwrite(comment, 1, comsize, fpOutCD) == comsize) {
offsetCD += comsize;
} else {
err = Z_ERRNO;
break;
}
}
} else {
err = Z_ERRNO;
break;
}
}
/* Success */
entries++;
} else {
break;
}
}
/* Final central directory */
{
int entriesZip = entries;
char header[22];
char* comment = ""; // "ZIP File recovered by zlib/minizip/mztools";
int comsize = (int) strlen(comment);
if (entriesZip > 0xffff) {
entriesZip = 0xffff;
}
WRITE_32(header, 0x06054b50);
WRITE_16(header + 4, 0); /* disk # */
WRITE_16(header + 6, 0); /* disk # */
WRITE_16(header + 8, entriesZip); /* hack */
WRITE_16(header + 10, entriesZip); /* hack */
WRITE_32(header + 12, offsetCD); /* size of CD */
WRITE_32(header + 16, offset); /* offset to CD */
WRITE_16(header + 20, comsize); /* comment */
/* Header */
if (fwrite(header, 1, 22, fpOutCD) == 22) {
/* Comment field */
if (comsize > 0) {
if ((int)fwrite(comment, 1, comsize, fpOutCD) != comsize) {
err = Z_ERRNO;
}
}
} else {
err = Z_ERRNO;
}
}
/* Final merge (file + central directory) */
fclose(fpOutCD);
if (err == Z_OK) {
fpOutCD = fopen(fileOutTmp, "rb");
if (fpOutCD != NULL) {
int nRead;
char buffer[8192];
while ( (nRead = (int)fread(buffer, 1, sizeof(buffer), fpOutCD)) > 0) {
if ((int)fwrite(buffer, 1, nRead, fpOut) != nRead) {
err = Z_ERRNO;
break;
}
}
fclose(fpOutCD);
}
}
/* Close */
fclose(fpZip);
fclose(fpOut);
/* Wipe temporary file */
(void)remove(fileOutTmp);
/* Number of recovered entries */
if (err == Z_OK) {
if (nRecovered != NULL) {
*nRecovered = entries;
}
if (bytesRecovered != NULL) {
*bytesRecovered = totalBytes;
}
}
} else {
err = Z_STREAM_ERROR;
}
return err;
}

View File

@@ -1,31 +0,0 @@
/*
Additional tools for Minizip
Code: Xavier Roche '2004
License: Same as ZLIB (www.gzip.org)
*/
#ifndef _zip_tools_H
#define _zip_tools_H
#ifdef __cplusplus
extern "C" {
#endif
#ifndef _ZLIB_H
#include "zlib.h"
#endif
#include "unzip.h"
/* Repair a ZIP file (missing central directory)
file: file to recover
fileOut: output file after recovery
fileOutTmp: temporary file name used for recovery
*/
extern int ZEXPORT unzRepair(const char* file,
const char* fileOut,
const char* fileOutTmp,
uLong* nRecovered,
uLong* bytesRecovered);
#endif

File diff suppressed because it is too large Load Diff

View File

@@ -1,356 +0,0 @@
/* unzip.h -- IO for uncompress .zip files using zlib
Version 1.01e, February 12th, 2005
Copyright (C) 1998-2005 Gilles Vollant
This unzip package allow extract file from .ZIP file, compatible with PKZip 2.04g
WinZip, InfoZip tools and compatible.
Multi volume ZipFile (span) are not supported.
Encryption compatible with pkzip 2.04g only supported
Old compressions used by old PKZip 1.x are not supported
I WAIT FEEDBACK at mail info@winimage.com
Visit also http://www.winimage.com/zLibDll/unzip.htm for evolution
Condition of use and distribution are the same than zlib :
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
/* for more info about .ZIP format, see
http://www.info-zip.org/pub/infozip/doc/appnote-981119-iz.zip
http://www.info-zip.org/pub/infozip/doc/
PkWare has also a specification at :
ftp://ftp.pkware.com/probdesc.zip
*/
#ifndef _unz_H
#define _unz_H
#ifdef __cplusplus
extern "C" {
#endif
#ifndef _ZLIB_H
#include "zlib.h"
#endif
#ifndef _ZLIBIOAPI_H
#include "ioapi.h"
#endif
#if defined(STRICTUNZIP) || defined(STRICTZIPUNZIP)
/* like the STRICT of WIN32, we define a pointer that cannot be converted
from (void*) without cast */
typedef struct TagunzFile__ { int unused; } unzFile__;
typedef unzFile__ *unzFile;
#else
typedef voidp unzFile;
#endif
#define UNZ_OK (0)
#define UNZ_END_OF_LIST_OF_FILE (-100)
#define UNZ_ERRNO (Z_ERRNO)
#define UNZ_EOF (0)
#define UNZ_PARAMERROR (-102)
#define UNZ_BADZIPFILE (-103)
#define UNZ_INTERNALERROR (-104)
#define UNZ_CRCERROR (-105)
/* tm_unz contain date/time info */
typedef struct tm_unz_s
{
uInt tm_sec; /* seconds after the minute - [0,59] */
uInt tm_min; /* minutes after the hour - [0,59] */
uInt tm_hour; /* hours since midnight - [0,23] */
uInt tm_mday; /* day of the month - [1,31] */
uInt tm_mon; /* months since January - [0,11] */
uInt tm_year; /* years - [1980..2044] */
} tm_unz;
/* unz_global_info structure contain global data about the ZIPfile
These data comes from the end of central dir */
typedef struct unz_global_info_s
{
uLong number_entry; /* total number of entries in
the central dir on this disk */
uLong size_comment; /* size of the global comment of the zipfile */
} unz_global_info;
/* unz_file_info contain information about a file in the zipfile */
typedef struct unz_file_info_s
{
uLong version; /* version made by 2 bytes */
uLong version_needed; /* version needed to extract 2 bytes */
uLong flag; /* general purpose bit flag 2 bytes */
uLong compression_method; /* compression method 2 bytes */
uLong dosDate; /* last mod file date in Dos fmt 4 bytes */
uLong crc; /* crc-32 4 bytes */
uLong compressed_size; /* compressed size 4 bytes */
uLong uncompressed_size; /* uncompressed size 4 bytes */
uLong size_filename; /* filename length 2 bytes */
uLong size_file_extra; /* extra field length 2 bytes */
uLong size_file_comment; /* file comment length 2 bytes */
uLong disk_num_start; /* disk number start 2 bytes */
uLong internal_fa; /* internal file attributes 2 bytes */
uLong external_fa; /* external file attributes 4 bytes */
tm_unz tmu_date;
} unz_file_info;
extern int ZEXPORT unzStringFileNameCompare OF ((const char* fileName1,
const char* fileName2,
int iCaseSensitivity));
/*
Compare two filename (fileName1,fileName2).
If iCaseSenisivity = 1, comparision is case sensitivity (like strcmp)
If iCaseSenisivity = 2, comparision is not case sensitivity (like strcmpi
or strcasecmp)
If iCaseSenisivity = 0, case sensitivity is defaut of your operating system
(like 1 on Unix, 2 on Windows)
*/
extern unzFile ZEXPORT unzOpen OF((const char *path));
/*
Open a Zip file. path contain the full pathname (by example,
on a Windows XP computer "c:\\zlib\\zlib113.zip" or on an Unix computer
"zlib/zlib113.zip".
If the zipfile cannot be opened (file don't exist or in not valid), the
return value is NULL.
Else, the return value is a unzFile Handle, usable with other function
of this unzip package.
*/
extern unzFile ZEXPORT unzOpen2 OF((const char *path,
zlib_filefunc_def* pzlib_filefunc_def));
/*
Open a Zip file, like unzOpen, but provide a set of file low level API
for read/write the zip file (see ioapi.h)
*/
extern int ZEXPORT unzClose OF((unzFile file));
/*
Close a ZipFile opened with unzipOpen.
If there is files inside the .Zip opened with unzOpenCurrentFile (see later),
these files MUST be closed with unzipCloseCurrentFile before call unzipClose.
return UNZ_OK if there is no problem. */
extern int ZEXPORT unzGetGlobalInfo OF((unzFile file,
unz_global_info *pglobal_info));
/*
Write info about the ZipFile in the *pglobal_info structure.
No preparation of the structure is needed
return UNZ_OK if there is no problem. */
extern int ZEXPORT unzGetGlobalComment OF((unzFile file,
char *szComment,
uLong uSizeBuf));
/*
Get the global comment string of the ZipFile, in the szComment buffer.
uSizeBuf is the size of the szComment buffer.
return the number of byte copied or an error code <0
*/
/***************************************************************************/
/* Unzip package allow you browse the directory of the zipfile */
extern int ZEXPORT unzGoToFirstFile OF((unzFile file));
/*
Set the current file of the zipfile to the first file.
return UNZ_OK if there is no problem
*/
extern int ZEXPORT unzGoToNextFile OF((unzFile file));
/*
Set the current file of the zipfile to the next file.
return UNZ_OK if there is no problem
return UNZ_END_OF_LIST_OF_FILE if the actual file was the latest.
*/
extern int ZEXPORT unzLocateFile OF((unzFile file,
const char *szFileName,
int iCaseSensitivity));
/*
Try locate the file szFileName in the zipfile.
For the iCaseSensitivity signification, see unzStringFileNameCompare
return value :
UNZ_OK if the file is found. It becomes the current file.
UNZ_END_OF_LIST_OF_FILE if the file is not found
*/
/* ****************************************** */
/* Ryan supplied functions */
/* unz_file_info contain information about a file in the zipfile */
typedef struct unz_file_pos_s
{
uLong pos_in_zip_directory; /* offset in zip file directory */
uLong num_of_file; /* # of file */
} unz_file_pos;
extern int ZEXPORT unzGetFilePos(
unzFile file,
unz_file_pos* file_pos);
extern int ZEXPORT unzGoToFilePos(
unzFile file,
unz_file_pos* file_pos);
/* ****************************************** */
extern int ZEXPORT unzGetCurrentFileInfo OF((unzFile file,
unz_file_info *pfile_info,
char *szFileName,
uLong fileNameBufferSize,
void *extraField,
uLong extraFieldBufferSize,
char *szComment,
uLong commentBufferSize));
/*
Get Info about the current file
if pfile_info!=NULL, the *pfile_info structure will contain somes info about
the current file
if szFileName!=NULL, the filemane string will be copied in szFileName
(fileNameBufferSize is the size of the buffer)
if extraField!=NULL, the extra field information will be copied in extraField
(extraFieldBufferSize is the size of the buffer).
This is the Central-header version of the extra field
if szComment!=NULL, the comment string of the file will be copied in szComment
(commentBufferSize is the size of the buffer)
*/
/***************************************************************************/
/* for reading the content of the current zipfile, you can open it, read data
from it, and close it (you can close it before reading all the file)
*/
extern int ZEXPORT unzOpenCurrentFile OF((unzFile file));
/*
Open for reading data the current file in the zipfile.
If there is no error, the return value is UNZ_OK.
*/
extern int ZEXPORT unzOpenCurrentFilePassword OF((unzFile file,
const char* password));
/*
Open for reading data the current file in the zipfile.
password is a crypting password
If there is no error, the return value is UNZ_OK.
*/
extern int ZEXPORT unzOpenCurrentFile2 OF((unzFile file,
int* method,
int* level,
int raw));
/*
Same than unzOpenCurrentFile, but open for read raw the file (not uncompress)
if raw==1
*method will receive method of compression, *level will receive level of
compression
note : you can set level parameter as NULL (if you did not want known level,
but you CANNOT set method parameter as NULL
*/
extern int ZEXPORT unzOpenCurrentFile3 OF((unzFile file,
int* method,
int* level,
int raw,
const char* password));
/*
Same than unzOpenCurrentFile, but open for read raw the file (not uncompress)
if raw==1
*method will receive method of compression, *level will receive level of
compression
note : you can set level parameter as NULL (if you did not want known level,
but you CANNOT set method parameter as NULL
*/
extern int ZEXPORT unzCloseCurrentFile OF((unzFile file));
/*
Close the file in zip opened with unzOpenCurrentFile
Return UNZ_CRCERROR if all the file was read but the CRC is not good
*/
extern int ZEXPORT unzReadCurrentFile OF((unzFile file,
voidp buf,
unsigned len));
/*
Read bytes from the current file (opened by unzOpenCurrentFile)
buf contain buffer where data must be copied
len the size of buf.
return the number of byte copied if somes bytes are copied
return 0 if the end of file was reached
return <0 with error code if there is an error
(UNZ_ERRNO for IO error, or zLib error for uncompress error)
*/
extern z_off_t ZEXPORT unztell OF((unzFile file));
/*
Give the current position in uncompressed data
*/
extern int ZEXPORT unzeof OF((unzFile file));
/*
return 1 if the end of file was reached, 0 elsewhere
*/
extern int ZEXPORT unzGetLocalExtrafield OF((unzFile file,
voidp buf,
unsigned len));
/*
Read extra field from the current file (opened by unzOpenCurrentFile)
This is the local-header version of the extra field (sometimes, there is
more info in the local-header version than in the central-header)
if buf==NULL, it return the size of the local extra field
if buf!=NULL, len is the size of the buffer, the extra header is copied in
buf.
the return value is the number of bytes copied in buf, or (if <0)
the error code
*/
/***************************************************************************/
/* Get the current file offset */
extern uLong ZEXPORT unzGetOffset (unzFile file);
/* Set the current file offset */
extern int ZEXPORT unzSetOffset (unzFile file, uLong pos);
#ifdef __cplusplus
}
#endif
#endif /* _unz_H */

File diff suppressed because it is too large Load Diff

View File

@@ -1,235 +0,0 @@
/* zip.h -- IO for compress .zip files using zlib
Version 1.01e, February 12th, 2005
Copyright (C) 1998-2005 Gilles Vollant
This unzip package allow creates .ZIP file, compatible with PKZip 2.04g
WinZip, InfoZip tools and compatible.
Multi volume ZipFile (span) are not supported.
Encryption compatible with pkzip 2.04g only supported
Old compressions used by old PKZip 1.x are not supported
For uncompress .zip file, look at unzip.h
I WAIT FEEDBACK at mail info@winimage.com
Visit also http://www.winimage.com/zLibDll/unzip.html for evolution
Condition of use and distribution are the same than zlib :
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
/* for more info about .ZIP format, see
http://www.info-zip.org/pub/infozip/doc/appnote-981119-iz.zip
http://www.info-zip.org/pub/infozip/doc/
PkWare has also a specification at :
ftp://ftp.pkware.com/probdesc.zip
*/
#ifndef _zip_H
#define _zip_H
#ifdef __cplusplus
extern "C" {
#endif
#ifndef _ZLIB_H
#include "zlib.h"
#endif
#ifndef _ZLIBIOAPI_H
#include "ioapi.h"
#endif
#if defined(STRICTZIP) || defined(STRICTZIPUNZIP)
/* like the STRICT of WIN32, we define a pointer that cannot be converted
from (void*) without cast */
typedef struct TagzipFile__ { int unused; } zipFile__;
typedef zipFile__ *zipFile;
#else
typedef voidp zipFile;
#endif
#define ZIP_OK (0)
#define ZIP_EOF (0)
#define ZIP_ERRNO (Z_ERRNO)
#define ZIP_PARAMERROR (-102)
#define ZIP_BADZIPFILE (-103)
#define ZIP_INTERNALERROR (-104)
#ifndef DEF_MEM_LEVEL
# if MAX_MEM_LEVEL >= 8
# define DEF_MEM_LEVEL 8
# else
# define DEF_MEM_LEVEL MAX_MEM_LEVEL
# endif
#endif
/* default memLevel */
/* tm_zip contain date/time info */
typedef struct tm_zip_s
{
uInt tm_sec; /* seconds after the minute - [0,59] */
uInt tm_min; /* minutes after the hour - [0,59] */
uInt tm_hour; /* hours since midnight - [0,23] */
uInt tm_mday; /* day of the month - [1,31] */
uInt tm_mon; /* months since January - [0,11] */
uInt tm_year; /* years - [1980..2044] */
} tm_zip;
typedef struct
{
tm_zip tmz_date; /* date in understandable format */
uLong dosDate; /* if dos_date == 0, tmu_date is used */
/* uLong flag; */ /* general purpose bit flag 2 bytes */
uLong internal_fa; /* internal file attributes 2 bytes */
uLong external_fa; /* external file attributes 4 bytes */
} zip_fileinfo;
typedef const char* zipcharpc;
#define APPEND_STATUS_CREATE (0)
#define APPEND_STATUS_CREATEAFTER (1)
#define APPEND_STATUS_ADDINZIP (2)
extern zipFile ZEXPORT zipOpen OF((const char *pathname, int append));
/*
Create a zipfile.
pathname contain on Windows XP a filename like "c:\\zlib\\zlib113.zip" or on
an Unix computer "zlib/zlib113.zip".
if the file pathname exist and append==APPEND_STATUS_CREATEAFTER, the zip
will be created at the end of the file.
(useful if the file contain a self extractor code)
if the file pathname exist and append==APPEND_STATUS_ADDINZIP, we will
add files in existing zip (be sure you don't add file that doesn't exist)
If the zipfile cannot be opened, the return value is NULL.
Else, the return value is a zipFile Handle, usable with other function
of this zip package.
*/
/* Note : there is no delete function into a zipfile.
If you want delete file into a zipfile, you must open a zipfile, and create another
Of couse, you can use RAW reading and writing to copy the file you did not want delte
*/
extern zipFile ZEXPORT zipOpen2 OF((const char *pathname,
int append,
zipcharpc* globalcomment,
zlib_filefunc_def* pzlib_filefunc_def));
extern int ZEXPORT zipOpenNewFileInZip OF((zipFile file,
const char* filename,
const zip_fileinfo* zipfi,
const void* extrafield_local,
uInt size_extrafield_local,
const void* extrafield_global,
uInt size_extrafield_global,
const char* comment,
int method,
int level));
/*
Open a file in the ZIP for writing.
filename : the filename in zip (if NULL, '-' without quote will be used
*zipfi contain supplemental information
if extrafield_local!=NULL and size_extrafield_local>0, extrafield_local
contains the extrafield data the the local header
if extrafield_global!=NULL and size_extrafield_global>0, extrafield_global
contains the extrafield data the the local header
if comment != NULL, comment contain the comment string
method contain the compression method (0 for store, Z_DEFLATED for deflate)
level contain the level of compression (can be Z_DEFAULT_COMPRESSION)
*/
extern int ZEXPORT zipOpenNewFileInZip2 OF((zipFile file,
const char* filename,
const zip_fileinfo* zipfi,
const void* extrafield_local,
uInt size_extrafield_local,
const void* extrafield_global,
uInt size_extrafield_global,
const char* comment,
int method,
int level,
int raw));
/*
Same than zipOpenNewFileInZip, except if raw=1, we write raw file
*/
extern int ZEXPORT zipOpenNewFileInZip3 OF((zipFile file,
const char* filename,
const zip_fileinfo* zipfi,
const void* extrafield_local,
uInt size_extrafield_local,
const void* extrafield_global,
uInt size_extrafield_global,
const char* comment,
int method,
int level,
int raw,
int windowBits,
int memLevel,
int strategy,
const char* password,
uLong crcForCtypting));
/*
Same than zipOpenNewFileInZip2, except
windowBits,memLevel,,strategy : see parameter strategy in deflateInit2
password : crypting password (NULL for no crypting)
crcForCtypting : crc of file to compress (needed for crypting)
*/
extern int ZEXPORT zipWriteInFileInZip OF((zipFile file,
const void* buf,
unsigned len));
/*
Write data in the zipfile
*/
extern int ZEXPORT zipCloseFileInZip OF((zipFile file));
/*
Close the current file in the zipfile
*/
extern int ZEXPORT zipCloseFileInZipRaw OF((zipFile file,
uLong uncompressed_size,
uLong crc32));
/*
Close the current file in the zipfile, for fiel opened with
parameter raw=1 in zipOpenNewFileInZip2
uncompressed_size and crc32 are value for the uncompressed size
*/
extern int ZEXPORT zipClose OF((zipFile file,
const char* global_comment));
/*
Close the zipfile
*/
#ifdef __cplusplus
}
#endif
#endif /* _zip_H */

View File

@@ -1,821 +0,0 @@
//========================================================================
// NeHe OpenGL Wizard : NeHeSimple.cpp
// Wizard Created by: Vic Hollis
//========================================================================
/*
* This Code Was Created By Jeff Molofee 2000
* A HUGE Thanks To Fredric Echols For Cleaning Up
* And Optimizing This Code, Making It More Flexible!
* If You've Found This Code Useful, Please Let Me Know.
* Visit My Site At nehe.gamedev.net
*/
#ifdef WIN32
#include <windows.h> // Header File For Windows
#else
typedef struct _HDC {} *HDC;
typedef struct _HGLRC {} *HGLRC;
typedef struct _HWND {} *HWND;
typedef struct _HINSTANCE {} *HINSTANCE;
typedef struct _WNDCLASS
{
int wc;
int style;
int* lpfnWndProc;
int cbClsExtra;
int cbWndExtra;
HINSTANCE hInstance;
int* hIcon;
int* hCursor;
int hbrBackground;
char* lpszMenuName;
const char* lpszClassName;
} WNDCLASS;
typedef struct
{
unsigned short dmSize;
unsigned int dmFields;
unsigned int dmBitsPerPel;
unsigned int dmPelsWidth;
unsigned int dmPelsHeight;
} DEVMODE;
typedef HINSTANCE HMODULE;
typedef struct _RECT { int left; int right; int top; int bottom; } RECT;
typedef struct _MSG { int wParam; int message; } MSG;
typedef unsigned int LRESULT;
typedef unsigned int UINT;
typedef signed int WPARAM;
typedef unsigned int LPARAM;
typedef int* WNDPROC;
typedef int* HCURSOR;
typedef HCURSOR HICON;
typedef HCURSOR HMENU;
typedef struct _PIXELFORMATDESCRIPTOR {
int a;int b;int c;int d;int e;int f;int g;int h;int i;int j;int k;int l;int m;int n;int o;int p;int q;int r;int s;int t;int u;int v;int w;int x;int y;int z; } PIXELFORMATDESCRIPTOR;
typedef char* LPSTR;
enum { VK_CONTROL, VK_RETURN, VK_ESCAPE, VK_SPACE, VK_F1, VK_F2, VK_F3 };
enum { MB_OK, MB_ICONINFORMATION, MB_ICONSTOP, MB_YESNO, MB_ICONEXCLAMATION, IDYES };
enum { CS_HREDRAW, CS_VREDRAW, CS_OWNDC };
enum { WS_EX_APPWINDOW, WS_POPUP, WS_EX_WINDOWEDGE, WS_OVERLAPPED, WS_CAPTION, WS_MINIMIZEBOX, WS_MAXIMIZEBOX, WS_SIZEBOX, WS_SYSMENU, WS_CLIPSIBLINGS, WS_CLIPCHILDREN };
enum { WM_ACTIVATE, WM_SYSCOMMAND, WM_CLOSE, WM_KEYDOWN, WM_KEYUP, WM_LBUTTONDOWN, WM_LBUTTONUP, WM_RBUTTONDOWN, WM_RBUTTONUP, WM_MOUSEMOVE, WM_SIZE, WM_QUIT };
enum { DM_BITSPERPEL, DM_PELSWIDTH, DM_PELSHEIGHT };
enum { CDS_FULLSCREEN };
enum { DISP_CHANGE_SUCCESSFUL };
enum { SC_SCREENSAVE, SC_MONITORPOWER };
enum { PFD_DRAW_TO_WINDOW, PFD_SUPPORT_OPENGL, PFD_DOUBLEBUFFER, PFD_TYPE_RGBA, PFD_MAIN_PLANE };
enum { SW_SHOW };
enum { IDC_ARROW };
enum { PM_REMOVE };
static const char* IDI_WINLOGO = "";
#define CALLBACK
#define WINAPI
#define ZeroMemory bzero
int GetTickCount() { return 0; }
long ChangeDisplaySettings(DEVMODE*, unsigned int);
int ShowCursor(bool);
HGLRC wglCreateContext(HDC);
bool wglMakeCurrent(HDC, HGLRC);
bool wglDeleteContext(HGLRC);
int ReleaseDC(HWND, HDC);
int MessageBox(HWND, const char*, const char*, unsigned int);
bool DestroyWindow(HWND);
bool UnregisterClass(const char*, HINSTANCE);
HMODULE GetModuleHandle(char*);
HCURSOR LoadCursor(HINSTANCE, int);
HICON LoadIcon(HINSTANCE, const char*);
int* RegisterClass(const WNDCLASS*);
bool AdjustWindowRectEx(RECT*, unsigned int, bool, unsigned int);
HWND CreateWindowEx(unsigned int, const char*, const char*, unsigned int, int, int, int, int, HWND, HMENU, HINSTANCE, void*);
HDC GetDC(HWND);
int ChoosePixelFormat(HDC, const PIXELFORMATDESCRIPTOR*);
bool SetPixelFormat(HDC, int, PIXELFORMATDESCRIPTOR*);
bool ShowWindow(HWND, int);
bool SetForegroundWindow(HWND);
HWND SetFocus(HWND);
unsigned short HIWORD(unsigned int);
unsigned short LOWORD(unsigned int);
LRESULT DefWindowProc(HWND, unsigned int, WPARAM, LPARAM);
void PostQuitMessage(int);
bool PeekMessage(MSG*, HWND, unsigned int, unsigned int, unsigned int);
bool TranslateMessage(const MSG*);
LRESULT DispatchMessage(const MSG*);
bool SwapBuffers(HDC);
#endif
#include <GL/gl.h> // Header File For The OpenGL32 Library
#include <GL/glu.h> // Header File For The GLu32 Library
#include <queue>
#include "../../JGE/include/JGE.h"
#include "../../JGE/include/JTypes.h"
#include "../../JGE/include/JApp.h"
#include "../../JGE/include/JFileSystem.h"
#include "../../JGE/include/JRenderer.h"
#include "../../JGE/include/JGameLauncher.h"
//#include "..\src\GameApp.h"
#ifdef WIN32
#pragma comment( lib, "opengl32.lib" ) // Search For OpenGL32.lib While Linking
#pragma comment( lib, "glu32.lib" ) // Search For GLu32.lib While Linking
#pragma comment( lib, "User32.lib" )
#pragma comment( lib, "Gdi32.lib" )
#pragma comment( lib, "Comdlg32.lib" )
#endif
HDC hDC=NULL; // Private GDI Device Context
HGLRC hRC=NULL; // Permanent Rendering Context
HWND hWnd=NULL; // Holds Our Window Handle
HINSTANCE hInstance; // Holds The Instance Of The Application
bool active=TRUE; // Window Active Flag Set To TRUE By Default
enum eDisplayMode
{
DisplayMode_lowRes = 0,
DisplayMode_hiRes,
DisplayMode_fullscreen
};
unsigned int gDisplayMode = DisplayMode_lowRes;
const float kActualRatio((GLfloat)SCREEN_WIDTH / (GLfloat)SCREEN_HEIGHT);
DWORD lastTickCount;
BOOL g_keys[256];
BOOL g_holds[256];
//------------------------------------------------------------------------
JGE* g_engine = NULL;
JApp* g_app = NULL;
JGameLauncher* g_launcher = NULL;
//------------------------------------------------------------------------
static u32 gButtons = 0;
static u32 gOldButtons = 0;
static const struct { LocalKeySym keysym; JButton keycode; }
gDefaultBindings[] =
{
{ VK_CONTROL, JGE_BTN_CTRL },
{ VK_RETURN, JGE_BTN_MENU },
{ VK_ESCAPE, JGE_BTN_MENU },
{ VK_UP, JGE_BTN_UP },
{ VK_RIGHT, JGE_BTN_RIGHT },
{ VK_DOWN, JGE_BTN_DOWN },
{ VK_LEFT, JGE_BTN_LEFT },
{ 'Z', JGE_BTN_UP },
{ 'D', JGE_BTN_RIGHT },
{ 'S', JGE_BTN_DOWN },
{ 'Q', JGE_BTN_LEFT },
{ 'A', JGE_BTN_PREV },
{ 'E', JGE_BTN_NEXT },
{ 'I', JGE_BTN_CANCEL },
{ 'L', JGE_BTN_OK },
{ VK_SPACE, JGE_BTN_OK },
{ 'K', JGE_BTN_SEC },
{ 'J', JGE_BTN_PRI },
{ 'F', JGE_BTN_FULLSCREEN },
};
void JGECreateDefaultBindings()
{
for (signed int i = sizeof(gDefaultBindings)/sizeof(gDefaultBindings[0]) - 1; i >= 0; --i)
g_engine->BindKey(gDefaultBindings[i].keysym, gDefaultBindings[i].keycode);
}
int JGEGetTime()
{
return (int)GetTickCount();
}
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); // Declaration For WndProc
GLvoid ReSizeGLScene(GLsizei width, GLsizei height) // Resize And Initialize The GL Window
{
if (height==0) // Prevent A Divide By Zero By
height=1; // Making Height Equal One
JRenderer::GetInstance()->SetActualWidth(static_cast<float>(width));
JRenderer::GetInstance()->SetActualHeight(static_cast<float>(height));
GLsizei adjustedWidth(width);
GLsizei adjustedHeight(height);
GLint x(0);
GLint y(0);
if ((GLfloat)width / (GLfloat)height < kActualRatio)
{
adjustedHeight = (GLsizei)(width / kActualRatio);
y = -(adjustedHeight - height) / 2;
}
else
{
adjustedWidth = (GLsizei)(height * kActualRatio);
x = -(adjustedWidth - width) / 2;
}
glViewport(x, y, adjustedWidth, adjustedHeight);
glScissor(0, 0, width, height);
glMatrixMode (GL_PROJECTION); // Select The Projection Matrix
glLoadIdentity (); // Reset The Projection Matrix
gluOrtho2D(0.0f, (float) width - 1.0f, 0.0f, (float) height - 1.0f);
glMatrixMode (GL_MODELVIEW); // Select The Modelview Matrix
glLoadIdentity(); // Reset The Modelview Matrix
glDisable (GL_DEPTH_TEST);
}
int InitGL(void) // All Setup For OpenGL Goes Here
{
glClearColor (0.0f, 0.0f, 0.0f, 0.0f); // Black Background
glClearDepth (1.0f); // Depth Buffer Setup
glDepthFunc (GL_LEQUAL); // The Type Of Depth Testing (Less Or Equal)
glEnable (GL_DEPTH_TEST); // Enable Depth Testing
glShadeModel (GL_SMOOTH); // Select Smooth Shading
glHint (GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); // Set Perspective Calculations To Most Accurate
glHint(GL_LINE_SMOOTH_HINT, GL_NICEST); // Set Line Antialiasing
//glEnable(GL_LINE_SMOOTH); // Enable it!
glEnable(GL_CULL_FACE); // do not calculate inside of poly's
glFrontFace(GL_CCW); // counter clock-wise polygons are out
glEnable(GL_TEXTURE_2D);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_SCISSOR_TEST); // Enable Clipping
//glScissor(20, 20, 320, 240);
return TRUE; // Initialization Went OK
}
int InitGame(void)
{
g_engine = JGE::GetInstance();
//JGameLauncher *launcher = new JGameLauncher();
g_app = g_launcher->GetGameApp();
g_app->Create();
g_engine->SetApp(g_app);
JRenderer::GetInstance()->Enable2D();
lastTickCount = GetTickCount();
ZeroMemory(g_keys, 256);
ZeroMemory(g_holds, 256);
//delete launcher;
return TRUE;
}
void DestroyGame(void)
{
// JParticleSystem::Destroy();
// JMotionSystem::Destroy();
g_engine->SetApp(NULL);
if (g_app)
{
g_app->Destroy();
delete g_app;
g_app = NULL;
}
JGE::Destroy();
g_engine = NULL;
}
int DrawGLScene(void) // Here's Where We Do All The Drawing
{
// glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear Screen And Depth Buffer
// glLoadIdentity (); // Reset The Modelview Matrix
//if (g_app)
// g_app->Render();
g_engine->Render();
// glFlush ();
return TRUE; // Everything Went OK
}
void Update(float dt)
{
g_engine->SetDelta(dt);
g_engine->Update(dt);
}
void KillGLWindow(void) // Properly Kill The Window
{
if (gDisplayMode == DisplayMode_fullscreen)
{
ChangeDisplaySettings(NULL,0); // If So Switch Back To The Desktop
ShowCursor(TRUE); // Show Mouse Pointer
}
if (hRC) // Do We Have A Rendering Context?
{
if (!wglMakeCurrent(NULL,NULL)) // Are We Able To Release The DC And RC Contexts?
MessageBox(NULL,"Release Of DC And RC Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
if (!wglDeleteContext(hRC)) // Are We Able To Delete The RC?
MessageBox(NULL,"Release Rendering Context Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
hRC=NULL; // Set RC To NULL
}
if (hDC && !ReleaseDC(hWnd,hDC)) // Are We Able To Release The DC
{
MessageBox(NULL,"Release Device Context Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
hDC=NULL; // Set DC To NULL
}
if (hWnd && !DestroyWindow(hWnd)) // Are We Able To Destroy The Window?
{
MessageBox(NULL,"Could Not Release hWnd.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
hWnd=NULL; // Set hWnd To NULL
}
if (!UnregisterClass("OpenGL",hInstance)) // Are We Able To Unregister Class
{
MessageBox(NULL,"Could Not Unregister Class.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
hInstance=NULL; // Set hInstance To NULL
}
}
/* This Code Creates Our OpenGL Window. Parameters Are: *
* title - Title To Appear At The Top Of The Window *
* bits - Number Of Bits To Use For Color (8/16/24/32) */
BOOL CreateGLWindow(char* title, int width, int height, int bits)
{
int actualScreenWidth = ::GetSystemMetrics(SM_CXSCREEN);
int actualScreenHeight = ::GetSystemMetrics(SM_CYSCREEN);
JRenderer::GetInstance()->SetActualWidth(static_cast<float>(width));
JRenderer::GetInstance()->SetActualHeight(static_cast<float>(height));
GLuint pixelFormat; // Holds The Results After Searching For A Match
WNDCLASS wc; // Windows Class Structure
DWORD dwExStyle; // Window Extended Style
DWORD dwStyle; // Window Style
RECT windowRect; // Grabs Rectangle Upper Left / Lower Right Values
windowRect.left = (long) 0;
windowRect.top = (long) 0;
if (gDisplayMode != DisplayMode_fullscreen)
{
windowRect.left = (actualScreenWidth - width) / 2;
windowRect.top = (actualScreenHeight - height) / 2;
}
windowRect.right = windowRect.left + (long)width; // Set Right Value To Requested Width
windowRect.bottom = windowRect.top + (long)height; // Set Bottom Value To Requested Height
hInstance = GetModuleHandle(NULL); // Grab An Instance For Our Window
wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; // Redraw On Size, And Own DC For Window.
wc.lpfnWndProc = (WNDPROC) WndProc; // WndProc Handles Messages
wc.cbClsExtra = 0; // No Extra Window Data
wc.cbWndExtra = 0; // No Extra Window Data
wc.hInstance = hInstance; // Set The Instance
wc.hIcon = LoadIcon(NULL, IDI_WINLOGO); // Load The Default Icon
wc.hCursor = LoadCursor(NULL, IDC_ARROW); // Load The Arrow Pointer
wc.hbrBackground = NULL; // No Background Required For GL
wc.lpszMenuName = NULL; // We Don't Want A Menu
wc.lpszClassName = "OpenGL"; // Set The Class Name
if (!RegisterClass(&wc)) // Attempt To Register The Window Class
{
MessageBox(NULL,"Failed To Register The Window Class.","ERROR",MB_OK|MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}
if (gDisplayMode == DisplayMode_fullscreen) // Attempt Fullscreen Mode?
{
DEVMODE dmScreenSettings; // Device Mode
memset(&dmScreenSettings,0,sizeof(dmScreenSettings)); // Makes Sure Memory's Cleared
dmScreenSettings.dmSize=sizeof(dmScreenSettings); // Size Of The Devmode Structure
dmScreenSettings.dmPelsWidth = actualScreenWidth; // Selected Screen Width
dmScreenSettings.dmPelsHeight = actualScreenHeight; // Selected Screen Height
dmScreenSettings.dmBitsPerPel = bits; // Selected Bits Per Pixel
dmScreenSettings.dmFields=DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT;
// Try To Set Selected Mode And Get Results. NOTE: CDS_FULLSCREEN Gets Rid Of Start Bar.
LONG result = ChangeDisplaySettings(&dmScreenSettings,CDS_FULLSCREEN);
if (result != DISP_CHANGE_SUCCESSFUL)
{
// If The Mode Fails, Offer Two Options. Quit Or Use Windowed Mode.
if (MessageBox(NULL,"The Requested Fullscreen Mode Is Not Supported By\nYour Video Card. Use Windowed Mode Instead?","NeHe GL",MB_YESNO|MB_ICONEXCLAMATION)==IDYES)
{
gDisplayMode = DisplayMode_lowRes; // Windowed Mode Selected.
}
else
{
// Pop Up A Message Box Letting User Know The Program Is Closing.
MessageBox(NULL,"Program Will Now Close.","ERROR",MB_OK|MB_ICONSTOP);
return FALSE; // Return FALSE
}
}
}
if (gDisplayMode == DisplayMode_fullscreen) // Are We Still In Fullscreen Mode?
{
dwExStyle=WS_EX_APPWINDOW; // Window Extended Style
dwStyle=WS_POPUP; // Windows Style
ShowCursor(FALSE); // Hide Mouse Pointer
}
else
{
dwExStyle=WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; // Window Extended Style
//dwStyle=WS_OVERLAPPEDWINDOW; // Windows Style
dwStyle= WS_OVERLAPPED | \
WS_CAPTION | \
WS_MINIMIZEBOX |
WS_SIZEBOX |
WS_MAXIMIZEBOX |
//WS_MINIMIZE |
WS_SYSMENU;// |
//WS_THICKFRAME ;
}
AdjustWindowRectEx(&windowRect, dwStyle, FALSE, dwExStyle); // Adjust Window To True Requested Size
// Create The Window
if (hWnd == NULL)
{
if (!(hWnd=CreateWindowEx( dwExStyle, // Extended Style For The Window
"OpenGL", // Class Name
title, // Window Title
dwStyle | // Defined Window Style
WS_CLIPSIBLINGS | // Required Window Style
WS_CLIPCHILDREN, // Required Window Style
windowRect.left, windowRect.top, // Window Position
windowRect.right-windowRect.left, // Calculate Window Width
windowRect.bottom-windowRect.top, // Calculate Window Height
NULL, // No Parent Window
NULL, // No Menu
hInstance, // Instance
NULL))) // Dont Pass Anything To WM_CREATE
{
KillGLWindow(); // Reset The Display
MessageBox(NULL,"Window Creation Error.","ERROR",MB_OK|MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}
}
static PIXELFORMATDESCRIPTOR pfd= // pfd Tells Windows How We Want Things To Be
{
sizeof(PIXELFORMATDESCRIPTOR), // Size Of This Pixel Format Descriptor
1, // Version Number
PFD_DRAW_TO_WINDOW | // Format Must Support Window
PFD_SUPPORT_OPENGL | // Format Must Support OpenGL
PFD_DOUBLEBUFFER, // Must Support Double Buffering
PFD_TYPE_RGBA, // Request An RGBA Format
bits, // Select Our Color Depth
0, 0, 0, 0, 0, 0, // Color Bits Ignored
0, // No Alpha Buffer
0, // Shift Bit Ignored
0, // No Accumulation Buffer
0, 0, 0, 0, // Accumulation Bits Ignored
16, // 16Bit Z-Buffer (Depth Buffer)
0, // No Stencil Buffer
0, // No Auxiliary Buffer
PFD_MAIN_PLANE, // Main Drawing Layer
0, // Reserved
0, 0, 0 // Layer Masks Ignored
};
if (!(hDC=GetDC(hWnd))) // Did We Get A Device Context?
{
KillGLWindow(); // Reset The Display
MessageBox(NULL,"Can't Create A GL Device Context.","ERROR",MB_OK|MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}
if (!(pixelFormat=ChoosePixelFormat(hDC,&pfd))) // Did Windows Find A Matching Pixel Format?
{
KillGLWindow(); // Reset The Display
MessageBox(NULL,"Can't Find A Suitable PixelFormat.","ERROR",MB_OK|MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}
if(!SetPixelFormat(hDC,pixelFormat,&pfd)) // Are We Able To Set The Pixel Format?
{
KillGLWindow(); // Reset The Display
MessageBox(NULL,"Can't Set The PixelFormat.","ERROR",MB_OK|MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}
if (!(hRC=wglCreateContext(hDC))) // Are We Able To Get A Rendering Context?
{
KillGLWindow(); // Reset The Display
MessageBox(NULL,"Can't Create A GL Rendering Context.","ERROR",MB_OK|MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}
if(!wglMakeCurrent(hDC,hRC)) // Try To Activate The Rendering Context
{
KillGLWindow(); // Reset The Display
MessageBox(NULL,"Can't Activate The GL Rendering Context.","ERROR",MB_OK|MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}
ShowWindow(hWnd,SW_SHOW); // Show The Window
SetForegroundWindow(hWnd); // Slightly Higher Priority
SetFocus(hWnd); // Sets Keyboard Focus To The Window
ReSizeGLScene(width, height); // Set Up Our Perspective GL Screen
if (!InitGL()) // Initialize Our Newly Created GL Window
{
KillGLWindow(); // Reset The Display
MessageBox(NULL,"Initialization Failed.","ERROR",MB_OK|MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}
return TRUE; // Success
}
LRESULT CALLBACK WndProc(
HWND hWnd, // Handle For This Window
UINT uMsg, // Message For This Window
WPARAM wParam, // Additional Message Information
LPARAM lParam) // Additional Message Information
{
switch (uMsg) // Check For Windows Messages
{
case WM_ACTIVATE: // Watch For Window Activate Message
{
if (!HIWORD(wParam)) // Check Minimization State
{
active=TRUE; // Program Is Active
if (g_engine != NULL)
g_engine->Resume();
}
else
{
active=FALSE; // Program Is No Longer Active
if (g_engine != NULL)
g_engine->Pause();
}
return 0; // Return To The Message Loop
}
case WM_SYSCOMMAND: // Intercept System Commands
{
switch (wParam) // Check System Calls
{
case SC_SCREENSAVE: // Screensaver Trying To Start?
case SC_MONITORPOWER: // Monitor Trying To Enter Powersave?
return 0; // Prevent From Happening
}
break; // Exit
}
case WM_CLOSE: // Did We Receive A Close Message?
{
PostQuitMessage(0); // Send A Quit Message
return 0; // Jump Back
}
case WM_KEYDOWN: // Update Keyboard Buffers For Keys Pressed
if ((wParam >= 0) && (wParam <= 255)) // Is Key (wParam) In A Valid Range?
{
g_engine->HoldKey_NoRepeat(wParam);
return 0;
}
break; // Break
case WM_KEYUP: // Update Keyboard Buffers For Keys Released
if ((wParam >= 0) && (wParam <= 255)) // Is Key (wParam) In A Valid Range?
{
g_engine->ReleaseKey(wParam);
return 0; // Return
}
break;
case WM_LBUTTONDOWN:
{
return 0;
}
case WM_LBUTTONUP:
{
return 0;
}
case WM_RBUTTONDOWN:
{
return 0;
}
case WM_RBUTTONUP:
{
return 0;
}
case WM_MOUSEMOVE:
{
// Mint2D::SetMousePosition(LOWORD(lParam), HIWORD(lParam));
return 0;
}
case WM_SIZE: // Resize The OpenGL Window
{
ReSizeGLScene(LOWORD(lParam),HIWORD(lParam)); // LoWord=Width, HiWord=Height
return 0; // Jump Back
}
}
// Pass All Unhandled Messages To DefWindowProc
return DefWindowProc(hWnd,uMsg,wParam,lParam);
}
bool JGEToggleFullscreen()
{
//cycle between the display modes
++gDisplayMode;
if (gDisplayMode > DisplayMode_fullscreen)
gDisplayMode = DisplayMode_lowRes;
int width = 0, height = 0;
int actualScreenWidth = ::GetSystemMetrics(SM_CXSCREEN);
int actualScreenHeight = ::GetSystemMetrics(SM_CYSCREEN);
switch (gDisplayMode)
{
case DisplayMode_fullscreen:
width = actualScreenWidth;
height = actualScreenHeight;
break;
case DisplayMode_hiRes:
width = SCREEN_WIDTH * 2;
height = SCREEN_HEIGHT * 2;
break;
case DisplayMode_lowRes:
default:
width = SCREEN_WIDTH;
height = SCREEN_HEIGHT;
break;
}
DWORD dwExStyle = GetWindowLong(hWnd, GWL_EXSTYLE);
DWORD dwStyle = GetWindowLong(hWnd, GWL_STYLE);
if (gDisplayMode == DisplayMode_fullscreen)
{
dwExStyle &= ~(WS_EX_DLGMODALFRAME | WS_EX_CLIENTEDGE | WS_EX_STATICEDGE);
dwStyle &= ~(WS_CAPTION | WS_THICKFRAME | WS_MINIMIZE | WS_MAXIMIZE | WS_SYSMENU);
}
else
{
dwExStyle |= WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;
dwStyle |= WS_OVERLAPPEDWINDOW;
}
int x = (actualScreenWidth - width) / 2;
int y = (actualScreenHeight - height) / 2;
RECT windowRect;
windowRect.left = x;
windowRect.top = y;
windowRect.right = windowRect.left + width;
windowRect.bottom = windowRect.top + height;
AdjustWindowRectEx(&windowRect, dwStyle, FALSE, dwExStyle);
DEVMODE dmScreenSettings; // Device Mode
memset(&dmScreenSettings,0,sizeof(dmScreenSettings)); // Makes Sure Memory's Cleared
dmScreenSettings.dmSize=sizeof(dmScreenSettings); // Size Of The Devmode Structure
dmScreenSettings.dmPelsWidth = width; // Selected Screen Width
dmScreenSettings.dmPelsHeight = height; // Selected Screen Height
dmScreenSettings.dmBitsPerPel = 32; // Selected Bits Per Pixel
dmScreenSettings.dmFields=DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT;
// Try To Set Selected Mode And Get Results. NOTE: CDS_FULLSCREEN Gets Rid Of Start Bar.
LONG result = ChangeDisplaySettings(&dmScreenSettings, gDisplayMode == DisplayMode_fullscreen ? CDS_FULLSCREEN : 0);
SetWindowLong(hWnd,
GWL_EXSTYLE,
dwExStyle);
SetWindowLong(hWnd,
GWL_STYLE,
dwStyle);
SetWindowPos(hWnd, NULL, windowRect.left, windowRect.top, windowRect.right - windowRect.left, windowRect.bottom - windowRect.top, SWP_NOZORDER | SWP_FRAMECHANGED);
ReSizeGLScene(width, height);
return true;
}
int WINAPI WinMain(
HINSTANCE hInstance, // Instance
HINSTANCE hPrevInstance, // Previous Instance
LPSTR lpCmdLine, // Command Line Parameters
int nCmdShow) // Window Show State
{
MSG msg; // Windows Message Structure
BOOL done=FALSE; // Bool Variable To Exit Loop
DWORD tickCount;
int dt;
g_launcher = new JGameLauncher();
u32 flags = g_launcher->GetInitFlags();
JGECreateDefaultBindings();
if ((flags&JINIT_FLAG_ENABLE3D)!=0)
JRenderer::Set3DFlag(true);
// Create Our OpenGL Window
if (!CreateGLWindow(g_launcher->GetName(),SCREEN_WIDTH,SCREEN_HEIGHT,32))
{
return 0; // Quit If Window Was Not Created
}
if (!InitGame()) // Initialize Our Game
{
KillGLWindow(); // Reset The Display
MessageBox(NULL,"Game Initialization Failed.","ERROR",MB_OK|MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}
while(!done) // Loop That Runs While done=FALSE
{
if (PeekMessage(&msg,NULL,0,0,PM_REMOVE)) // Is There A Message Waiting?
{
if (msg.message==WM_QUIT) // Have We Received A Quit Message?
{
done=TRUE; // If So done=TRUE
}
else // If Not, Deal With Window Messages
{
TranslateMessage(&msg); // Translate The Message
DispatchMessage(&msg); // Dispatch The Message
}
}
else // If There Are No Messages
{
// Draw The Scene. Watch For ESC Key And Quit Messages From DrawGLScene()
if (active) // Program Active?
{
if (g_engine->IsDone())
done=TRUE; // ESC Signalled A Quit
else // Not Time To Quit, Update Screen
{
tickCount = GetTickCount(); // Get The Tick Count
dt = (tickCount - lastTickCount);
lastTickCount = tickCount;
Update((float)dt/1000.0f); // Update frame
//Mint2D::BackupKeys();
DrawGLScene(); // Draw The Scene
SwapBuffers(hDC); // Swap Buffers (Double Buffering)
}
}
}
}
if (g_launcher)
delete g_launcher;
// Shutdown
DestroyGame();
KillGLWindow(); // Kill The Window
return (msg.wParam); // Exit The Program
}

View File

@@ -1,25 +0,0 @@
MAIN=zfs
CC=g++
CFLAGS= -O2 -Wall -DNDEBUG -DUNIX
INCLUDES=
LFLAGS= -lz
SRCS = \
zfs.cpp \
zfsystem.cpp \
ziphdr.cpp \
zstream.cpp \
OBJS = $(SRCS:.cpp=.o)
$(MAIN): $(OBJS)
$(CC) -o $(MAIN) $(LFLAGS) $(OBJS)
.cpp.o:
$(CC) $(CFLAGS) $(INCLUDES) -c $<
clean:
rm -f *.o $(MAIN)

Binary file not shown.

Binary file not shown.

View File

@@ -1,256 +0,0 @@
// bfileio.h: interface for the binary file i/o.
//
//////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2004 Tanguy Fautre
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//
// Tanguy Fautr<74>E
// softdev@telenet.be
//
//////////////////////////////////////////////////////////////////////
//
// File I/O Facilities.
// ********************
//
// Current version: 1.00 BETA 4 (16/07/2004)
//
// Comment: readvar() and writevar() read a little endian ordered
// value on a file and put it in a variable.
// search_iterator only accepts "<directory>/*.<ext>".
// Uses ANSI C "assert()". Define NDEBUG to turn it off.
// (note: Visual C++ define NDEBUG in Release mode)
//
// History: - 1.00 BETA 4 (16/07/2004) - Fixed small bug in UNIX search_iterator
// - 1.00 BETA 3 (27/06/2004) - Added UNIX compatibility
// - 1.00 BETA 2 (21/02/2003) - Now endianess independent
// - 1.00 BETA 1 (06/09/2002) - First public release
//
//////////////////////////////////////////////////////////////////////
#pragma once
#if defined WIN32
#include <io.h> // Windows I/O facilities (Directories)
#else
#include <dirent.h>
#include <string.h>
#endif
#include <limits.h>
namespace io_facilities {
// Global function for reading binary variables
template <class T> std::istream & readvar(std::istream & File, T & Var, const std::streamsize NbBytes);
template <class T> std::ostream & writevar(std::ostream & File, const T & Var, const std::streamsize NbBytes);
// Class for searching files and directories
// (!!! not compliant with C++ std::iterator and is thus meant for specific use !!!)
class search_iterator
{
public:
search_iterator();
search_iterator(const char * FileSpec);
~search_iterator();
operator bool () const;
search_iterator & operator ++ ();
search_iterator & begin(const char * FileSpec);
search_iterator & next();
bool end() const;
std::string Name() const;
protected:
bool m_Valid;
#if defined WIN32
intptr_t m_hFiles;
_finddata_t m_FindData;
#else
DIR * m_Directory;
std::string m_Extension;
struct dirent * m_DirectoryEntry;
#endif
};
//////////////////////////////////////////////////////////////////////
// io_facilities:: Inline Functions
//////////////////////////////////////////////////////////////////////
template <class T>
inline std::istream & readvar(std::istream & File, T & Var, const std::streamsize NbBytes)
{
// Debug test to ensure type size is big enough
assert(sizeof(T) >= size_t(NbBytes));
// Var = 0 ensure type size won't matter
T TmpVar = Var = 0;
for (std::streamsize i = 0; i < NbBytes; ++i) {
File.read(reinterpret_cast<char *>(&TmpVar), 1);
Var |= TmpVar << (i * CHAR_BIT);
}
return File;
}
template <class T>
inline std::ostream & writevar(std::ostream & File, const T & Var, const std::streamsize NbBytes)
{
// Debug test to ensure type size is big enough
assert(sizeof(T) >= size_t(NbBytes));
T TmpVar = Var;
for (std::streamsize i = 0; i < NbBytes; ++i)
File.write(reinterpret_cast<const char *>(&(TmpVar >>= (CHAR_BIT * i))), 1);
return File;
}
//////////////////////////////////////////////////////////////////////
// io_facilities::search_iterator Inline Member Functions
//////////////////////////////////////////////////////////////////////
inline search_iterator::search_iterator()
: m_Valid(false),
#if defined WIN32
m_hFiles(-1)
#else
m_Directory(NULL)
#endif
{ }
inline search_iterator::search_iterator(const char * FileSpec)
: m_Valid(false),
#if defined WIN32
m_hFiles(-1)
#else
m_Directory(NULL)
#endif
{
begin(FileSpec);
}
inline search_iterator::~search_iterator() {
#if defined WIN32
if (m_hFiles != -1) _findclose(m_hFiles);
#else
if (m_Directory != NULL) closedir(m_Directory);
#endif
}
inline search_iterator::operator bool () const {
return m_Valid;
}
inline search_iterator & search_iterator::operator ++ () {
return next();
}
inline search_iterator & search_iterator::begin(const char * FileSpec) {
#if defined WIN32
if (m_hFiles != -1) _findclose(m_hFiles);
m_Valid = ((m_hFiles = _findfirst(FileSpec, &m_FindData)) != -1);
#else
std::string DirectoryName;
if (m_Directory != NULL) closedir(m_Directory);
int i;
for (i = strlen(FileSpec); i >= 0; --i)
if (FileSpec[i] == '/') break;
if (i < 0)
DirectoryName = ".";
else
DirectoryName.assign(FileSpec + 0, FileSpec + i++);
m_Extension = FileSpec + i + 1;
std::transform(m_Extension.begin(), m_Extension.end(), m_Extension.begin(), ::tolower);
m_Valid = ((m_Directory = opendir(DirectoryName.c_str())) != NULL);
if (! m_Valid)
return (* this);
next();
#endif
return (* this);
}
inline bool search_iterator::end() const {
return false;
}
inline search_iterator & search_iterator::next() {
#if defined WIN32
m_Valid = (_findnext(m_hFiles, &m_FindData) != -1);
#else
bool Found = false;
while (! Found) {
m_Valid = ((m_DirectoryEntry = readdir(m_Directory)) != NULL);
if (m_Valid) {
std::string FileName = m_DirectoryEntry->d_name;
if (FileName[0] == '.')
Found = false;
else if (FileName.size() <= m_Extension.size())
Found = false;
else {
std::transform(FileName.begin(), FileName.end(), FileName.begin(), ::tolower);
if (std::equal(m_Extension.rbegin(), m_Extension.rend(), FileName.rbegin()))
Found = true;
}
}
else
break;
}
#endif
return (* this);
}
inline std::string search_iterator::Name() const {
#if defined WIN32
return (m_FindData.name);
#else
return (m_DirectoryEntry->d_name);
#endif
}
} // namespace io_facilities

View File

@@ -1,16 +0,0 @@
#pragma once
namespace mstatic_assert {
template <bool> class compile_time_error;
template <> class compile_time_error<true> { };
}
#define mstatic_assert(expr) { mstatic_assert::compile_time_error<((expr) != 0)> ERROR_STATIC_ASSERT; (void) ERROR_STATIC_ASSERT; }
#define mstatic_assert_msg(expr, msg) { mstatic_assert::compile_time_error<((expr) != 0)> ERROR_##msg; (void) ERROR_##msg; }

View File

@@ -1,8 +0,0 @@
// stdafx.cpp : source file that includes just the standard includes
// zfs.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file

View File

@@ -1,21 +0,0 @@
// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//
#pragma once
// Standard headers
#include <algorithm>
#include <cassert>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <map>
#include <string>
#include <vector>
//#include "stdint.h"
#include <stdint.h>

View File

@@ -1,77 +0,0 @@
#ifndef _ZIPFS_STDINT_H_
#define _ZIPFS_STDINT_H_
#include "static_assert.h"
#if defined _MSC_VER
typedef signed char int8_t;
typedef unsigned char uint8_t;
typedef signed short int16_t;
typedef unsigned short uint16_t;
typedef signed int int32_t;
typedef unsigned int uint32_t;
typedef signed __int64 int64_t;
typedef unsigned __int64 uint64_t;
typedef signed char int_least8_t;
typedef unsigned char uint_least8_t;
typedef signed short int_least16_t;
typedef unsigned short uint_least16_t;
typedef signed int int_least32_t;
typedef unsigned int uint_least32_t;
typedef signed __int64 int_least64_t;
typedef unsigned __int64 uint_least64_t;
#elif defined UNIX
typedef signed char int8_t;
typedef unsigned char uint8_t;
typedef signed short int16_t;
typedef unsigned short uint16_t;
typedef signed int int32_t;
typedef unsigned int uint32_t;
typedef signed long long int64_t;
typedef unsigned long long uint64_t;
typedef signed char int_least8_t;
typedef unsigned char uint_least8_t;
typedef signed short int_least16_t;
typedef unsigned short uint_least16_t;
typedef signed int int_least32_t;
typedef unsigned int uint_least32_t;
typedef signed long long int_least64_t;
typedef unsigned long long uint_least64_t;
#endif
inline void __CheckSizedTypes()
{
// one byte must be exactly 8 bits
//static_assert(CHAR_BIT == 8);
mstatic_assert(sizeof(int8_t) == 1);
mstatic_assert(sizeof(uint8_t) == 1);
mstatic_assert(sizeof(int16_t) == 2);
mstatic_assert(sizeof(uint16_t) == 2);
mstatic_assert(sizeof(int32_t) == 4);
mstatic_assert(sizeof(uint32_t) == 4);
mstatic_assert(sizeof(int64_t) == 8);
mstatic_assert(sizeof(uint64_t) == 8);
mstatic_assert(sizeof(int_least8_t) >= 1);
mstatic_assert(sizeof(uint_least8_t) >= 1);
mstatic_assert(sizeof(int_least16_t) >= 2);
mstatic_assert(sizeof(uint_least16_t) >= 2);
mstatic_assert(sizeof(int_least32_t) >= 4);
mstatic_assert(sizeof(uint_least32_t) >= 4);
mstatic_assert(sizeof(int_least64_t) >= 8);
mstatic_assert(sizeof(uint_least64_t) >= 8);
}
#endif

View File

@@ -1,44 +0,0 @@
// ZFS.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
// ZFS headers
#include "zfsystem.h"
void DoSomething(std::istream & File)
{
// Output the file via cout (note: rdbuf() method is a std C++ method, not zfs specific)
std::cout << File.rdbuf() << std::endl;
}
int main(int argc, char * argv[])
{
using namespace std;
using zip_file_system::filesystem;
using zip_file_system::izfstream;
// Create and initialize the Zip File System (basepath, file_extension, makedefault)
// and output the its status via cout
filesystem FileSystem("base_data", "cpk", true);
cout << FileSystem << endl;
// Try to open a zipped file (Careful! The openmode is always 'ios::in | ios::binary'.)
izfstream File("testfile.txt");
if (! File)
cout << "ERROR: Cannot open file!" << endl;
// Call some function expecting an istream object
DoSomething(File);
// The End.
cout << "\nPress ENTER to continue." << endl;
cin.get();
}

View File

@@ -1,21 +0,0 @@
Microsoft Visual Studio Solution File, Format Version 8.00
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "zfs", "zfs.vcproj", "{54F414A2-0634-467B-95D4-35E8D171D2CA}"
ProjectSection(ProjectDependencies) = postProject
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfiguration) = preSolution
Debug = Debug
Release = Release
EndGlobalSection
GlobalSection(ProjectConfiguration) = postSolution
{54F414A2-0634-467B-95D4-35E8D171D2CA}.Debug.ActiveCfg = Debug|Win32
{54F414A2-0634-467B-95D4-35E8D171D2CA}.Debug.Build.0 = Debug|Win32
{54F414A2-0634-467B-95D4-35E8D171D2CA}.Release.ActiveCfg = Release|Win32
{54F414A2-0634-467B-95D4-35E8D171D2CA}.Release.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
EndGlobalSection
GlobalSection(ExtensibilityAddIns) = postSolution
EndGlobalSection
EndGlobal

View File

@@ -1,175 +0,0 @@
<?xml version="1.0" encoding="Windows-1252"?>
<VisualStudioProject
ProjectType="Visual C++"
Version="7.10"
Name="zfs"
ProjectGUID="{54F414A2-0634-467B-95D4-35E8D171D2CA}"
Keyword="Win32Proj">
<Platforms>
<Platform
Name="Win32"/>
</Platforms>
<Configurations>
<Configuration
Name="Debug|Win32"
OutputDirectory="Debug"
IntermediateDirectory="Debug"
ConfigurationType="1"
CharacterSet="2">
<Tool
Name="VCCLCompilerTool"
Optimization="0"
PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE"
MinimalRebuild="TRUE"
BasicRuntimeChecks="3"
RuntimeLibrary="5"
UsePrecompiledHeader="3"
WarningLevel="3"
Detect64BitPortabilityProblems="TRUE"
DebugInformationFormat="4"/>
<Tool
Name="VCCustomBuildTool"/>
<Tool
Name="VCLinkerTool"
OutputFile="$(OutDir)/zfs.exe"
LinkIncremental="2"
GenerateDebugInformation="TRUE"
ProgramDatabaseFile="$(OutDir)/zfs.pdb"
SubSystem="1"
TargetMachine="1"/>
<Tool
Name="VCMIDLTool"/>
<Tool
Name="VCPostBuildEventTool"/>
<Tool
Name="VCPreBuildEventTool"/>
<Tool
Name="VCPreLinkEventTool"/>
<Tool
Name="VCResourceCompilerTool"/>
<Tool
Name="VCWebServiceProxyGeneratorTool"/>
<Tool
Name="VCXMLDataGeneratorTool"/>
<Tool
Name="VCWebDeploymentTool"/>
<Tool
Name="VCManagedWrapperGeneratorTool"/>
<Tool
Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
</Configuration>
<Configuration
Name="Release|Win32"
OutputDirectory="Release"
IntermediateDirectory="Release"
ConfigurationType="1"
CharacterSet="2">
<Tool
Name="VCCLCompilerTool"
PreprocessorDefinitions="WIN32;NDEBUG;_CONSOLE"
RuntimeLibrary="4"
UsePrecompiledHeader="3"
WarningLevel="3"
Detect64BitPortabilityProblems="TRUE"
DebugInformationFormat="3"/>
<Tool
Name="VCCustomBuildTool"/>
<Tool
Name="VCLinkerTool"
OutputFile="$(OutDir)/zfs.exe"
LinkIncremental="1"
GenerateDebugInformation="TRUE"
SubSystem="1"
OptimizeReferences="2"
EnableCOMDATFolding="2"
TargetMachine="1"/>
<Tool
Name="VCMIDLTool"/>
<Tool
Name="VCPostBuildEventTool"/>
<Tool
Name="VCPreBuildEventTool"/>
<Tool
Name="VCPreLinkEventTool"/>
<Tool
Name="VCResourceCompilerTool"/>
<Tool
Name="VCWebServiceProxyGeneratorTool"/>
<Tool
Name="VCXMLDataGeneratorTool"/>
<Tool
Name="VCWebDeploymentTool"/>
<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=".\stdafx.cpp">
<FileConfiguration
Name="Debug|Win32">
<Tool
Name="VCCLCompilerTool"
UsePrecompiledHeader="1"/>
</FileConfiguration>
<FileConfiguration
Name="Release|Win32">
<Tool
Name="VCCLCompilerTool"
UsePrecompiledHeader="1"/>
</FileConfiguration>
</File>
<File
RelativePath=".\zfs.cpp">
</File>
<File
RelativePath=".\zfsystem.cpp">
</File>
<File
RelativePath=".\ziphdr.cpp">
</File>
<File
RelativePath=".\zstream.cpp">
</File>
</Filter>
<Filter
Name="Header Files"
Filter="h;hpp;hxx;hm;inl;inc;xsd"
UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}">
<File
RelativePath=".\fileio.h">
</File>
<File
RelativePath=".\static_assert.h">
</File>
<File
RelativePath=".\stdafx.h">
</File>
<File
RelativePath=".\stdint.h">
</File>
<File
RelativePath=".\zfsystem.h">
</File>
<File
RelativePath=".\ziphdr.h">
</File>
<File
RelativePath=".\zstream.h">
</File>
<File
RelativePath=".\zstream_zlib.h">
</File>
</Filter>
</Files>
<Globals>
</Globals>
</VisualStudioProject>

View File

@@ -1,105 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{54F414A2-0634-467B-95D4-35E8D171D2CA}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<CharacterSet>MultiByte</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<CharacterSet>MultiByte</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup>
<_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>
<OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">.</OutDir>
<IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Debug\</IntDir>
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</LinkIncremental>
<OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Release\</OutDir>
<IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Release\</IntDir>
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</LinkIncremental>
<TargetExt Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">.lib</TargetExt>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MinimalRebuild>true</MinimalRebuild>
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
<PrecompiledHeader>NotUsing</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>EditAndContinue</DebugInformationFormat>
<AdditionalIncludeDirectories>..\JGE\Dependencies\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<AdditionalOptions>/NODEFAULTLIB:LIBCMT /NODEFAULTLIB:MSVCPRTD %(AdditionalOptions)</AdditionalOptions>
</ClCompile>
<Link>
<OutputFile>$(OutDir)zfs.exe</OutputFile>
<GenerateDebugInformation>true</GenerateDebugInformation>
<ProgramDatabaseFile>$(OutDir)zfs.pdb</ProgramDatabaseFile>
<SubSystem>Console</SubSystem>
<TargetMachine>MachineX86</TargetMachine>
<AdditionalLibraryDirectories>
</AdditionalLibraryDirectories>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<PrecompiledHeader>Use</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
</ClCompile>
<Link>
<OutputFile>$(OutDir)zfs.exe</OutputFile>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Console</SubSystem>
<OptimizeReferences>true</OptimizeReferences>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<TargetMachine>MachineX86</TargetMachine>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="zfs.cpp" />
<ClCompile Include="zfsystem.cpp" />
<ClCompile Include="ziphdr.cpp" />
<ClCompile Include="zstream.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="fileio.h" />
<ClInclude Include="static_assert.h" />
<ClInclude Include="stdafx.h" />
<ClInclude Include="stdint.h" />
<ClInclude Include="zfsystem.h" />
<ClInclude Include="ziphdr.h" />
<ClInclude Include="zstream.h" />
<ClInclude Include="zstream_zlib.h" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@@ -1,53 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Source Files">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="Header Files">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="zfs.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="zfsystem.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="ziphdr.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="zstream.cpp">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="fileio.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="static_assert.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="stdafx.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="stdint.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="zfsystem.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="ziphdr.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="zstream.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="zstream_zlib.h">
<Filter>Header Files</Filter>
</ClInclude>
</ItemGroup>
</Project>

View File

@@ -1,793 +0,0 @@
//Important: This file has been modified in order to be integrated in to JGE++
//
// zfsystem.cpp: implementation of the zip file system classes.
//
// Copyright (C) 2004 Tanguy Fautre
// For conditions of distribution and use,
// see copyright notice in zfsystem.h
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "zfsystem.h"
// Debug
#include "../../include/JLogger.h"
#include "fileio.h" // I/O facilities
#if defined (WIN32)
#include <sys/types.h>
#endif
#include <sys/stat.h>
namespace zip_file_system {
using namespace std;
//////////////////////////////////////////////////////////////////////
// Static variables initialization
//////////////////////////////////////////////////////////////////////
filesystem * izfstream::pDefaultFS = NULL;
string filesystem::CurrentZipName = "";
ifstream filesystem::CurrentZipFile;
filesystem * filesystem::pCurrentFS = NULL;
std::vector<filesystem::pooledBuffer *> filesystem::m_Buffers;
static const int STORED = 0;
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
filesystem::filesystem(const char * BasePath, const char * FileExt, bool DefaultFS)
: m_BasePath(BasePath), m_FileExt(FileExt)
{
using io_facilities::search_iterator;
// Init m_BasePath and be sure the base path finish with a '/' or a '\'
if (! m_BasePath.empty()) {
string::iterator c = m_BasePath.end();
c--;
if ((*c != '/') && (*c != '\\'))
m_BasePath += '/';
}
// Search all *.zip files (or whatever the ZipExt specify as the file extension)
// Search is case insensitive (see fileio.h for details)
// The case insensitive state is mostly because some of the filesystems we support such as FAT32 are case insensitive
// Being case sensitive would lead to weird bugs on these systems.
vector<string> ZipFiles;
for (search_iterator ZSrch = (m_BasePath + "*." + m_FileExt).c_str(); ZSrch != ZSrch.end(); ++ZSrch)
ZipFiles.push_back(ZSrch.Name());
// Open each zip files that have been found, in alphabetic order
sort(ZipFiles.begin(), ZipFiles.end());
for (vector<string>::const_iterator ZipIt = ZipFiles.begin(); ZipIt != ZipFiles.end(); ++ZipIt)
InsertZip(ZipIt->c_str(), ZipIt - ZipFiles.begin());
// Should we make this the default File System for ifile?
if (DefaultFS)
MakeDefault();
}
//////////////////////////////////////////////////////////////////////
// File System Member Functions
//////////////////////////////////////////////////////////////////////
zbuffer * filesystem::getValidBuffer(const std::string & filename, const std::string & externalFilename, std::streamoff Offset, std::streamoff Size )
{
//if exists filename in pool and is not in use, return that
for (size_t i = 0; i < m_Buffers.size(); ++i)
{
if (m_Buffers[i]->filename != filename)
continue;
zbuffer * buffer = m_Buffers[i]->buffer;
if (buffer && !buffer->is_used())
{
buffer->use(Offset, Size);
return buffer;
}
}
// if more than 3 objects in the pool, delete and close the first one that is unused
if (m_Buffers.size() > 3)
{
for (size_t i = 0; i < m_Buffers.size(); ++i)
{
zbuffer * buffer = m_Buffers[i]->buffer;
if (buffer && !buffer->is_used())
{
delete m_Buffers[i];
m_Buffers.erase(m_Buffers.begin() + i);
break;
}
}
}
//No possiblility to open more files for now
if (m_Buffers.size() > 3)
return NULL;
//create a new buffer object, add it to the pool, and return that
pooledBuffer * pb = new pooledBuffer(filename, externalFilename);
zbuffer * buffer = new zbuffer_stored();
buffer->open(filename.c_str(), Offset, Size);
pb->buffer = buffer;
m_Buffers.push_back(pb);
return pb->buffer;
}
void filesystem::closeBufferPool()
{
for (size_t i = 0; i < m_Buffers.size(); ++i)
{
if (m_Buffers[i])
{
if (m_Buffers[i]->buffer && m_Buffers[i]->buffer->is_used())
{
LOG("FATAL: File Buffer still in use but need to close");
}
delete m_Buffers[i];
}
}
m_Buffers.clear();
}
void filesystem::unuse(izfstream & File)
{
File.setstate(std::ios::badbit);
if (!File.Zipped())
{
delete(File.rdbuf(NULL));
}
else
{
zbuffer * buffer = static_cast<zbuffer *>(File.rdbuf());
if (buffer)
buffer->unuse();
}
}
void filesystem::Open(izfstream & File, const char * Filename)
{
// Close the file if it was opened;
File.close();
File.setFS(this);
// Generate the path and see if the file is zipped or not
string FullPath = m_BasePath + Filename;
// File is not zipped
if (FileNotZipped(FullPath.c_str())) {
// Link the izfile object with an opened filebuf
filebuf * FileBuf = new filebuf;
FileBuf->open(FullPath.c_str(), ios::binary | ios::in);
if (FileBuf->is_open()) {
#ifdef USE_ZBUFFER_POOL
File.rdbuf(FileBuf);
#else
delete File.rdbuf(FileBuf);
#endif
File.clear(ios::goodbit);
File.m_FilePath = Filename;
File.m_FullFilePath = FullPath;
File.m_Zipped = false;
}
// File is maybe zipped
} else {
file_info FileInfo;
string ZipPath;
// Check whether the file is zipped, whether the file is a directory and try to open.
if (FindFile(Filename, &FileInfo) && (! FileInfo.m_Directory) && (! ((ZipPath = FindZip(FileInfo.m_PackID)).empty()))) {
// Get the position of the compressed data
if (CurrentZipName.size())
{
if ((pCurrentFS!= this) || (CurrentZipName.compare(ZipPath) != 0))
{
CurrentZipFile.close();
CurrentZipName = "";
pCurrentFS = NULL;
}
}
if (!CurrentZipName.size())
{
CurrentZipName = ZipPath;
string zipName = m_BasePath + CurrentZipName;
CurrentZipFile.open(zipName.c_str(), ios::binary);
pCurrentFS = this;
}
if (!CurrentZipFile) {
CurrentZipName = "";
pCurrentFS = NULL;
return;
}
streamoff DataPos = SkipLFHdr(CurrentZipFile, streamoff(FileInfo.m_Offset));
if (DataPos != streamoff(-1)) {
string zipName = m_BasePath + CurrentZipName;
// Open the file at the right position
#ifdef USE_ZBUFFER_POOL
zbuffer * buffer = getValidBuffer(zipName, Filename, streamoff(DataPos), streamoff(FileInfo.m_CompSize));
if (!buffer)
{
File.setstate(ios::badbit);
}
else
{
File.rdbuf(buffer);
File._SetCompMethod(FileInfo.m_CompMethod);
#else
((izstream &) File).open(
zipName.c_str(),
streamoff(DataPos),
streamoff(FileInfo.m_CompSize),
FileInfo.m_CompMethod
);
if (File) {
#endif
File.m_FilePath = Filename;
File.m_FullFilePath = FullPath;
File.m_Zipped = true;
File.m_UncompSize = FileInfo.m_Size;
File.m_CompSize = FileInfo.m_CompSize;
File.m_Offset = FileInfo.m_Offset;
}
}
}
}
}
bool filesystem::DirExists(const std::string & folderName)
{
//Check in zip
file_info FileInfo;
// Check whether the file is zipped, whether the file is a directory and try to open.
if (FindFile(folderName.c_str(), &FileInfo) && (FileInfo.m_Directory))
return true;
//check real folder
string FullPath = m_BasePath + folderName;
#if defined (WIN32)
struct _stat statBuffer;
if ((_stat(FullPath.c_str(), &statBuffer) >= 0 && // make sure it exists
statBuffer.st_mode & S_IFDIR)) // and it's not a file
return true;
#else
struct stat st;
if (stat(FullPath.c_str(), &st) == 0)
return true;
#endif
//Neither in real folder nor in zip
return false;
}
bool filesystem::FileExists(const std::string & fileName)
{
if (fileName.length() < 1) return false;
//Check in zip
file_info FileInfo;
// Check whether the file is zipped, whether the file is a directory and try to open.
if (FindFile(fileName.c_str(), &FileInfo) && (!FileInfo.m_Directory))
return true;
//check real folder
string FullPath = m_BasePath + fileName;
#if defined (WIN32)
struct _stat statBuffer;
if (_stat(FullPath.c_str(), &statBuffer) >= 0) // make sure it exists
return true;
#else
struct stat st;
if (stat(FullPath.c_str(), &st) == 0)
return true;
#endif
//Neither in real folder nor in zip
return false;
}
// Note: this doesn't scan the folders outside of the zip...should we add that here ?
std::vector<std::string>& filesystem::scanfolder(const std::string& folderName, std::vector<std::string>& results)
{
filemap_const_iterator folderPos = m_Files.find(folderName);
if (folderPos == m_Files.end())
return results;
filemap_const_iterator It = folderPos;
string folderNameLC = folderName;
std::transform(folderNameLC.begin(), folderNameLC.end(), folderNameLC.begin(), ::tolower);
size_t length = folderNameLC.length();
while(++It != m_Files.end())
{
string currentFile = (* It).first;
string currentFileLC = currentFile;
std::transform(currentFileLC.begin(), currentFileLC.end(), currentFileLC.begin(), ::tolower);
if (currentFileLC.find(folderNameLC) == 0)
{
string relativePath = currentFile.substr(length);
size_t pos = relativePath.find_first_of("/\\");
//Only add direct children, no recursive browse
if (pos == string::npos || pos == (relativePath.length() - 1))
results.push_back(relativePath);
}
else
{
break;
//We know other files will not belong to that folder because of the order of the map
}
}
return results;
}
//////////////////////////////////////////////////////////////////////
// File System Protected Member Functions
//////////////////////////////////////////////////////////////////////
bool filesystem::FileNotZipped(const char * FilePath) const
{
//return io_facilities::search_iterator(FilePath);
// follow new search_iterator implementation
std::ifstream File(FilePath);
if (! File)
return false;
return true;
}
bool filesystem::FindFile(const char * Filename, file_info * FileInfo) const
{
filemap_const_iterator It = m_Files.find(Filename);
if (It == m_Files.end())
return false; // File not found
* FileInfo = (* It).second;
return true;
}
const string & filesystem::FindZip(size_t PackID) const
{
static const string EmptyString;
zipmap_const_iterator It = m_Zips.find(PackID);
if (It == m_Zips.end())
return EmptyString; // PackID not valid
return (* It).second.m_Filename;
}
void filesystem::InsertZip(const char * Filename, const size_t PackID)
{
zipfile_info ZipInfo;
// Get full path to the zip file and prepare ZipInfo
ZipInfo.m_Filename = Filename;
string ZipPath = m_BasePath + Filename;
// Open zip
LOG(("opening zip:" + ZipPath).c_str());
ifstream File(ZipPath.c_str(), ios::binary);
if (! File)
return;
// Find the start of the central directory
if (! File.seekg(CentralDir(File)))
{
File.close();
return;
}
LOG("open zip ok");
// Check every headers within the zip file
file_header FileHdr;
while ((NextHeader(File) == FILE) && (FileHdr.ReadHeader(File))) {
// Include files into Files map
const char * Name = &(* FileHdr.m_Filename.begin());
const unsigned short i = FileHdr.m_FilenameSize - 1;
if (FileHdr.m_FilenameSize != 0) {
m_Files[Name] = file_info(
PackID, // Package ID
FileHdr.m_RelOffset, // "Local File" header offset position
FileHdr.m_UncompSize, // File Size
FileHdr.m_CompSize, // Compressed File Size
FileHdr.m_CompMethod, // Compression Method;
((Name[i] == '/') || (Name[i] == '\\')) // Is a directory?
);
++(ZipInfo.m_NbEntries);
ZipInfo.m_FilesSize += FileHdr.m_UncompSize;
ZipInfo.m_FilesCompSize += FileHdr.m_CompSize;
}
}
File.close();
// Add zip file to Zips data base (only if not empty)
if (ZipInfo.m_NbEntries != 0)
m_Zips[PackID] = ZipInfo;
LOG("--zip file loading DONE");
}
bool filesystem::PreloadZip(const char * Filename, map<string, limited_file_info>& target)
{
zipfile_info ZipInfo;
// Open zip
izfstream File;
File.open(Filename, this);
if (! File)
return false;
// Find the start of the central directory
if (File.Zipped())
{
streamoff realBeginOfFile = SkipLFHdr(CurrentZipFile, File.getOffset());
if (! CurrentZipFile.seekg(CentralDirZipped(CurrentZipFile, realBeginOfFile, File.getCompSize())))
{
File.close();
return false;
}
// Check every headers within the zip file
file_header FileHdr;
while ((NextHeader(CurrentZipFile) == FILE) && (FileHdr.ReadHeader(CurrentZipFile))) {
// Include files into Files map
const char * Name = &(* FileHdr.m_Filename.begin());
if (FileHdr.m_FilenameSize != 0) {
// The zip in zip method only supports stored Zips because of JFileSystem limitations
if ((FileHdr.m_UncompSize != FileHdr.m_CompSize) || FileHdr.m_CompMethod != STORED)
continue;
target[Name] = limited_file_info(
realBeginOfFile + FileHdr.m_RelOffset, // "Local File" header offset position
FileHdr.m_UncompSize // File Size
);
}
}
File.close();
return (target.size() ? true : false);
}
else
{
if (! File.seekg(CentralDir(File)))
{
File.close();
return false;
}
// Check every headers within the zip file
file_header FileHdr;
while ((NextHeader(File) == FILE) && (FileHdr.ReadHeader(File))) {
// Include files into Files map
const char * Name = &(* FileHdr.m_Filename.begin());
if (FileHdr.m_FilenameSize != 0) {
// The zip in zip method only supports stored Zips because of JFileSystem limitations
if ((FileHdr.m_UncompSize != FileHdr.m_CompSize) || FileHdr.m_CompMethod != STORED)
continue;
target[Name] = limited_file_info(
FileHdr.m_RelOffset, // "Local File" header offset position
FileHdr.m_UncompSize // File Size
);
}
}
File.close();
return (target.size() ? true : false);
}
}
//////////////////////////////////////////////////////////////////////
// File System Friend Functions
//////////////////////////////////////////////////////////////////////
ostream & operator << (ostream & Out, const filesystem & FS)
{
size_t NbFiles = 0;
filesystem::zipfile_info AllZipsInfo;
for (filesystem::zipmap_const_iterator It = FS.m_Zips.begin(); It != FS.m_Zips.end(); ++It) {
const filesystem::zipfile_info & ZInfo = (* It).second;
// Print zip filename
Out << setiosflags(ios::left) << setw(32) << "-> \"" + ZInfo.m_Filename + "\"" << resetiosflags(ios::left);
// Print number of entries found in this zip file
Out << " " << setw(5) << ZInfo.m_NbEntries << " files";
// Print the uncompressed size of all included files
Out << " " << setw(7) << ZInfo.m_FilesSize / 1024 << " KB";
// Print the compressed size of all these files
Out << " " << setw(7) << ZInfo.m_FilesCompSize / 1024 << " KB packed" << endl;
++NbFiles;
AllZipsInfo.m_NbEntries += ZInfo.m_NbEntries;
AllZipsInfo.m_FilesSize += ZInfo.m_FilesSize;
AllZipsInfo.m_FilesCompSize += ZInfo.m_FilesCompSize;
}
// Print the general info
Out << "\nTotal: ";
Out << NbFiles << " packs ";
Out << AllZipsInfo.m_NbEntries << " files ";
Out << float(AllZipsInfo.m_FilesSize) / (1024 * 1024) << " MB ";
Out << float(AllZipsInfo.m_FilesCompSize) / (1024 * 1024) << " MB packed." << endl;
return Out;
}
//////////////////////////////////////////////////////////////////////
// "Less Than" Comparaison lt_path_str Member Functions
//////////////////////////////////////////////////////////////////////
bool filesystem::lt_path::operator () (const string & s1, const string & s2) const
{
const char * A = s1.c_str();
const char * B = s2.c_str();
for (size_t i = 0; ; ++i) {
if ((A[i] == '\0') && (B[i] == '\0'))
return false;
// '/' is the same as '\'
if (! (
(A[i] == B[i]) ||
((A[i] == '\\') && (B[i] == '/')) ||
((A[i] == '/') && (B[i] == '\\'))
)) {
// This line puts uppercases first
if ((A[i] == '\0') || (A[i] < B[i]))
return true;
else
return false;
}
}
}
//////////////////////////////////////////////////////////////////////
// Zip Header Classes Related Member Functions
//////////////////////////////////////////////////////////////////////
streamoff filesystem::CentralDirZipped(std::istream & File, std::streamoff begin, std::size_t size) const
{
using io_facilities::readvar;
std::streamoff eof = begin + size;
// Look for the "end of central dir" header. Start minimum 22 bytes before end.
if (! File.seekg(eof - 22, ios::beg))
return -1;
streamoff EndPos;
streamoff StartPos = File.tellg();
if (StartPos == streamoff(0))
return -1;
if (StartPos <= begin + streamoff(65536))
EndPos = 1;
else
EndPos = StartPos - streamoff(65536);
// Start the scan
do {
unsigned int RawSignature;
if (! readvar(File, RawSignature, 4))
return -1;
eofcd_header Header;
streampos Pos = File.tellg();
// Found a potential "eofcd" header?
if ((RawSignature == ENDOFDIR) && (File.seekg(-4, ios::cur)) && (Header.ReadHeader(File))) {
// Check invariant values (1 disk only)
if ((Header.m_NbDisks == 0) && (0 == Header.m_DirDisk) && (Header.m_LocalEntries == Header.m_TotalEntries)) {
// Check comment ends at eof
if (! File.seekg(eof - 1 , ios::beg))
return -1;
if ((File.tellg() + streamoff(1)) == (Pos + streamoff(Header.m_CommentSize + 22 - 4))) {
// Check the start offset leads to a correct directory/file header;
if (! File.seekg(begin + Header.m_Offset)) return -1;
if (! readvar(File, RawSignature, 4)) return -1;
if (RawSignature == FILE)
return begin + Header.m_Offset;
}
}
}
File.seekg(Pos);
} while ((File.seekg(-5, ios::cur)) && (File.tellg() > EndPos) && (File.tellg() > begin));
return -1;
}
streamoff filesystem::CentralDir(istream & File) const
{
using io_facilities::readvar;
// Look for the "end of central dir" header. Start minimum 22 bytes before end.
if (! File.seekg(-22, ios::end)) return -1;
streamoff EndPos;
streamoff StartPos = File.tellg();
if (StartPos == streamoff(0)) return -1;
if (StartPos <= streamoff(65536))
EndPos = 1;
else
EndPos = StartPos - streamoff(65536);
// Start the scan
do {
unsigned int RawSignature;
if (! readvar(File, RawSignature, 4)) return -1;
eofcd_header Header;
streampos Pos = File.tellg();
// Found a potential "eofcd" header?
if ((RawSignature == ENDOFDIR) && (File.seekg(-4, ios::cur)) && (Header.ReadHeader(File))) {
// Check invariant values (1 disk only)
if ((Header.m_NbDisks == 0) && (0 == Header.m_DirDisk) && (Header.m_LocalEntries == Header.m_TotalEntries)) {
// Check comment ends at eof
if (! File.seekg(-1, ios::end)) return -1;
if ((File.tellg() + streamoff(1)) == (Pos + streamoff(Header.m_CommentSize + 22 - 4))) {
// Check the start offset leads to a correct directory/file header;
if (! File.seekg(Header.m_Offset)) return -1;
if (! readvar(File, RawSignature, 4)) return -1;
if (RawSignature == FILE)
return Header.m_Offset;
}
}
}
File.seekg(Pos);
} while ((File.seekg(-5, ios::cur)) && (File.tellg() > EndPos));
return -1;
}
streamoff filesystem::SkipLFHdr(istream & File, streamoff LFHdrPos)
{
using io_facilities::readvar;
unsigned short NameSize;
unsigned short FieldSize;
unsigned int RawSignature;
// verify it's a local header
if (! File.seekg(LFHdrPos)) return -1;
if (! readvar(File, RawSignature, 4)) return -1;
if (RawSignature != LOCALFILE) return -1;
// Skip and go directly to comment/field size
if (! File.seekg(22, ios::cur)) return -1;
if (! readvar(File, NameSize, 2)) return -1;
if (! readvar(File, FieldSize, 2)) return -1;
// Skip comment and extra field
if (! File.seekg(NameSize + FieldSize, ios::cur)) return -1;
// Now we are at the compressed data position
return (File.tellg());
}
headerid filesystem::NextHeader(istream & File) const
{
using io_facilities::readvar;
unsigned int RawSignature;
if (! readvar(File, RawSignature, 4))
return READERROR;
if (! File.seekg(-4, ios::cur))
return READERROR;
headerid Signature = headerid(RawSignature);
switch (Signature) {
case FILE:
case LOCALFILE:
case ENDOFDIR:
return Signature;
default:
return UNKNOWN;
}
}
} // namespace zip_file_system

View File

@@ -1,332 +0,0 @@
//Important: This file has been modified in order to be integrated in to JGE++
//
// zfsystem.h: interface for the zip file system classes.
//
//////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2004 Tanguy Fautre
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//
// Tanguy Fautr<74>E
// softdev@telenet.be
//
//////////////////////////////////////////////////////////////////////
//
// Zip File System.
// ****************
//
// Current version: 1.00 BETA 2 (16/07/2004)
//
// Comment: -
//
// History: - 1.00 BETA 2 (16/07/2004) - Updated to follow latest version
// of fileio.h
// - 1.00 BETA 1 (21/07/2002) - First public release
//
//////////////////////////////////////////////////////////////////////
#pragma once
#include "stdafx.h"
#include "ziphdr.h" // Zip file header
#include "zstream.h" // Zip Stream
// Zip File System Namespace
namespace zip_file_system {
class filesystem;
// Input Zip File class
class izfstream : public izstream
{
public:
izfstream(filesystem * pFS = pDefaultFS);
izfstream(const char * FilePath, filesystem * pFS = pDefaultFS);
void open(const char * FilePath, filesystem * pFS = pDefaultFS);
void close();
bool is_open() const;
void setFS(filesystem * pFS = pDefaultFS);
bool Zipped() const;
bool isBeingUsed() const;
const std::string & FilePath() const;
const std::string & FullFilePath() const;
size_t getUncompSize();
size_t getOffset();
size_t getCompSize();
protected:
friend class filesystem;
// Default File System Pointer (default = NULL)
static filesystem * pDefaultFS;
std::string m_FilePath;
std::string m_FullFilePath;
filesystem * m_pFS;
bool m_Zipped;
size_t m_UncompSize;
size_t m_Offset;
size_t m_CompSize;
bool m_Used;
};
// Zip File System central class
class filesystem
{
public:
// "local" file info class
class file_info
{
public:
file_info() : m_PackID(0), m_Offset(0), m_Size(0), m_CompSize(0), m_CompMethod(0), m_Directory(true) { }
file_info(size_t PackID, size_t Offset, size_t Size, size_t CompSize, short CompMethod, bool Directory) :
m_PackID(PackID), m_Offset(Offset), m_Size(Size), m_CompSize(CompSize), m_CompMethod(CompMethod), m_Directory(Directory) { }
size_t m_PackID;
size_t m_Offset;
size_t m_Size;
size_t m_CompSize;
short m_CompMethod;
bool m_Directory;
};
class limited_file_info
{
public:
limited_file_info() : m_Offset(0), m_Size(0) { }
limited_file_info(size_t Offset, size_t Size) :
m_Offset(Offset), m_Size(Size) { }
size_t m_Offset;
size_t m_Size;
};
class pooledBuffer
{
public:
pooledBuffer(std::string filename, std::string externalFilename ) : filename(filename), externalFilename(externalFilename), buffer(NULL) {}
~pooledBuffer() { if (buffer) { delete buffer; } }
std::string filename;
std::string externalFilename;
zbuffer * buffer;
};
filesystem(const char * BasePath = "", const char * FileExt = "zip", bool DefaultFS = true);
~filesystem();
void MakeDefault();
void Open(izfstream & File, const char * Filename);
bool DirExists(const std::string & folderName);
bool FileExists(const std::string & fileName);
bool PreloadZip(const char * Filename, std::map<std::string, limited_file_info>& target);
static std::string getCurrentZipName();
static filesystem * getCurrentFS();
static std::streamoff SkipLFHdr(std::istream & File, std::streamoff LFHdrPos);
void unuse(izfstream & File);
//Fills the vector results with a list of children of the given folder
std::vector<std::string>& scanfolder(const std::string& folderName, std::vector<std::string>& results);
friend std::ostream & operator << (std::ostream & Out, const filesystem & FS);
static void closeTempFiles();
protected:
// Zip file info class
class zipfile_info
{
public:
zipfile_info() : m_NbEntries(0), m_FilesSize(0), m_FilesCompSize(0) { }
std::string m_Filename;
size_t m_NbEntries;
size_t m_FilesSize;
size_t m_FilesCompSize;
};
// Class for file path string comparaison
struct lt_path
{
bool operator() (const std::string & s1, const std::string & s2) const;
};
// Protected member functions
// Zip file format related functions
std::streamoff CentralDir(std::istream & File) const;
std::streamoff CentralDirZipped(std::istream & File, std::streamoff begin, std::size_t size) const;
headerid NextHeader(std::istream & File) const;
// File/Zip map related functions
bool FileNotZipped(const char * FilePath) const;
bool FindFile(const char * Filename, file_info * FileInfo) const;
const std::string & FindZip(size_t PackID) const;
void InsertZip(const char * Filename, const size_t PackID);
static zbuffer * getValidBuffer(const std::string & filename, const std::string & externalFilename, std::streamoff Offset = 0, std::streamoff Size = 0);
static void closeBufferPool();
// New type definitions
typedef std::map<size_t, zipfile_info> zipmap;
typedef std::map<size_t, zipfile_info>::iterator zipmap_iterator;
typedef std::map<size_t, zipfile_info>::const_iterator zipmap_const_iterator;
typedef std::map<std::string, file_info, lt_path> filemap;
typedef std::map<std::string, file_info, lt_path>::iterator filemap_iterator;
typedef std::map<std::string, file_info, lt_path>::const_iterator filemap_const_iterator;
// Mighty protected member variables
std::string m_BasePath;
std::string m_FileExt;
zipmap m_Zips;
filemap m_Files;
static std::vector<pooledBuffer *> m_Buffers;
static std::ifstream CurrentZipFile;
static std::string CurrentZipName;
static filesystem * pCurrentFS;
};
//////////////////////////////////////////////////////////////////////
// zip_file_system::izfile Inline Functions
//////////////////////////////////////////////////////////////////////
inline izfstream::izfstream(filesystem * pFS) : m_pFS(pFS) { }
inline izfstream::izfstream(const char * FilePath, filesystem * pFS) : m_pFS(pFS) {
open(FilePath);
}
inline void izfstream::setFS(filesystem * pFS) {
m_pFS = pFS;
}
inline size_t izfstream::getUncompSize()
{
return m_UncompSize;
}
inline size_t izfstream::getOffset()
{
return m_Offset;
}
inline size_t izfstream::getCompSize()
{
return m_CompSize;
}
inline void izfstream::open(const char * FilePath, filesystem * pFS) {
if (pFS)
m_pFS = pFS;
if (m_pFS != NULL)
m_pFS->Open(* this, FilePath);
}
inline void izfstream::close() {
#ifdef USE_ZBUFFER_POOL
if (m_pFS)
m_pFS->unuse( * this);
#else
izstream::close();
#endif
m_FilePath = m_FullFilePath = "";
m_UncompSize = 0;
}
inline bool izfstream::is_open() const {
return static_cast<zbuffer *>(rdbuf())->is_open();
}
inline bool izfstream::Zipped() const {
return m_Zipped;
}
inline bool izfstream::isBeingUsed() const {
return m_Used;
}
inline const std::string & izfstream::FilePath() const {
return m_FilePath;
}
inline const std::string & izfstream::FullFilePath() const {
return m_FullFilePath;
}
//////////////////////////////////////////////////////////////////////
// zip_file_system::filesystem Inline Functions
//////////////////////////////////////////////////////////////////////
inline filesystem::~filesystem() {
// Security mesure with izfile::pDefaultFS
if (izfstream::pDefaultFS == this)
izfstream::pDefaultFS = NULL;
}
inline void filesystem::closeTempFiles() {
if (CurrentZipName.size())
{
CurrentZipFile.close();
CurrentZipName = "";
}
closeBufferPool();
}
inline void filesystem::MakeDefault() {
izfstream::pDefaultFS = this;
}
inline std::string filesystem::getCurrentZipName()
{
return CurrentZipName;
}
inline filesystem * filesystem::getCurrentFS()
{
return pCurrentFS;
}
} // namespace zip_file_system

View File

@@ -1,123 +0,0 @@
// ziphdr.cpp: implementation of the zip header classes.
//
// Copyright (C) 2002 Tanguy Fautre
// For conditions of distribution and use,
// see copyright notice in ziphdr.h
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "ziphdr.h"
#include "fileio.h" // I/O facilities
namespace zip_file_system {
//////////////////////////////////////////////////////////////////////
// Zip Header Classes Member Functions
//////////////////////////////////////////////////////////////////////
bool local_file_header::ReadHeader(std::istream & File)
{
using io_facilities::readvar;
// quick check about char size
//static_assert(CHAR_BIT == 8);
if (! readvar(File, m_Signature, 4)) return false;
if (! readvar(File, m_VersionExtract, 2)) return false;
if (! readvar(File, m_GeneralFlags, 2)) return false;
if (! readvar(File, m_CompMethod, 2)) return false;
if (! readvar(File, m_Time, 2)) return false;
if (! readvar(File, m_Date, 2)) return false;
if (! readvar(File, m_CRC32, 4)) return false;
if (! readvar(File, m_CompSize, 4)) return false;
if (! readvar(File, m_UncompSize, 4)) return false;
if (! readvar(File, m_FilenameSize, 2)) return false;
if (! readvar(File, m_FieldSize, 2)) return false;
m_Filename.resize(m_FilenameSize + 1);
m_ExtraField.resize(m_FieldSize + 1);
if (! File.read(&(m_Filename[0]), m_FilenameSize)) return false;
if (! File.read(&(m_ExtraField[0]), m_FieldSize)) return false;
m_Filename[m_FilenameSize] = '\0';
m_ExtraField[m_FieldSize] = '\0';
return true;
}
bool file_header::ReadHeader(std::istream & File)
{
using io_facilities::readvar;
if (! readvar(File, m_Signature, 4)) return false;
if (! readvar(File, m_VersionMade, 2)) return false;
if (! readvar(File, m_VersionExtract, 2)) return false;
if (! readvar(File, m_GeneralFlags, 2)) return false;
if (! readvar(File, m_CompMethod, 2)) return false;
if (! readvar(File, m_Time, 2)) return false;
if (! readvar(File, m_Date, 2)) return false;
if (! readvar(File, m_CRC32, 4)) return false;
if (! readvar(File, m_CompSize, 4)) return false;
if (! readvar(File, m_UncompSize, 4)) return false;
if (! readvar(File, m_FilenameSize, 2)) return false;
if (! readvar(File, m_FieldSize, 2)) return false;
if (! readvar(File, m_CommentSize, 2)) return false;
if (! readvar(File, m_DiskNb, 2)) return false;
if (! readvar(File, m_IntAttrib, 2)) return false;
if (! readvar(File, m_ExtAttrib, 4)) return false;
if (! readvar(File, m_RelOffset, 4)) return false;
m_Filename.resize(m_FilenameSize + 1);
m_ExtraField.resize(m_FieldSize + 1);
m_Comment.resize(m_CommentSize + 1);
if (! File.read(&(m_Filename[0]), m_FilenameSize)) return false;
if (! File.read(&(m_ExtraField[0]), m_FieldSize)) return false;
if (! File.read(&(m_Comment[0]), m_CommentSize)) return false;
m_Filename[m_FilenameSize] = '\0';
m_ExtraField[m_FieldSize] = '\0';
m_Comment[m_CommentSize] = '\0';
return true;
}
bool eofcd_header::ReadHeader(std::istream & File)
{
using io_facilities::readvar;
if (! readvar(File, m_Signature, 4)) return false;
if (! readvar(File, m_NbDisks, 2)) return false;
if (! readvar(File, m_DirDisk, 2)) return false;
if (! readvar(File, m_LocalEntries, 2)) return false;
if (! readvar(File, m_TotalEntries, 2)) return false;
if (! readvar(File, m_DirSize, 4)) return false;
if (! readvar(File, m_Offset, 4)) return false;
if (! readvar(File, m_CommentSize, 2)) return false;
m_Comment.resize(m_CommentSize + 1);
if (! File.read(&(m_Comment[0]), m_CommentSize)) return false;
m_Comment[m_CommentSize] = '\0';
return true;
}
} // namespace zip_file_system

View File

@@ -1,143 +0,0 @@
// zfsystem.h: interface for the zip header classes.
//
//////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2002 Tanguy Fautre
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//
// Tanguy Fautr<74>E
// softdev@telenet.be
//
//////////////////////////////////////////////////////////////////////
//
// Zip File Format Headers.
// ***********************
//
// Current version: 1.00 BETA 2 (01/09/2003)
//
// Comment: Based on the ZIP file format specification from Appnote.txt
// from the PKZip Website on July 13, 1998.
// New implementations of the ZIP file format might not work
// correctly (ZIP64 ?).
//
// History: - 1.00 BETA 2 (01/09/2003) - Use stdint.h sized types
// - 1.00 BETA 1 (12/06/2002) - First public release
//
//////////////////////////////////////////////////////////////////////
#pragma once
// Zip File System Namespace
namespace zip_file_system {
// Zip file headers
enum headerid { LOCALFILE = 0x04034b50,
FILE = 0x02014b50,
ENDOFDIR = 0x06054b50,
UNKNOWN,
READERROR
};
// Zip file "local file" header class
struct local_file_header
{
bool ReadHeader(std::istream & File);
static const uint_least32_t m_ConstSign= LOCALFILE;
uint_least32_t m_Signature;
uint_least16_t m_VersionExtract;
uint_least16_t m_GeneralFlags;
uint_least16_t m_CompMethod;
uint_least16_t m_Time;
uint_least16_t m_Date;
uint_least32_t m_CRC32;
uint_least32_t m_CompSize;
uint_least32_t m_UncompSize;
uint_least16_t m_FilenameSize;
uint_least16_t m_FieldSize;
std::vector<char> m_Filename;
std::vector<char> m_ExtraField;
};
// Zip file "file header" header class
struct file_header
{
bool ReadHeader(std::istream & File);
static const headerid m_ConstSign = FILE;
uint_least32_t m_Signature;
uint_least16_t m_VersionMade;
uint_least16_t m_VersionExtract;
uint_least16_t m_GeneralFlags;
uint_least16_t m_CompMethod;
uint_least16_t m_Time;
uint_least16_t m_Date;
uint_least32_t m_CRC32;
uint_least32_t m_CompSize;
uint_least32_t m_UncompSize;
uint_least16_t m_FilenameSize;
uint_least16_t m_FieldSize;
uint_least16_t m_CommentSize;
uint_least16_t m_DiskNb;
uint_least16_t m_IntAttrib;
uint_least32_t m_ExtAttrib;
uint_least32_t m_RelOffset;
std::vector<char> m_Filename;
std::vector<char> m_ExtraField;
std::vector<char> m_Comment;
};
// Zip file "end of central dir" header class
struct eofcd_header
{
bool ReadHeader(std::istream & File);
static const headerid m_ConstSign = ENDOFDIR;
uint_least32_t m_Signature;
uint_least16_t m_NbDisks;
uint_least16_t m_DirDisk;
uint_least16_t m_LocalEntries;
uint_least16_t m_TotalEntries;
uint_least32_t m_DirSize;
uint_least32_t m_Offset;
uint_least16_t m_CommentSize;
std::vector<char> m_Comment;
};
} // namespace zip_file_system

View File

@@ -1,453 +0,0 @@
// zstream.cpp: implementation of the zstream class.
//
// Copyright (C) 2002 Tanguy Fautre
// For conditions of distribution and use,
// see copyright notice in zfsystem.h
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "zstream.h"
namespace zip_file_system {
using namespace std;
//////////////////////////////////////////////////////////////////////
// zstream Member Functions
//////////////////////////////////////////////////////////////////////
void izstream::open(const char * Filename, streamoff Offset, streamoff Size, int CompMethod)
{
// Change the buffer if need
if (m_CompMethod == CompMethod) {
if (rdbuf() != NULL)
static_cast<zbuffer *>(rdbuf())->close();
} else
SetCompMethod(CompMethod);
// clear up the file status
clear(ios::goodbit);
// open the buffer
switch (m_CompMethod) {
case STORED:
case DEFLATED:
if (! (static_cast<zbuffer *>(rdbuf())->open(Filename, Offset, Size))) {
setstate(ios::badbit);
SetCompMethod(-1);
}
break;
default:
setstate(ios::badbit);
}
}
zbuffer * izstream::GetRightBuffer(int CompMethod) const
{
switch (CompMethod) {
// stored
case STORED:
return new zbuffer_stored;
// deflated
case DEFLATED:
return new zbuffer_deflated;
// else not supported
default:
return NULL;
}
}
bool zbuffer::use(std::streamoff Offset, std::streamoff Size)
{
if (! m_ZipFile)
return false;
//Don't use a buffer already used;
if (m_Used)
return false;
// adjust file position
if (! m_ZipFile.seekg(Offset, ios::beg))
return false;
setg( m_Buffer, // beginning of putback area
m_Buffer, // read position
m_Buffer); // end of buffer
m_Buffer[0] = 0;
m_Pos = -1;
m_Size = Size;
m_Used = true;
return true;
}
//////////////////////////////////////////////////////////////////////
// zbuffer_stored Member Functions
//////////////////////////////////////////////////////////////////////
zbuffer_stored * zbuffer_stored::open(const char * Filename, streamoff Offset, streamoff Size)
{
// open main compressed file
m_ZipFile.open(Filename, ios::binary);
if (! m_ZipFile)
return NULL;
// adjust file position
if (! use(Offset, Size))
return NULL;
m_Opened = true;
m_Filename = Filename;
return this;
}
zbuffer_stored * zbuffer_stored::close()
{
if (! m_Opened)
return NULL;
else {
m_Opened = false;
m_Used = false;
m_ZipFile.close();
}
return this;
}
int zbuffer_stored::overflow(int)
{
return EOF;
}
int zbuffer_stored::underflow()
{
// Buffer Valid?
if (! m_Opened)
return EOF;
// Do we really need to refill it?
if (gptr() < egptr())
return static_cast<unsigned char>(* gptr());
// Refill de buffer.
// Set the real position of the beginning of the buffer.
if (m_Pos == streamoff(-1))
m_Pos = 0;
streamoff ToRead = ((m_Size - m_Pos) < BUFFERSIZE) ? (m_Size - m_Pos) : BUFFERSIZE;
if ((ToRead == 0) || (! m_ZipFile.read(m_Buffer, ToRead)))
return EOF;
m_Pos += ToRead;
// Reset buffer pointers.
setg( m_Buffer, // beginning of putback area
m_Buffer, // read position
m_Buffer + ToRead); // end of buffer
return static_cast<unsigned char>(m_Buffer[0]);
}
streampos zbuffer_stored::seekoff(streamoff off, ios::seekdir dir, ios::openmode nMode)
{
streamoff WantedPos = 0;
// Find out the wanted position.
switch (dir) {
case ios_base::cur:
WantedPos = m_Pos + streamoff(gptr() - eback()) + off;
break;
case ios_base::beg:
WantedPos = off;
break;
case ios_base::end:
WantedPos = m_Size + off;
break;
default:
assert(false);
}
// Is the position valid?
if ((WantedPos < 0) || (WantedPos > m_Size))
return streambuf::seekoff(off, dir, nMode); // return invalid streamoff
// Is the position already within the buffer?
if ((WantedPos >= m_Pos) && (WantedPos - m_Pos < egptr() - eback())) {
setg(eback(), eback() + (WantedPos - m_Pos), egptr());
return WantedPos;
}
// Fill up the buffer at the right position.
if (! m_ZipFile.seekg(WantedPos, ios::beg))
return streambuf::seekoff(off, dir, nMode);
m_Pos = WantedPos;
streamoff ToRead = ((m_Size - m_Pos) < BUFFERSIZE) ? (m_Size - m_Pos) : BUFFERSIZE;
if (ToRead == 0)
return WantedPos;
if (! m_ZipFile.read(m_Buffer, ToRead))
return streambuf::seekoff(off, dir, nMode);
// Set the buffer at the right position
setg(m_Buffer, m_Buffer, m_Buffer + ToRead);
return WantedPos;
}
int zbuffer_stored::sync()
{
return 0;
}
streambuf * zbuffer_stored::setbuf(char *, int)
{
return NULL;
}
//////////////////////////////////////////////////////////////////////
// zbuffer_deflated Member Functions
//////////////////////////////////////////////////////////////////////
zbuffer_deflated * zbuffer_deflated::open(const char * Filename, streamoff Offset, streamoff Size)
{
// open main compressed file
m_ZipFile.open(Filename, ios::binary);
if (! m_ZipFile)
return NULL;
// adjust file position
if (! use(Offset, Size))
return NULL;
// z_stream (NULL) Initialization
m_ZStream.next_in = Z_NULL;
m_ZStream.avail_in = 0;
m_ZStream.total_in = 0;
m_ZStream.next_out = Z_NULL;
m_ZStream.avail_out = 0;
m_ZStream.total_out = 0;
m_ZStream.zalloc = Z_NULL;
m_ZStream.zfree = Z_NULL;
m_ZStream.opaque = Z_NULL;
// inflate routine Initialization: Window Size = -MAX_WBITS tells there are no header
if (inflateInit2(&m_ZStream, -MAX_WBITS) != Z_OK)
return NULL;
m_Opened = true;
m_StreamEnd = false;
m_Pos = 0;
m_CompPos = 0;
m_Filename = Filename;
return this;
}
zbuffer_deflated * zbuffer_deflated::close()
{
if (! m_Opened)
return NULL;
else {
m_Opened = false;
m_Used = false;
m_ZipFile.close();
// z_stream unitialization.
if (inflateEnd(&m_ZStream) != Z_OK)
return NULL;
}
return this;
}
int zbuffer_deflated::overflow(int)
{
return EOF;
}
int zbuffer_deflated::underflow()
{
// Buffer Valid?
if (! m_Opened)
return EOF;
// Do we really need to refill it?
if (gptr() < egptr())
return static_cast<unsigned char>(* gptr());
// Can we refill?
if (m_StreamEnd)
return EOF;
streamoff ToRead;
streamoff OldPos;
bool BufferRefill = false;
// Check input (compressed) buffer status
if ((m_ZStream.avail_in == 0) && (m_CompPos < m_Size )) {
ToRead = ((m_Size - m_CompPos) > BUFFERSIZE) ? BUFFERSIZE : (m_Size - m_CompPos);
m_CompPos += ToRead;
if (! m_ZipFile.read(m_CompBuffer, ToRead))
return EOF;
m_ZStream.next_in = reinterpret_cast<unsigned char *>(m_CompBuffer);
m_ZStream.avail_in = ToRead;
}
// Ajust start read position in output buffer at the "old" end of buffer
ToRead = m_ZStream.total_out % BUFFERSIZE;
OldPos = m_ZStream.total_out;
// Check output (decompressed) buffer status
if (m_ZStream.avail_out == 0) {
BufferRefill = true;
m_ZStream.next_out = reinterpret_cast<unsigned char *>(m_Buffer);
m_ZStream.avail_out = BUFFERSIZE;
}
// Decompress (Inflate)
int Result = inflate(&m_ZStream, Z_SYNC_FLUSH);
// Check decompression result
if (Result == Z_STREAM_END)
m_StreamEnd = true;
else if (Result != Z_OK)
return EOF;
// Set the real position of the beginning of the buffer.
if (m_Pos == streamoff(-1))
m_Pos = 0;
else
if (BufferRefill)
m_Pos += m_ZStream.total_out - OldPos;
// Reset buffer pointers.
setg( m_Buffer, // beginning of putback area
m_Buffer + ToRead, // read position
m_Buffer + ((m_ZStream.total_out - 1) % (BUFFERSIZE)) + 1); // end of buffer
return static_cast<unsigned char>(m_Buffer[ToRead]);
}
streampos zbuffer_deflated::seekoff(std::streamoff off, std::ios::seekdir dir, std::ios::openmode nMode)
{
streamoff WantedPos = 0;
// Find out the wanted position.
switch (dir) {
case ios_base::cur:
WantedPos = m_Pos + streamoff(gptr() - eback()) + off;
break;
case ios_base::beg:
WantedPos = off;
break;
case ios_base::end:
WantedPos = m_Size + off;
break;
default:
assert(false);
}
// Is the position valid?
if ((WantedPos < 0) || (WantedPos > m_Size))
return streambuf::seekoff(off, dir, nMode); // return invalid streamoff
// Is the position already within the buffer?
if ((WantedPos >= m_Pos) && (WantedPos - m_Pos < egptr() - eback())) {
setg(eback(), eback() + (WantedPos - m_Pos), egptr());
return WantedPos;
}
// Found out whether we have to decompress further or if we have to reset the decompression.
if (WantedPos < m_Pos) {
// Reset the decompression.
if (inflateReset(&m_ZStream) != Z_OK)
return streambuf::seekoff(off, dir, nMode);
// z_stream Reset
m_ZStream.next_in = Z_NULL;
m_ZStream.avail_in = 0;
m_ZStream.total_in = 0;
m_ZStream.next_out = Z_NULL;
m_ZStream.avail_out = 0;
m_ZStream.total_out = 0;
}
// call underflow() untill the right position is within the buffer.
while (WantedPos - m_Pos >= egptr() - eback()) {
setg(eback(), egptr(), egptr());
if (underflow() == EOF)
return streambuf::seekoff(off, dir, nMode);
}
// now the position is within the buffer.
setg(eback(), eback() + (WantedPos - m_Pos), egptr());
return WantedPos;
}
int zbuffer_deflated::sync()
{
return 0;
}
streambuf * zbuffer_deflated::setbuf(char *, int)
{
return NULL;
}
} // namespace zip_file_system

View File

@@ -1,191 +0,0 @@
// zstream.h: interface for the zstream classes.
//
//////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2002 Tanguy Fautre
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//
// Tanguy Fautr<74>E
// softdev@telenet.be
//
//////////////////////////////////////////////////////////////////////
//
// Zip (Input) Stream.
// *******************
//
// Current version: 1.00 BETA 4 (02/09/2003)
//
// Comment: izstream currently only supports "stored" and "deflated"
// compression methods.
//
// !!!IMPORTANT!!!
// Modify "zstream_zlib.h" for headers and lib dependencies
// on Zlib (http://www.zlib.org)
//
// History: - 1.00 BETA 4 (02/09/2003) - Made zbuffer constructor protected
// - 1.00 BETA 3 (21/02/2003) - Fixed bugs with seekoff()
// - 1.00 BETA 2 (23/12/2002) - Fixed a bug with izstream
// (Added m_ComMethod(-1) in constructor)
// - 1.00 BETA 1 (29/05/2002) - First public release
//
//////////////////////////////////////////////////////////////////////
#pragma once
#include "zstream_zlib.h" // Zlib dependencies
#ifdef PSP
#define USE_ZBUFFER_POOL
#endif
// Zip File System Namespace
namespace zip_file_system {
// Base buffer class
class zbuffer : public std::streambuf
{
public:
virtual ~zbuffer() { }
virtual zbuffer * open(const char * Filename, std::streamoff Offset, std::streamoff Size) = 0;
virtual zbuffer * close() = 0;
bool is_open() const { return m_Opened; }
bool is_used() const {return m_Used;}
void unuse() { m_Used = false;}
bool use(std::streamoff Offset, std::streamoff Size);
std::string getFilename() { return m_Filename; }
protected:
zbuffer() : m_Size(0), m_Opened(false), m_Used(false) { }
static const int BUFFERSIZE = 4092;
std::string m_Filename;
std::ifstream m_ZipFile;
std::streamoff m_Pos;
std::streamoff m_Size;
char m_Buffer[BUFFERSIZE];
bool m_Opened;
bool m_Used;
};
// Buffer class for stored compression method.
class zbuffer_stored : public zbuffer
{
public:
virtual ~zbuffer_stored() { close(); }
virtual zbuffer_stored * open(const char * Filename, std::streamoff Offset, std::streamoff Size);
virtual zbuffer_stored * close();
virtual int overflow(int c = EOF);
virtual int underflow();
virtual int sync();
using std::streambuf::setbuf;
virtual std::streambuf * setbuf(char * pr, int nLength);
virtual std::streampos seekoff(std::streamoff, std::ios::seekdir, std::ios::openmode);
// Default Implementation is enough
// virtual streampos seekpos(streampos, int);
};
// Buffer class for deflated compression method.
class zbuffer_deflated : public zbuffer
{
public:
virtual ~zbuffer_deflated() {
close();
}
virtual zbuffer_deflated * open(const char * Filename, std::streamoff Offset, std::streamoff Size);
virtual zbuffer_deflated * close();
virtual int overflow(int c = EOF);
virtual int underflow();
virtual int sync();
using std::streambuf::setbuf;
virtual std::streambuf * setbuf(char * pr, int nLength);
virtual std::streampos seekoff(std::streamoff, std::ios::seekdir, std::ios::openmode);
// Default Implementation is enough
// virtual streampos seekpos(streampos, int);
protected:
z_stream m_ZStream;
std::streamoff m_CompPos;
char m_CompBuffer[BUFFERSIZE];
bool m_StreamEnd;
};
// main istream class for reading zipped files
class izstream : public std::istream
{
public:
izstream() : std::istream(NULL), m_CompMethod(-1) { setstate(std::ios::badbit); }
virtual ~izstream() {
#ifdef USE_ZBUFFER_POOL
rdbuf(NULL); //This doesn't delete the buffer, deletion is handled by zfsystem;
#else
delete(rdbuf());
#endif
}
void open(const char * Filename, std::streamoff Offset, std::streamoff Size, int CompMethod);
void close() { SetCompMethod(-1); }
void _SetCompMethod(int CompMethod) { m_CompMethod = CompMethod; };
protected:
static const int STORED = 0;
static const int DEFLATED = 8;
zbuffer * GetRightBuffer(int CompMethod) const;
void SetCompMethod(int CompMethod) {
delete rdbuf(GetRightBuffer(m_CompMethod = CompMethod));
if (rdbuf() == NULL)
setstate(std::ios::badbit);
}
int m_CompMethod;
};
} // namespace zip_file_system;

View File

@@ -1,27 +0,0 @@
//////////////////////////////////////////////////////////////////////
//
// !!! IMPORTANT !!!
//
// You'll need to modify the following library and header paths to
// correctly link with ZLib.
//
//////////////////////////////////////////////////////////////////////
#pragma once
#include <zlib.h>
// Visual C++
/*
#if defined _MSC_VER
#if defined _DEBUG
#pragma comment(lib, "../JGE/Dependencies/lib/zlibd.lib")
#else
#pragma comment(lib, "../JGE/Dependencies/lib/zdll.lib")
#endif
#endif
*/