<commit_before>
/*
 * Copyright 2012 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "SkObjectParser.h"
#include "SkData.h"
#include "SkFontDescriptor.h"
#include "SkRRect.h"
#include "SkShader.h"
#include "SkStream.h"
#include "SkStringUtils.h"
#include "SkTypeface.h"
#include "SkUtils.h"

/* TODO(chudy): Replace all std::strings with char */

SkString* SkObjectParser::BitmapToString(const SkBitmap& bitmap) {
    SkString* mBitmap = new SkString("SkBitmap: ");
    mBitmap->append("W: ");
    mBitmap->appendS32(bitmap.width());
    mBitmap->append(" H: ");
    mBitmap->appendS32(bitmap.height());

    const char* gConfigStrings[] = {
        "None", "A1", "A8", "Index8", "RGB565", "ARGB4444", "ARGB8888"
    };
    SkASSERT(SkBitmap::kConfigCount == 7);

    mBitmap->append(" Config: ");
    mBitmap->append(gConfigStrings[bitmap.getConfig()]);

    if (bitmap.isOpaque()) {
        mBitmap->append(" opaque");
    } else {
        mBitmap->append(" not-opaque");
    }

    if (bitmap.isImmutable()) {
        mBitmap->append(" immutable");
    } else {
        mBitmap->append(" not-immutable");
    }

    if (bitmap.isVolatile()) {
        mBitmap->append(" volatile");
    } else {
        mBitmap->append(" not-volatile");
    }

    mBitmap->append(" genID: ");
    mBitmap->appendS32(bitmap.getGenerationID());

    return mBitmap;
}

SkString* SkObjectParser::BoolToString(bool doAA) {
    SkString* mBool = new SkString("Bool doAA: ");
    if (doAA) {
        mBool->append("True");
    } else {
        mBool->append("False");
    }
    return mBool;
}

SkString* SkObjectParser::CustomTextToString(const char* text) {
    SkString* mText = new SkString(text);
    return mText;
}

SkString* SkObjectParser::IntToString(int x, const char* text) {
    SkString* mInt = new SkString(text);
    mInt->append(" ");
    mInt->appendScalar(SkIntToScalar(x));
    return mInt;
}

SkString* SkObjectParser::IRectToString(const SkIRect& rect) {
    SkString* mRect = new SkString("SkIRect: ");
    mRect->append("L: ");
    mRect->appendS32(rect.left());
    mRect->append(", T: ");
    mRect->appendS32(rect.top());
    mRect->append(", R: ");
    mRect->appendS32(rect.right());
    mRect->append(", B: ");
    mRect->appendS32(rect.bottom());
    return mRect;
}

SkString* SkObjectParser::MatrixToString(const SkMatrix& matrix) {
    SkString* str = new SkString("SkMatrix: ");
#ifdef SK_DEVELOPER
    matrix.toString(str);
#endif
    return str;
}

SkString* SkObjectParser::PaintToString(const SkPaint& paint) {
    SkString* str = new SkString;
#ifdef SK_DEVELOPER
    paint.toString(str);
#endif
    return str;
}

SkString* SkObjectParser::PathToString(const SkPath& path) {
    SkString* mPath = new SkString("Path (");

    static const char* gFillStrings[] = {
        "Winding", "EvenOdd", "InverseWinding", "InverseEvenOdd"
    };

    mPath->append(gFillStrings[path.getFillType()]);
    mPath->append(", ");

    static const char* gConvexityStrings[] = {
        "Unknown", "Convex", "Concave"
    };
    SkASSERT(SkPath::kConcave_Convexity == 2);

    mPath->append(gConvexityStrings[path.getConvexity()]);
    mPath->append(", ");

    if (path.isRect(NULL)) {
        mPath->append("isRect, ");
    } else {
        mPath->append("isNotRect, ");
    }

    mPath->appendS32(path.countVerbs());
    mPath->append("V, ");
    mPath->appendS32(path.countPoints());
    mPath->append("P): ");

    static const char* gVerbStrings[] = {
        "Move", "Line", "Quad", "Conic", "Cubic", "Close", "Done"
    };
    static const int gPtsPerVerb[] = { 1, 1, 2, 2, 3, 0, 0 };
    static const int gPtOffsetPerVerb[] = { 0, 1, 1, 1, 1, 0, 0 };
    SkASSERT(SkPath::kDone_Verb == 6);

    SkPath::Iter iter(const_cast<SkPath&>(path), false);
    SkPath::Verb verb;
    SkPoint points[4];

    for(verb = iter.next(points, false);
        verb != SkPath::kDone_Verb;
        verb = iter.next(points, false)) {

        mPath->append(gVerbStrings[verb]);
        mPath->append(" ");

        for (int i = 0; i < gPtsPerVerb[verb]; ++i) {
            mPath->append("(");
            mPath->appendScalar(points[gPtOffsetPerVerb[verb]+i].fX);
            mPath->append(", ");
            mPath->appendScalar(points[gPtOffsetPerVerb[verb]+i].fY);
            mPath->append(")");
        }

        if (SkPath::kConic_Verb == verb) {
            mPath->append("(");
            mPath->appendScalar(iter.conicWeight());
            mPath->append(")");
        }

        mPath->append(" ");
    }

    SkString* boundStr = SkObjectParser::RectToString(path.getBounds(), "    Bound: ");

    if (NULL != boundStr) {
        mPath->append(*boundStr);
        SkDELETE(boundStr);
    }

    return mPath;
}

SkString* SkObjectParser::PointsToString(const SkPoint pts[], size_t count) {
    SkString* mPoints = new SkString("SkPoints pts[]: ");
    for (unsigned int i = 0; i < count; i++) {
        mPoints->append("(");
        mPoints->appendScalar(pts[i].fX);
        mPoints->append(",");
        mPoints->appendScalar(pts[i].fY);
        mPoints->append(")");
    }
    return mPoints;
}

SkString* SkObjectParser::PointModeToString(SkCanvas::PointMode mode) {
    SkString* mMode = new SkString("SkCanvas::PointMode: ");
    if (mode == SkCanvas::kPoints_PointMode) {
        mMode->append("kPoints_PointMode");
    } else if (mode == SkCanvas::kLines_PointMode) {
        mMode->append("kLines_Mode");
    } else if (mode == SkCanvas::kPolygon_PointMode) {
        mMode->append("kPolygon_PointMode");
    }
    return mMode;
}

SkString* SkObjectParser::RectToString(const SkRect& rect, const char* title) {

    SkString* mRect = new SkString;

    if (NULL == title) {
        mRect->append("SkRect: ");
    } else {
        mRect->append(title);
    }
    mRect->append("(");
    mRect->appendScalar(rect.left());
    mRect->append(", ");
    mRect->appendScalar(rect.top());
    mRect->append(", ");
    mRect->appendScalar(rect.right());
    mRect->append(", ");
    mRect->appendScalar(rect.bottom());
    mRect->append(")");
    return mRect;
}

SkString* SkObjectParser::RRectToString(const SkRRect& rrect, const char* title) {

    SkString* mRRect = new SkString;

    if (NULL == title) {
        mRRect->append("SkRRect (");
        if (rrect.isEmpty()) {
            mRRect->append("empty");
        } else if (rrect.isRect()) {
            mRRect->append("rect");
        } else if (rrect.isOval()) {
            mRRect->append("oval");
        } else if (rrect.isSimple()) {
            mRRect->append("simple");
        } else {
            SkASSERT(rrect.isComplex());
            mRRect->append("complex");
        }
        mRRect->append("): ");
    } else {
        mRRect->append(title);
    }
    mRRect->append("(");
    mRRect->appendScalar(rrect.rect().left());
    mRRect->append(", ");
    mRRect->appendScalar(rrect.rect().top());
    mRRect->append(", ");
    mRRect->appendScalar(rrect.rect().right());
    mRRect->append(", ");
    mRRect->appendScalar(rrect.rect().bottom());
    mRRect->append(") radii: (");
    for (int i = 0; i < 4; ++i) {
        const SkVector& radii = rrect.radii((SkRRect::Corner) i);
        mRRect->appendScalar(radii.fX);
        mRRect->append(", ");
        mRRect->appendScalar(radii.fY);
        if (i < 3) {
            mRRect->append(", ");
        }
    }
    mRRect->append(")");
    return mRRect;
}

SkString* SkObjectParser::RegionOpToString(SkRegion::Op op) {
    SkString* mOp = new SkString("SkRegion::Op: ");
    if (op == SkRegion::kDifference_Op) {
        mOp->append("kDifference_Op");
    } else if (op == SkRegion::kIntersect_Op) {
        mOp->append("kIntersect_Op");
    } else if (op == SkRegion::kUnion_Op) {
        mOp->append("kUnion_Op");
    } else if (op == SkRegion::kXOR_Op) {
        mOp->append("kXOR_Op");
    } else if (op == SkRegion::kReverseDifference_Op) {
        mOp->append("kReverseDifference_Op");
    } else if (op == SkRegion::kReplace_Op) {
        mOp->append("kReplace_Op");
    } else {
        mOp->append("Unknown Type");
    }
    return mOp;
}

SkString* SkObjectParser::RegionToString(const SkRegion& region) {
    SkString* mRegion = new SkString("SkRegion: Data unavailable.");
    return mRegion;
}

SkString* SkObjectParser::SaveFlagsToString(SkCanvas::SaveFlags flags) {
    SkString* mFlags = new SkString("SkCanvas::SaveFlags: ");
    if(flags == SkCanvas::kMatrixClip_SaveFlag) {
        mFlags->append("kMatrixClip_SaveFlag");
    } else if (flags == SkCanvas::kClip_SaveFlag) {
        mFlags->append("kClip_SaveFlag");
    } else if (flags == SkCanvas::kHasAlphaLayer_SaveFlag) {
        mFlags->append("kHasAlphaLayer_SaveFlag");
    } else if (flags == SkCanvas::kFullColorLayer_SaveFlag) {
        mFlags->append("kFullColorLayer_SaveFlag");
    } else if (flags == SkCanvas::kClipToLayer_SaveFlag) {
        mFlags->append("kClipToLayer_SaveFlag");
    } else if (flags == SkCanvas::kMatrixClip_SaveFlag) {
        mFlags->append("kMatrixClip_SaveFlag");
    } else if (flags == SkCanvas::kARGB_NoClipLayer_SaveFlag) {
        mFlags->append("kARGB_NoClipLayer_SaveFlag");
    } else if (flags == SkCanvas::kARGB_ClipLayer_SaveFlag) {
        mFlags->append("kARGB_ClipLayer_SaveFlag");
    } else {
        mFlags->append("Data Unavailable");
    }
    return mFlags;
}

SkString* SkObjectParser::ScalarToString(SkScalar x, const char* text) {
    SkString* mScalar = new SkString(text);
    mScalar->append(" ");
    mScalar->appendScalar(x);
    return mScalar;
}

SkString* SkObjectParser::TextToString(const void* text, size_t byteLength,
                                       SkPaint::TextEncoding encoding) {

    SkString* decodedText = new SkString();
    switch (encoding) {
        case SkPaint::kUTF8_TextEncoding: {
            decodedText->append("UTF-8: ");
            decodedText->append((const char*)text, byteLength);
            break;
        }
        case SkPaint::kUTF16_TextEncoding: {
            decodedText->append("UTF-16: ");
            size_t sizeNeeded = SkUTF16_ToUTF8((uint16_t*)text, byteLength / 2, NULL);
            char* utf8 = new char[sizeNeeded];
            SkUTF16_ToUTF8((uint16_t*)text, byteLength / 2, utf8);
            decodedText->append(utf8, sizeNeeded);
            delete utf8;
            break;
        }
        case SkPaint::kUTF32_TextEncoding: {
            decodedText->append("UTF-32: ");
            const SkUnichar* begin = (const SkUnichar*)text;
            const SkUnichar* end = (const SkUnichar*)((const char*)text + byteLength);
            for (const SkUnichar* unichar = begin; unichar < end; ++unichar) {
                decodedText->appendUnichar(*unichar);
            }
            break;
        }
        case SkPaint::kGlyphID_TextEncoding: {
            decodedText->append("GlyphID: ");
            const uint16_t* begin = (const uint16_t*)text;
            const uint16_t* end = (const uint16_t*)((const char*)text + byteLength);
            for (const uint16_t* glyph = begin; glyph < end; ++glyph) {
                decodedText->append("0x");
                decodedText->appendHex(*glyph);
                decodedText->append(" ");
            }
            break;
        }
        default:
            decodedText->append("Unknown text encoding.");
            break;
    }

    return decodedText;
}
<commit_msg>SkObjectParser::SaveFlagsToString() should handle SaveFlags as a bitmask.<commit_after>
/*
 * Copyright 2012 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "SkObjectParser.h"
#include "SkData.h"
#include "SkFontDescriptor.h"
#include "SkRRect.h"
#include "SkShader.h"
#include "SkStream.h"
#include "SkStringUtils.h"
#include "SkTypeface.h"
#include "SkUtils.h"

/* TODO(chudy): Replace all std::strings with char */

SkString* SkObjectParser::BitmapToString(const SkBitmap& bitmap) {
    SkString* mBitmap = new SkString("SkBitmap: ");
    mBitmap->append("W: ");
    mBitmap->appendS32(bitmap.width());
    mBitmap->append(" H: ");
    mBitmap->appendS32(bitmap.height());

    const char* gConfigStrings[] = {
        "None", "A1", "A8", "Index8", "RGB565", "ARGB4444", "ARGB8888"
    };
    SkASSERT(SkBitmap::kConfigCount == 7);

    mBitmap->append(" Config: ");
    mBitmap->append(gConfigStrings[bitmap.getConfig()]);

    if (bitmap.isOpaque()) {
        mBitmap->append(" opaque");
    } else {
        mBitmap->append(" not-opaque");
    }

    if (bitmap.isImmutable()) {
        mBitmap->append(" immutable");
    } else {
        mBitmap->append(" not-immutable");
    }

    if (bitmap.isVolatile()) {
        mBitmap->append(" volatile");
    } else {
        mBitmap->append(" not-volatile");
    }

    mBitmap->append(" genID: ");
    mBitmap->appendS32(bitmap.getGenerationID());

    return mBitmap;
}

SkString* SkObjectParser::BoolToString(bool doAA) {
    SkString* mBool = new SkString("Bool doAA: ");
    if (doAA) {
        mBool->append("True");
    } else {
        mBool->append("False");
    }
    return mBool;
}

SkString* SkObjectParser::CustomTextToString(const char* text) {
    SkString* mText = new SkString(text);
    return mText;
}

SkString* SkObjectParser::IntToString(int x, const char* text) {
    SkString* mInt = new SkString(text);
    mInt->append(" ");
    mInt->appendScalar(SkIntToScalar(x));
    return mInt;
}

SkString* SkObjectParser::IRectToString(const SkIRect& rect) {
    SkString* mRect = new SkString("SkIRect: ");
    mRect->append("L: ");
    mRect->appendS32(rect.left());
    mRect->append(", T: ");
    mRect->appendS32(rect.top());
    mRect->append(", R: ");
    mRect->appendS32(rect.right());
    mRect->append(", B: ");
    mRect->appendS32(rect.bottom());
    return mRect;
}

SkString* SkObjectParser::MatrixToString(const SkMatrix& matrix) {
    SkString* str = new SkString("SkMatrix: ");
#ifdef SK_DEVELOPER
    matrix.toString(str);
#endif
    return str;
}

SkString* SkObjectParser::PaintToString(const SkPaint& paint) {
    SkString* str = new SkString;
#ifdef SK_DEVELOPER
    paint.toString(str);
#endif
    return str;
}

SkString* SkObjectParser::PathToString(const SkPath& path) {
    SkString* mPath = new SkString("Path (");

    static const char* gFillStrings[] = {
        "Winding", "EvenOdd", "InverseWinding", "InverseEvenOdd"
    };

    mPath->append(gFillStrings[path.getFillType()]);
    mPath->append(", ");

    static const char* gConvexityStrings[] = {
        "Unknown", "Convex", "Concave"
    };
    SkASSERT(SkPath::kConcave_Convexity == 2);

    mPath->append(gConvexityStrings[path.getConvexity()]);
    mPath->append(", ");

    if (path.isRect(NULL)) {
        mPath->append("isRect, ");
    } else {
        mPath->append("isNotRect, ");
    }

    mPath->appendS32(path.countVerbs());
    mPath->append("V, ");
    mPath->appendS32(path.countPoints());
    mPath->append("P): ");

    static const char* gVerbStrings[] = {
        "Move", "Line", "Quad", "Conic", "Cubic", "Close", "Done"
    };
    static const int gPtsPerVerb[] = { 1, 1, 2, 2, 3, 0, 0 };
    static const int gPtOffsetPerVerb[] = { 0, 1, 1, 1, 1, 0, 0 };
    SkASSERT(SkPath::kDone_Verb == 6);

    SkPath::Iter iter(const_cast<SkPath&>(path), false);
    SkPath::Verb verb;
    SkPoint points[4];

    for(verb = iter.next(points, false);
        verb != SkPath::kDone_Verb;
        verb = iter.next(points, false)) {

        mPath->append(gVerbStrings[verb]);
        mPath->append(" ");

        for (int i = 0; i < gPtsPerVerb[verb]; ++i) {
            mPath->append("(");
            mPath->appendScalar(points[gPtOffsetPerVerb[verb]+i].fX);
            mPath->append(", ");
            mPath->appendScalar(points[gPtOffsetPerVerb[verb]+i].fY);
            mPath->append(")");
        }

        if (SkPath::kConic_Verb == verb) {
            mPath->append("(");
            mPath->appendScalar(iter.conicWeight());
            mPath->append(")");
        }

        mPath->append(" ");
    }

    SkString* boundStr = SkObjectParser::RectToString(path.getBounds(), "    Bound: ");

    if (NULL != boundStr) {
        mPath->append(*boundStr);
        SkDELETE(boundStr);
    }

    return mPath;
}

SkString* SkObjectParser::PointsToString(const SkPoint pts[], size_t count) {
    SkString* mPoints = new SkString("SkPoints pts[]: ");
    for (unsigned int i = 0; i < count; i++) {
        mPoints->append("(");
        mPoints->appendScalar(pts[i].fX);
        mPoints->append(",");
        mPoints->appendScalar(pts[i].fY);
        mPoints->append(")");
    }
    return mPoints;
}

SkString* SkObjectParser::PointModeToString(SkCanvas::PointMode mode) {
    SkString* mMode = new SkString("SkCanvas::PointMode: ");
    if (mode == SkCanvas::kPoints_PointMode) {
        mMode->append("kPoints_PointMode");
    } else if (mode == SkCanvas::kLines_PointMode) {
        mMode->append("kLines_Mode");
    } else if (mode == SkCanvas::kPolygon_PointMode) {
        mMode->append("kPolygon_PointMode");
    }
    return mMode;
}

SkString* SkObjectParser::RectToString(const SkRect& rect, const char* title) {

    SkString* mRect = new SkString;

    if (NULL == title) {
        mRect->append("SkRect: ");
    } else {
        mRect->append(title);
    }
    mRect->append("(");
    mRect->appendScalar(rect.left());
    mRect->append(", ");
    mRect->appendScalar(rect.top());
    mRect->append(", ");
    mRect->appendScalar(rect.right());
    mRect->append(", ");
    mRect->appendScalar(rect.bottom());
    mRect->append(")");
    return mRect;
}

SkString* SkObjectParser::RRectToString(const SkRRect& rrect, const char* title) {

    SkString* mRRect = new SkString;

    if (NULL == title) {
        mRRect->append("SkRRect (");
        if (rrect.isEmpty()) {
            mRRect->append("empty");
        } else if (rrect.isRect()) {
            mRRect->append("rect");
        } else if (rrect.isOval()) {
            mRRect->append("oval");
        } else if (rrect.isSimple()) {
            mRRect->append("simple");
        } else {
            SkASSERT(rrect.isComplex());
            mRRect->append("complex");
        }
        mRRect->append("): ");
    } else {
        mRRect->append(title);
    }
    mRRect->append("(");
    mRRect->appendScalar(rrect.rect().left());
    mRRect->append(", ");
    mRRect->appendScalar(rrect.rect().top());
    mRRect->append(", ");
    mRRect->appendScalar(rrect.rect().right());
    mRRect->append(", ");
    mRRect->appendScalar(rrect.rect().bottom());
    mRRect->append(") radii: (");
    for (int i = 0; i < 4; ++i) {
        const SkVector& radii = rrect.radii((SkRRect::Corner) i);
        mRRect->appendScalar(radii.fX);
        mRRect->append(", ");
        mRRect->appendScalar(radii.fY);
        if (i < 3) {
            mRRect->append(", ");
        }
    }
    mRRect->append(")");
    return mRRect;
}

SkString* SkObjectParser::RegionOpToString(SkRegion::Op op) {
    SkString* mOp = new SkString("SkRegion::Op: ");
    if (op == SkRegion::kDifference_Op) {
        mOp->append("kDifference_Op");
    } else if (op == SkRegion::kIntersect_Op) {
        mOp->append("kIntersect_Op");
    } else if (op == SkRegion::kUnion_Op) {
        mOp->append("kUnion_Op");
    } else if (op == SkRegion::kXOR_Op) {
        mOp->append("kXOR_Op");
    } else if (op == SkRegion::kReverseDifference_Op) {
        mOp->append("kReverseDifference_Op");
    } else if (op == SkRegion::kReplace_Op) {
        mOp->append("kReplace_Op");
    } else {
        mOp->append("Unknown Type");
    }
    return mOp;
}

SkString* SkObjectParser::RegionToString(const SkRegion& region) {
    SkString* mRegion = new SkString("SkRegion: Data unavailable.");
    return mRegion;
}

SkString* SkObjectParser::SaveFlagsToString(SkCanvas::SaveFlags flags) {
    SkString* mFlags = new SkString("SkCanvas::SaveFlags: ");
    if (flags & SkCanvas::kMatrix_SaveFlag) {
        mFlags->append("kMatrix_SaveFlag ");
    }
    if (flags & SkCanvas::kClip_SaveFlag) {
        mFlags->append("kClip_SaveFlag ");
    }
    if (flags & SkCanvas::kHasAlphaLayer_SaveFlag) {
        mFlags->append("kHasAlphaLayer_SaveFlag ");
    }
    if (flags & SkCanvas::kFullColorLayer_SaveFlag) {
        mFlags->append("kFullColorLayer_SaveFlag ");
    }
    if (flags & SkCanvas::kClipToLayer_SaveFlag) {
        mFlags->append("kClipToLayer_SaveFlag ");
    }
    return mFlags;
}

SkString* SkObjectParser::ScalarToString(SkScalar x, const char* text) {
    SkString* mScalar = new SkString(text);
    mScalar->append(" ");
    mScalar->appendScalar(x);
    return mScalar;
}

SkString* SkObjectParser::TextToString(const void* text, size_t byteLength,
                                       SkPaint::TextEncoding encoding) {

    SkString* decodedText = new SkString();
    switch (encoding) {
        case SkPaint::kUTF8_TextEncoding: {
            decodedText->append("UTF-8: ");
            decodedText->append((const char*)text, byteLength);
            break;
        }
        case SkPaint::kUTF16_TextEncoding: {
            decodedText->append("UTF-16: ");
            size_t sizeNeeded = SkUTF16_ToUTF8((uint16_t*)text, byteLength / 2, NULL);
            char* utf8 = new char[sizeNeeded];
            SkUTF16_ToUTF8((uint16_t*)text, byteLength / 2, utf8);
            decodedText->append(utf8, sizeNeeded);
            delete utf8;
            break;
        }
        case SkPaint::kUTF32_TextEncoding: {
            decodedText->append("UTF-32: ");
            const SkUnichar* begin = (const SkUnichar*)text;
            const SkUnichar* end = (const SkUnichar*)((const char*)text + byteLength);
            for (const SkUnichar* unichar = begin; unichar < end; ++unichar) {
                decodedText->appendUnichar(*unichar);
            }
            break;
        }
        case SkPaint::kGlyphID_TextEncoding: {
            decodedText->append("GlyphID: ");
            const uint16_t* begin = (const uint16_t*)text;
            const uint16_t* end = (const uint16_t*)((const char*)text + byteLength);
            for (const uint16_t* glyph = begin; glyph < end; ++glyph) {
                decodedText->append("0x");
                decodedText->appendHex(*glyph);
                decodedText->append(" ");
            }
            break;
        }
        default:
            decodedText->append("Unknown text encoding.");
            break;
    }

    return decodedText;
}
<|endoftext|>


<commit_before>#include <ncurses.h>
#include <string>
#include <vector>

#include "configuration.hh"
#include "newmove.hh"

static contents* cont;

void init(std::vector<std::string>* vec) {
    cont = new contents(vec);
    print_contents(cont);
}

contents* get_contents() { return cont; }

void print_contents(const contents* contents) {
    clear();
    int b_y,b_x,
        y = 0;
    getyx(stdscr,b_y,b_x);

    for(unsigned int i = contents->y_offset;
        i < contents->cont->size()
            && i < contents->max_y - 1 + contents->y_offset; i++) {
        unsigned int x = 0;
        std::string line = (*contents->cont)[i];
        int til = 0;
        for(unsigned int i = 0; i < line.length(); i++) {
            if(line[i] == '\t') {
                x += TAB_SIZE - til - 1;
                if(x >= contents->max_x) {
                    x = 0;
                    y++;
                }
                move(y,x);
                til = 0;
            } else {
                addch(line[i]);
                til++;
                til %= TAB_SIZE;
            }
            x++;
            if(x-1 == contents->max_x) {
                addch('\\');
                x = 0;
                ++y;
            }
            move(y,x);
        }
        move(++y,0);
    }
    move(contents->y,to_visual((*contents->cont)[contents->y],contents->x));
}
<commit_msg>``refresh'' doesn't die if given empty file<commit_after>#include <ncurses.h>
#include <string>
#include <vector>

#include "configuration.hh"
#include "newmove.hh"

static contents* cont;

void init(std::vector<std::string>* vec) {
    cont = new contents(vec);
    print_contents(cont);
}

contents* get_contents() { return cont; }

void print_contents(const contents* contents) {
    clear();
    if(contents->cont->size() == 0) return;
    int b_y,b_x,
        y = 0;
    getyx(stdscr,b_y,b_x);

    for(unsigned int i = contents->y_offset;
        i < contents->cont->size()
            && i < contents->max_y - 1 + contents->y_offset; i++) {
        unsigned int x = 0;
        std::string line = (*contents->cont)[i];
        int til = 0;
        for(unsigned int i = 0; i < line.length(); i++) {
            if(line[i] == '\t') {
                x += TAB_SIZE - til - 1;
                if(x >= contents->max_x) {
                    x = 0;
                    y++;
                }
                move(y,x);
                til = 0;
            } else {
                addch(line[i]);
                til++;
                til %= TAB_SIZE;
            }
            x++;
            if(x-1 == contents->max_x) {
                addch('\\');
                x = 0;
                ++y;
            }
            move(y,x);
        }
        move(++y,0);
    }
    move(contents->y,to_visual((*contents->cont)[contents->y],contents->x));
}
<|endoftext|>


<commit_before>// ======================================================================== //
// Copyright 2009-2016 Intel Corporation                                    //
//                                                                          //
// Licensed under the Apache License, Version 2.0 (the "License");          //
// you may not use this file except in compliance with the License.         //
// You may obtain a copy of the License at                                  //
//                                                                          //
//     http://www.apache.org/licenses/LICENSE-2.0                           //
//                                                                          //
// Unless required by applicable law or agreed to in writing, software      //
// distributed under the License is distributed on an "AS IS" BASIS,        //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and      //
// limitations under the License.                                           //
// ======================================================================== //

/*! \file apps/particleViewer/viewer.cpp
  \brief A GLUT-based viewer for simple particle data */

// viewer widget
#include "apps/common/widgets/glut3D.h"
// ospray, for rendering
#include "ospray/ospray.h"
// particle viewer
#include "Model.h"
#include "uintah.h"
// embree
#include "sys/filename.h"

namespace ospray {
  namespace particle {

    using std::cout;
    using std::endl;

    bool showFPS = false;
    int maxAccum = 64;
    int accumID = 0;
    int timeStep = 0;
    std::vector<OSPModel> modelTimeStep;

    std::string modelSaveFileName = "";
    OSPRenderer        ospRenderer = NULL;
    typedef enum { LAMMPS_XYZ, DAT_XYZ } InputFormat;

    /*! when using the OBJ renderer, we create a automatic dirlight with this direction; use ''--sun-dir x y z' to change */
    //  vec3f defaultDirLight_direction(-.3, -1, .4);
    vec3f defaultDirLight_direction(.3, -1, -.2);

    //! the renderer we're about to use
    std::string rendererType = "ao1";
    //    std::string rendererType = "raycast_eyelight";
    // float defaultRadius = 1.f;
    InputFormat inputFormat = LAMMPS_XYZ;
    void error(const std::string &err)
    {
      cout << "#osp::ospParticleViewer fatal error : " << err << endl;
      cout << endl;
      cout << "Proper usage: " << endl;
      cout << "  ./ospParticleViewer <inFileName[.xyz|.xml]>" << endl;
      cout << endl;
      exit(1);
    }

    using ospray::glut3D::Glut3DWidget;

    /*! mini scene graph viewer widget. \internal Note that all handling
      of camera is almost exactly similar to the code in volView;
      might make sense to move that into a common class! */
    struct ParticleViewer : public Glut3DWidget {
      ParticleViewer(OSPModel model, OSPRenderer renderer)
        : Glut3DWidget(Glut3DWidget::FRAMEBUFFER_NONE),
          fb(NULL), renderer(renderer), model(model)
      {
        Assert(model && "null model handle");
        camera = ospNewCamera("perspective");
        Assert(camera != NULL && "could not create camera");
        ospSet3f(camera,"pos",-1,1,-1);
        ospSet3f(camera,"dir",+1,-1,+1);
        ospCommit(camera);

        ospSetObject(renderer,"model",model);
        ospSetObject(renderer,"camera",camera);
        ospCommit(camera);
        ospCommit(renderer);
      };

      virtual void reshape(const ospray::vec2i &_newSize)
      {
        Glut3DWidget::reshape(_newSize);
        if (fb) ospFreeFrameBuffer(fb);
        const auto &newSize = reinterpret_cast<const osp::vec2i&>(_newSize);
        fb = ospNewFrameBuffer(newSize,OSP_RGBA_I8,OSP_FB_COLOR|OSP_FB_ACCUM);
        ospSet1f(fb, "gamma", 2.2f);
        ospCommit(fb);
        ospFrameBufferClear(fb,OSP_FB_ACCUM);
        accumID = 0;
        ospSetf(camera,"aspect",viewPort.aspect);
        ospCommit(camera);

        setTitle("OSPRay Particle Viewer");
      }

      virtual void keypress(char key, const vec2f where)
      {
        switch(key) {
        case 'Q': exit(0);
        case '>': {
          timeStep = (timeStep+1)%modelTimeStep.size();
          model = modelTimeStep[timeStep];
          ospSetObject(renderer,"model",model);
          PRINT(timeStep);
          PRINT(model);
          ospCommit(renderer);
          viewPort.modified = true;
          forceRedraw();
        } break;
        case '<': {
          timeStep = (timeStep+modelTimeStep.size()-1)%modelTimeStep.size();
          model = modelTimeStep[timeStep];
          PRINT(timeStep);
          PRINT(model);
          ospSetObject(renderer,"model",model);
          ospCommit(renderer);
          viewPort.modified = true;
          forceRedraw();
        } break;
        default:
          Glut3DWidget::keypress(key,where);
        }
      }

      virtual void display()
      {
        if (!fb || !renderer) return;

        static int frameID = 0;

        //{
        // note that the order of 'start' and 'end' here is
        // (intentionally) reversed: due to our asynchrounous rendering
        // you cannot place start() and end() _around_ the renderframe
        // call (which in itself will not do a lot other than triggering
        // work), but the average time between ttwo calls is roughly the
        // frame rate (including display overhead, of course)
        if (frameID > 0) fps.doneRender();
        fps.startRender();
        //}
        ++frameID;

        if (viewPort.modified) {
          Assert2(camera,"ospray camera is null");
          auto from = reinterpret_cast<osp::vec3f&>(viewPort.from);
          auto dir  = viewPort.at-viewPort.from;
          auto up   = reinterpret_cast<osp::vec3f&>(viewPort.up);
          ospSetVec3f(camera,"pos",from);
          ospSetVec3f(camera,"dir",reinterpret_cast<osp::vec3f&>(dir));
          ospSetVec3f(camera,"up",up);
          ospSetf(camera,"aspect",viewPort.aspect);
          ospCommit(camera);
          ospFrameBufferClear(fb,OSP_FB_ACCUM);
          viewPort.modified = false;
          accumID = 0;
        }

        ospRenderFrame(fb,renderer,OSP_FB_COLOR|OSP_FB_ACCUM);
        ++accumID;
        if (accumID < maxAccum)
          forceRedraw();

        ucharFB = (uint32 *) ospMapFrameBuffer(fb);
        frameBufferMode = Glut3DWidget::FRAMEBUFFER_UCHAR;
        Glut3DWidget::display();

        ospUnmapFrameBuffer(ucharFB,fb);

        if (showFPS) {
          char title[1000];

          sprintf(title,"OSPRay Particle Viewer (%f fps)",fps.getFPS());
          setTitle(title);
        }
      }

      OSPModel       model;
      OSPFrameBuffer fb;
      OSPRenderer    renderer;
      OSPCamera      camera;
      ospray::glut3D::FPSCounter fps;
    };

    particle::Model *createTestCube(int numPerSide)
    {
      particle::Model *m = new particle::Model;
      int type = m->getAtomType("testParticle");
      for (int z=0;z<numPerSide;z++)
        for (int y=0;y<numPerSide;y++)
          for (int x=0;x<numPerSide;x++) {
            particle::Model::Atom a;
            a.position.x = x/float(numPerSide);
            a.position.y = y/float(numPerSide);
            a.position.z = z/float(numPerSide);
            a.type = type;
            a.radius = 1.f/numPerSide;
            m->atom.push_back(a);
          }
      return m;
    }

    OSPData makeMaterials(OSPRenderer renderer,particle::Model *model)
    {
      int numMaterials = model->atomType.size();
      OSPMaterial matArray[numMaterials];
      for (int i=0;i<numMaterials;i++) {
        OSPMaterial mat = ospNewMaterial(renderer,"OBJMaterial");
        assert(mat);
        ospSet3fv(mat,"kd",&model->atomType[i]->color.x);
        ospCommit(mat);
        matArray[i] = mat;
      }
      OSPData data = ospNewData(numMaterials,OSP_OBJECT,matArray);
      ospCommit(data);
      return data;
    }

    struct DeferredLoadJob {
      DeferredLoadJob(particle::Model *model,
                      const embree::FileName &xyzFileName,
                      const embree::FileName &defFileName)
        : model(model), xyzFileName(xyzFileName), defFileName(defFileName)
      {}

      //! the mode we still have to load
      particle::Model *model;
      //! file name of xyz file to be loaded into this model
      embree::FileName xyzFileName;
      //! name of atom type defintion file active when this xyz file was added
      embree::FileName defFileName;
    };

    void ospParticleViewerMain(int &ac, const char **&av)
    {
      std::vector<Model *> particleModel;

      cout << "ospParticleViewer: starting to process cmdline arguments" << endl;
      std::vector<DeferredLoadJob *> deferredLoadingListXYZ;
      embree::FileName defFileName = "";

      for (int i=1;i<ac;i++) {
        const std::string arg = av[i];
        if (arg == "--renderer") {
          assert(i+1 < ac);
          rendererType = av[++i];
        } else if (arg == "--radius") {
          Model::defaultRadius = atof(av[++i]);
        } else if (arg == "--sun-dir") {
          defaultDirLight_direction.x = atof(av[++i]);
          defaultDirLight_direction.y = atof(av[++i]);
          defaultDirLight_direction.z = atof(av[++i]);
        } else if (arg == "--module" || arg == "--plugin") {
          assert(i+1 < ac);
          const char *moduleName = av[++i];
          cout << "loading ospray module '" << moduleName << "'" << endl;
          ospLoadModule(moduleName);
        } else if (arg == "--show-fps" || arg == "-fps") {
          showFPS = true;
        } else if (arg == "--save-to") {
          modelSaveFileName = av[++i];
        } else if (arg == "--atom-defs") {
          defFileName = av[++i];
        } else if (av[i][0] == '-') {
          error("unkown commandline argument '"+arg+"'");
        } else {
          embree::FileName fn = arg;
          if (fn.str() == "___CUBE_TEST___") {
            int numPerSide = atoi(av[++i]);
            particle::Model *m = createTestCube(numPerSide);
            particleModel.push_back(m);
          } else if (fn.ext() == "xyz") {
            particle::Model *m = new particle::Model;
            //            m->loadXYZ(fn);
            // std::pair<particle::Model *, embree::FileName> loadJob(m,fn.str());
            deferredLoadingListXYZ.push_back(new DeferredLoadJob(m,fn,defFileName));
            particleModel.push_back(m);
          } else if (fn.ext() == "xyz2") {
            particle::Model *m = new particle::Model;
            m->loadXYZ2(fn);
            particleModel.push_back(m);
          } else if (fn.ext() == "xml") {
            particle::Model *m = parse__Uintah_timestep_xml(fn);
            particleModel.push_back(m);
          } else
            error("unknown file format "+fn.str());
        }
      }
      if (particleModel.empty())
        error("no input file specified");

#pragma omp parallel for
      for (int i=0;i<deferredLoadingListXYZ.size();i++) {
        embree::FileName defFileName = deferredLoadingListXYZ[i]->defFileName;
        embree::FileName xyzFileName = deferredLoadingListXYZ[i]->xyzFileName;
        particle::Model *model = deferredLoadingListXYZ[i]->model;

        if (defFileName.str() != "")
          model->readAtomTypeDefinitions(defFileName);
        model->loadXYZ(xyzFileName);
      }

      // -------------------------------------------------------
      // done parsings
      // -------------------------------------------------------]
      cout << "ospParticleViewer: done parsing. found model with" << endl;
      cout << "  - num atoms: " << particleModel[0]->atom.size() << endl;
      if (modelSaveFileName != "") {
        particleModel[0]->saveToFile(modelSaveFileName);
        exit(0);
      }

      // -------------------------------------------------------
      // create ospray model
      // -------------------------------------------------------
      ospRenderer = ospNewRenderer(rendererType.c_str());
      if (!ospRenderer)
        error("could not create ospRenderer '"+rendererType+"'");
      Assert(ospRenderer != NULL && "could not create ospRenderer");

      for (int i=0;i<particleModel.size();i++) {
        OSPModel model = ospNewModel();
        OSPData materialData = makeMaterials(ospRenderer,particleModel[i]);

        OSPData data = ospNewData(particleModel[i]->atom.size()*5,OSP_FLOAT,
                                  &particleModel[i]->atom[0],OSP_DATA_SHARED_BUFFER);
        ospCommit(data);

        OSPGeometry geom = ospNewGeometry("spheres");
        ospSet1i(geom,"bytes_per_sphere",sizeof(Model::Atom));
        ospSet1i(geom,"offset_center",0);
        ospSet1i(geom,"offset_radius",3*sizeof(float));
        ospSet1i(geom,"offset_materialID",4*sizeof(float));
        ospSetData(geom,"spheres",data);
        ospSetData(geom,"materialList",materialData);
        ospCommit(geom);

        ospAddGeometry(model,geom);
        ospCommit(model);

        modelTimeStep.push_back(model);
      }

      OSPModel model = modelTimeStep[timeStep];

      std::vector<OSPLight> dirLights;
      cout << "msgView: Adding a hard coded directional light as the sun." << endl;
      OSPLight ospLight = ospNewLight(ospRenderer, "DirectionalLight");
      ospSetString(ospLight, "name", "sun" );
      ospSet3f(ospLight, "color", 1, 1, 1);
      ospSet3fv(ospLight, "direction", &defaultDirLight_direction.x);
      ospCommit(ospLight);
      dirLights.push_back(ospLight);
      OSPData dirLightArray = ospNewData(dirLights.size(), OSP_OBJECT, &dirLights[0], 0);
      ospSetData(ospRenderer, "directionalLights", dirLightArray);

      ospCommit(ospRenderer);

      cout << "ospParticleViewer: done creating ospray model." << endl;

      // -------------------------------------------------------
      // create viewer window
      // -------------------------------------------------------
      ParticleViewer window(model,ospRenderer);
      window.create("ospray particle viewer");
      printf("OSPRay Particle Viewer created. Press 'Q' to quit.\n");
      box3f wb(particleModel[0]->getBBox());
      PRINT(wb);
      window.setWorldBounds(wb);
      ospray::glut3D::runGLUT();
    }

  } // ::ospray::particle
} // ::ospray

int main(int ac, const char **av)
{
  ospInit(&ac,av);
  ospray::glut3D::initGLUT(&ac,av);
  ospray::particle::ospParticleViewerMain(ac,av);
}
<commit_msg>switch to using ospray::parallel_for in particleViewer app<commit_after>// ======================================================================== //
// Copyright 2009-2016 Intel Corporation                                    //
//                                                                          //
// Licensed under the Apache License, Version 2.0 (the "License");          //
// you may not use this file except in compliance with the License.         //
// You may obtain a copy of the License at                                  //
//                                                                          //
//     http://www.apache.org/licenses/LICENSE-2.0                           //
//                                                                          //
// Unless required by applicable law or agreed to in writing, software      //
// distributed under the License is distributed on an "AS IS" BASIS,        //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and      //
// limitations under the License.                                           //
// ======================================================================== //

/*! \file apps/particleViewer/viewer.cpp
  \brief A GLUT-based viewer for simple particle data */

// viewer widget
#include "apps/common/widgets/glut3D.h"
// ospray, for rendering
#include "ospray/ospray.h"
#include "common/parallel_for.h"
// particle viewer
#include "Model.h"
#include "uintah.h"
// embree
#include "sys/filename.h"

namespace ospray {
  namespace particle {

    using std::cout;
    using std::endl;

    bool showFPS = false;
    int maxAccum = 64;
    int accumID = 0;
    int timeStep = 0;
    std::vector<OSPModel> modelTimeStep;

    std::string modelSaveFileName = "";
    OSPRenderer        ospRenderer = NULL;
    typedef enum { LAMMPS_XYZ, DAT_XYZ } InputFormat;

    /*! when using the OBJ renderer, we create a automatic dirlight with this direction; use ''--sun-dir x y z' to change */
    //  vec3f defaultDirLight_direction(-.3, -1, .4);
    vec3f defaultDirLight_direction(.3, -1, -.2);

    //! the renderer we're about to use
    std::string rendererType = "ao1";
    //    std::string rendererType = "raycast_eyelight";
    // float defaultRadius = 1.f;
    InputFormat inputFormat = LAMMPS_XYZ;
    void error(const std::string &err)
    {
      cout << "#osp::ospParticleViewer fatal error : " << err << endl;
      cout << endl;
      cout << "Proper usage: " << endl;
      cout << "  ./ospParticleViewer <inFileName[.xyz|.xml]>" << endl;
      cout << endl;
      exit(1);
    }

    using ospray::glut3D::Glut3DWidget;

    /*! mini scene graph viewer widget. \internal Note that all handling
      of camera is almost exactly similar to the code in volView;
      might make sense to move that into a common class! */
    struct ParticleViewer : public Glut3DWidget {
      ParticleViewer(OSPModel model, OSPRenderer renderer)
        : Glut3DWidget(Glut3DWidget::FRAMEBUFFER_NONE),
          fb(NULL), renderer(renderer), model(model)
      {
        Assert(model && "null model handle");
        camera = ospNewCamera("perspective");
        Assert(camera != NULL && "could not create camera");
        ospSet3f(camera,"pos",-1,1,-1);
        ospSet3f(camera,"dir",+1,-1,+1);
        ospCommit(camera);

        ospSetObject(renderer,"model",model);
        ospSetObject(renderer,"camera",camera);
        ospCommit(camera);
        ospCommit(renderer);
      };

      virtual void reshape(const ospray::vec2i &_newSize)
      {
        Glut3DWidget::reshape(_newSize);
        if (fb) ospFreeFrameBuffer(fb);
        const auto &newSize = reinterpret_cast<const osp::vec2i&>(_newSize);
        fb = ospNewFrameBuffer(newSize,OSP_RGBA_I8,OSP_FB_COLOR|OSP_FB_ACCUM);
        ospSet1f(fb, "gamma", 2.2f);
        ospCommit(fb);
        ospFrameBufferClear(fb,OSP_FB_ACCUM);
        accumID = 0;
        ospSetf(camera,"aspect",viewPort.aspect);
        ospCommit(camera);

        setTitle("OSPRay Particle Viewer");
      }

      virtual void keypress(char key, const vec2f where)
      {
        switch(key) {
        case 'Q': exit(0);
        case '>': {
          timeStep = (timeStep+1)%modelTimeStep.size();
          model = modelTimeStep[timeStep];
          ospSetObject(renderer,"model",model);
          PRINT(timeStep);
          PRINT(model);
          ospCommit(renderer);
          viewPort.modified = true;
          forceRedraw();
        } break;
        case '<': {
          timeStep = (timeStep+modelTimeStep.size()-1)%modelTimeStep.size();
          model = modelTimeStep[timeStep];
          PRINT(timeStep);
          PRINT(model);
          ospSetObject(renderer,"model",model);
          ospCommit(renderer);
          viewPort.modified = true;
          forceRedraw();
        } break;
        default:
          Glut3DWidget::keypress(key,where);
        }
      }

      virtual void display()
      {
        if (!fb || !renderer) return;

        static int frameID = 0;

        //{
        // note that the order of 'start' and 'end' here is
        // (intentionally) reversed: due to our asynchrounous rendering
        // you cannot place start() and end() _around_ the renderframe
        // call (which in itself will not do a lot other than triggering
        // work), but the average time between ttwo calls is roughly the
        // frame rate (including display overhead, of course)
        if (frameID > 0) fps.doneRender();
        fps.startRender();
        //}
        ++frameID;

        if (viewPort.modified) {
          Assert2(camera,"ospray camera is null");
          auto from = reinterpret_cast<osp::vec3f&>(viewPort.from);
          auto dir  = viewPort.at-viewPort.from;
          auto up   = reinterpret_cast<osp::vec3f&>(viewPort.up);
          ospSetVec3f(camera,"pos",from);
          ospSetVec3f(camera,"dir",reinterpret_cast<osp::vec3f&>(dir));
          ospSetVec3f(camera,"up",up);
          ospSetf(camera,"aspect",viewPort.aspect);
          ospCommit(camera);
          ospFrameBufferClear(fb,OSP_FB_ACCUM);
          viewPort.modified = false;
          accumID = 0;
        }

        ospRenderFrame(fb,renderer,OSP_FB_COLOR|OSP_FB_ACCUM);
        ++accumID;
        if (accumID < maxAccum)
          forceRedraw();

        ucharFB = (uint32 *) ospMapFrameBuffer(fb);
        frameBufferMode = Glut3DWidget::FRAMEBUFFER_UCHAR;
        Glut3DWidget::display();

        ospUnmapFrameBuffer(ucharFB,fb);

        if (showFPS) {
          char title[1000];

          sprintf(title,"OSPRay Particle Viewer (%f fps)",fps.getFPS());
          setTitle(title);
        }
      }

      OSPModel       model;
      OSPFrameBuffer fb;
      OSPRenderer    renderer;
      OSPCamera      camera;
      ospray::glut3D::FPSCounter fps;
    };

    particle::Model *createTestCube(int numPerSide)
    {
      particle::Model *m = new particle::Model;
      int type = m->getAtomType("testParticle");
      for (int z=0;z<numPerSide;z++)
        for (int y=0;y<numPerSide;y++)
          for (int x=0;x<numPerSide;x++) {
            particle::Model::Atom a;
            a.position.x = x/float(numPerSide);
            a.position.y = y/float(numPerSide);
            a.position.z = z/float(numPerSide);
            a.type = type;
            a.radius = 1.f/numPerSide;
            m->atom.push_back(a);
          }
      return m;
    }

    OSPData makeMaterials(OSPRenderer renderer,particle::Model *model)
    {
      int numMaterials = model->atomType.size();
      OSPMaterial matArray[numMaterials];
      for (int i=0;i<numMaterials;i++) {
        OSPMaterial mat = ospNewMaterial(renderer,"OBJMaterial");
        assert(mat);
        ospSet3fv(mat,"kd",&model->atomType[i]->color.x);
        ospCommit(mat);
        matArray[i] = mat;
      }
      OSPData data = ospNewData(numMaterials,OSP_OBJECT,matArray);
      ospCommit(data);
      return data;
    }

    struct DeferredLoadJob {
      DeferredLoadJob(particle::Model *model,
                      const embree::FileName &xyzFileName,
                      const embree::FileName &defFileName)
        : model(model), xyzFileName(xyzFileName), defFileName(defFileName)
      {}

      //! the mode we still have to load
      particle::Model *model;
      //! file name of xyz file to be loaded into this model
      embree::FileName xyzFileName;
      //! name of atom type defintion file active when this xyz file was added
      embree::FileName defFileName;
    };

    void ospParticleViewerMain(int &ac, const char **&av)
    {
      std::vector<Model *> particleModel;

      cout << "ospParticleViewer: starting to process cmdline arguments" << endl;
      std::vector<DeferredLoadJob *> deferredLoadingListXYZ;
      embree::FileName defFileName = "";

      for (int i=1;i<ac;i++) {
        const std::string arg = av[i];
        if (arg == "--renderer") {
          assert(i+1 < ac);
          rendererType = av[++i];
        } else if (arg == "--radius") {
          Model::defaultRadius = atof(av[++i]);
        } else if (arg == "--sun-dir") {
          defaultDirLight_direction.x = atof(av[++i]);
          defaultDirLight_direction.y = atof(av[++i]);
          defaultDirLight_direction.z = atof(av[++i]);
        } else if (arg == "--module" || arg == "--plugin") {
          assert(i+1 < ac);
          const char *moduleName = av[++i];
          cout << "loading ospray module '" << moduleName << "'" << endl;
          ospLoadModule(moduleName);
        } else if (arg == "--show-fps" || arg == "-fps") {
          showFPS = true;
        } else if (arg == "--save-to") {
          modelSaveFileName = av[++i];
        } else if (arg == "--atom-defs") {
          defFileName = av[++i];
        } else if (av[i][0] == '-') {
          error("unkown commandline argument '"+arg+"'");
        } else {
          embree::FileName fn = arg;
          if (fn.str() == "___CUBE_TEST___") {
            int numPerSide = atoi(av[++i]);
            particle::Model *m = createTestCube(numPerSide);
            particleModel.push_back(m);
          } else if (fn.ext() == "xyz") {
            particle::Model *m = new particle::Model;
            //            m->loadXYZ(fn);
            // std::pair<particle::Model *, embree::FileName> loadJob(m,fn.str());
            deferredLoadingListXYZ.push_back(new DeferredLoadJob(m,fn,defFileName));
            particleModel.push_back(m);
          } else if (fn.ext() == "xyz2") {
            particle::Model *m = new particle::Model;
            m->loadXYZ2(fn);
            particleModel.push_back(m);
          } else if (fn.ext() == "xml") {
            particle::Model *m = parse__Uintah_timestep_xml(fn);
            particleModel.push_back(m);
          } else
            error("unknown file format "+fn.str());
        }
      }

      if (particleModel.empty())
        error("no input file specified");

      parallel_for(deferredLoadingListXYZ.size(), [&](int i){
        embree::FileName defFileName = deferredLoadingListXYZ[i]->defFileName;
        embree::FileName xyzFileName = deferredLoadingListXYZ[i]->xyzFileName;
        particle::Model *model = deferredLoadingListXYZ[i]->model;

        if (defFileName.str() != "")
          model->readAtomTypeDefinitions(defFileName);
        model->loadXYZ(xyzFileName);
      });

      // -------------------------------------------------------
      // done parsings
      // -------------------------------------------------------]
      cout << "ospParticleViewer: done parsing. found model with" << endl;
      cout << "  - num atoms: " << particleModel[0]->atom.size() << endl;
      if (modelSaveFileName != "") {
        particleModel[0]->saveToFile(modelSaveFileName);
        exit(0);
      }

      // -------------------------------------------------------
      // create ospray model
      // -------------------------------------------------------
      ospRenderer = ospNewRenderer(rendererType.c_str());
      if (!ospRenderer)
        error("could not create ospRenderer '"+rendererType+"'");
      Assert(ospRenderer != NULL && "could not create ospRenderer");

      for (int i=0;i<particleModel.size();i++) {
        OSPModel model = ospNewModel();
        OSPData materialData = makeMaterials(ospRenderer,particleModel[i]);

        OSPData data = ospNewData(particleModel[i]->atom.size()*5,OSP_FLOAT,
                                  &particleModel[i]->atom[0],OSP_DATA_SHARED_BUFFER);
        ospCommit(data);

        OSPGeometry geom = ospNewGeometry("spheres");
        ospSet1i(geom,"bytes_per_sphere",sizeof(Model::Atom));
        ospSet1i(geom,"offset_center",0);
        ospSet1i(geom,"offset_radius",3*sizeof(float));
        ospSet1i(geom,"offset_materialID",4*sizeof(float));
        ospSetData(geom,"spheres",data);
        ospSetData(geom,"materialList",materialData);
        ospCommit(geom);

        ospAddGeometry(model,geom);
        ospCommit(model);

        modelTimeStep.push_back(model);
      }

      OSPModel model = modelTimeStep[timeStep];

      std::vector<OSPLight> dirLights;
      cout << "msgView: Adding a hard coded directional light as the sun." << endl;
      OSPLight ospLight = ospNewLight(ospRenderer, "DirectionalLight");
      ospSetString(ospLight, "name", "sun" );
      ospSet3f(ospLight, "color", 1, 1, 1);
      ospSet3fv(ospLight, "direction", &defaultDirLight_direction.x);
      ospCommit(ospLight);
      dirLights.push_back(ospLight);
      OSPData dirLightArray = ospNewData(dirLights.size(), OSP_OBJECT, &dirLights[0], 0);
      ospSetData(ospRenderer, "directionalLights", dirLightArray);

      ospCommit(ospRenderer);

      cout << "ospParticleViewer: done creating ospray model." << endl;

      // -------------------------------------------------------
      // create viewer window
      // -------------------------------------------------------
      ParticleViewer window(model,ospRenderer);
      window.create("ospray particle viewer");
      printf("OSPRay Particle Viewer created. Press 'Q' to quit.\n");
      box3f wb(particleModel[0]->getBBox());
      PRINT(wb);
      window.setWorldBounds(wb);
      ospray::glut3D::runGLUT();
    }

  } // ::ospray::particle
} // ::ospray

int main(int ac, const char **av)
{
  ospInit(&ac,av);
  ospray::glut3D::initGLUT(&ac,av);
  ospray::particle::ospParticleViewerMain(ac,av);
}
<|endoftext|>


<commit_before>/*
Copyright (C) 2018,2019,2021 Rodrigo Jose Hernandez Cordoba

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <mutex>
#include "aeongames/ProtoBufClasses.h"
#include "aeongames/ProtoBufHelpers.h"
#include "aeongames/Node.h"
#include "aeongames/Mesh.h"
#include "aeongames/Pipeline.h"
#include "aeongames/Material.h"
#include "aeongames/Skeleton.h"
#include "aeongames/Animation.h"
#include "aeongames/Utilities.h"
#include "aeongames/ProtoBufHelpers.h"
#include "aeongames/ProtoBufUtils.h"
#include "aeongames/Window.h"
#include "aeongames/CRC.h"
#include "aeongames/AeonEngine.h"
#include "aeongames/ResourceCache.h"
#include "aeongames/Renderer.h"
#include "aeongames/Model.h"
#ifdef _MSC_VER
#pragma warning( push )
#pragma warning( disable : PROTOBUF_WARNINGS )
#endif
#include "model.pb.h"
#ifdef _MSC_VER
#pragma warning( pop )
#endif

namespace AeonGames
{
    Model::Model()
        = default;
    Model::~Model()
        = default;

    void Model::LoadFromMemory ( const void* aBuffer, size_t aBufferSize )
    {
        LoadFromProtoBufObject<Model, ModelMsg, "AEONMDL"_mgk> ( *this, aBuffer, aBufferSize );
    }

    void Model::LoadFromPBMsg ( const ModelMsg& aModelMsg )
    {
        ResourceId default_pipeline{};
        ResourceId default_material{};

        // Default Pipeline ---------------------------------------------------------------------
        if ( aModelMsg.has_default_pipeline() )
        {
            default_pipeline = {"Pipeline"_crc32, GetReferenceMsgId ( aModelMsg.default_pipeline() ) } ;
            default_pipeline.Store();
        }

        // Default Material ---------------------------------------------------------------------
        if ( aModelMsg.has_default_material() )
        {
            default_material = {"Material"_crc32, GetReferenceMsgId ( aModelMsg.default_material() ) } ;
            default_material.Store();
        }

        // Skeleton -----------------------------------------------------------------------------
        if ( aModelMsg.has_skeleton() )
        {
            mSkeleton = { "Skeleton"_crc32, GetReferenceMsgId ( aModelMsg.skeleton() ) };
            mSkeleton.Store();
        }
        // Meshes -----------------------------------------------------------------------------
        mAssemblies.reserve ( aModelMsg.assembly_size() );
        for ( auto& assembly : aModelMsg.assembly() )
        {
            ResourceId mesh{};
            ResourceId pipeline{default_pipeline};
            ResourceId material{default_material};

            if ( assembly.has_mesh() )
            {
                mesh = {"Mesh"_crc32, GetReferenceMsgId ( assembly.mesh() ) } ;
                mesh.Store();
            }

            if ( assembly.has_pipeline() )
            {
                pipeline = {"Pipeline"_crc32, GetReferenceMsgId ( assembly.pipeline() ) } ;
                pipeline.Store();
            }

            if ( assembly.has_material() )
            {
                material = {"Material"_crc32, GetReferenceMsgId ( assembly.material() ) } ;
                material.Store();
            }
            mAssemblies.emplace_back ( mesh, pipeline, material );
        }
        // Animations -----------------------------------------------------------------------------
        mAnimations.reserve ( aModelMsg.animation_size() );
        for ( auto& animation : aModelMsg.animation() )
        {
            mAnimations.emplace_back ( ResourceId{"Animation"_crc32, GetReferenceMsgId ( animation ) } ).Store();
        }
    }

    void Model::Unload()
    {
        /**@todo refcount Resource Id's? */
        mAssemblies.clear();
        mAnimations.clear();
    }

    const std::vector<Model::Assembly>& Model::GetAssemblies() const
    {
        return mAssemblies;
    }

    const Skeleton* Model::GetSkeleton() const
    {
        return mSkeleton.Cast<Skeleton>();
    }

    const std::vector<ResourceId>& Model::GetAnimations() const
    {
        return mAnimations;
    }

    void Model::LoadRendererResources ( Renderer& aRenderer ) const
    {
        for ( const auto i : mAssemblies )
        {
            aRenderer.LoadMesh ( *std::get<0> ( i ).Cast<Mesh>() );
            aRenderer.LoadPipeline ( *std::get<1> ( i ).Cast<Pipeline>() );
            aRenderer.LoadMaterial ( *std::get<2> ( i ).Cast<Material>() );
        }
    }

    void Model::UnloadRendererResources ( Renderer& aRenderer ) const
    {
        for ( const auto i : mAssemblies )
        {
            aRenderer.UnloadMesh ( *std::get<0> ( i ).Cast<Mesh>() );
            aRenderer.UnloadPipeline ( *std::get<1> ( i ).Cast<Pipeline>() );
            aRenderer.UnloadMaterial ( *std::get<2> ( i ).Cast<Material>() );
        }
    }
}
<commit_msg>Fix range for not using a reference.<commit_after>/*
Copyright (C) 2018,2019,2021 Rodrigo Jose Hernandez Cordoba

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <mutex>
#include "aeongames/ProtoBufClasses.h"
#include "aeongames/ProtoBufHelpers.h"
#include "aeongames/Node.h"
#include "aeongames/Mesh.h"
#include "aeongames/Pipeline.h"
#include "aeongames/Material.h"
#include "aeongames/Skeleton.h"
#include "aeongames/Animation.h"
#include "aeongames/Utilities.h"
#include "aeongames/ProtoBufHelpers.h"
#include "aeongames/ProtoBufUtils.h"
#include "aeongames/Window.h"
#include "aeongames/CRC.h"
#include "aeongames/AeonEngine.h"
#include "aeongames/ResourceCache.h"
#include "aeongames/Renderer.h"
#include "aeongames/Model.h"
#ifdef _MSC_VER
#pragma warning( push )
#pragma warning( disable : PROTOBUF_WARNINGS )
#endif
#include "model.pb.h"
#ifdef _MSC_VER
#pragma warning( pop )
#endif

namespace AeonGames
{
    Model::Model()
        = default;
    Model::~Model()
        = default;

    void Model::LoadFromMemory ( const void* aBuffer, size_t aBufferSize )
    {
        LoadFromProtoBufObject<Model, ModelMsg, "AEONMDL"_mgk> ( *this, aBuffer, aBufferSize );
    }

    void Model::LoadFromPBMsg ( const ModelMsg& aModelMsg )
    {
        ResourceId default_pipeline{};
        ResourceId default_material{};

        // Default Pipeline ---------------------------------------------------------------------
        if ( aModelMsg.has_default_pipeline() )
        {
            default_pipeline = {"Pipeline"_crc32, GetReferenceMsgId ( aModelMsg.default_pipeline() ) } ;
            default_pipeline.Store();
        }

        // Default Material ---------------------------------------------------------------------
        if ( aModelMsg.has_default_material() )
        {
            default_material = {"Material"_crc32, GetReferenceMsgId ( aModelMsg.default_material() ) } ;
            default_material.Store();
        }

        // Skeleton -----------------------------------------------------------------------------
        if ( aModelMsg.has_skeleton() )
        {
            mSkeleton = { "Skeleton"_crc32, GetReferenceMsgId ( aModelMsg.skeleton() ) };
            mSkeleton.Store();
        }
        // Meshes -----------------------------------------------------------------------------
        mAssemblies.reserve ( aModelMsg.assembly_size() );
        for ( auto& assembly : aModelMsg.assembly() )
        {
            ResourceId mesh{};
            ResourceId pipeline{default_pipeline};
            ResourceId material{default_material};

            if ( assembly.has_mesh() )
            {
                mesh = {"Mesh"_crc32, GetReferenceMsgId ( assembly.mesh() ) } ;
                mesh.Store();
            }

            if ( assembly.has_pipeline() )
            {
                pipeline = {"Pipeline"_crc32, GetReferenceMsgId ( assembly.pipeline() ) } ;
                pipeline.Store();
            }

            if ( assembly.has_material() )
            {
                material = {"Material"_crc32, GetReferenceMsgId ( assembly.material() ) } ;
                material.Store();
            }
            mAssemblies.emplace_back ( mesh, pipeline, material );
        }
        // Animations -----------------------------------------------------------------------------
        mAnimations.reserve ( aModelMsg.animation_size() );
        for ( auto& animation : aModelMsg.animation() )
        {
            mAnimations.emplace_back ( ResourceId{"Animation"_crc32, GetReferenceMsgId ( animation ) } ).Store();
        }
    }

    void Model::Unload()
    {
        /**@todo refcount Resource Id's? */
        mAssemblies.clear();
        mAnimations.clear();
    }

    const std::vector<Model::Assembly>& Model::GetAssemblies() const
    {
        return mAssemblies;
    }

    const Skeleton* Model::GetSkeleton() const
    {
        return mSkeleton.Cast<Skeleton>();
    }

    const std::vector<ResourceId>& Model::GetAnimations() const
    {
        return mAnimations;
    }

    void Model::LoadRendererResources ( Renderer& aRenderer ) const
    {
        for ( const auto& i : mAssemblies )
        {
            aRenderer.LoadMesh ( *std::get<0> ( i ).Cast<Mesh>() );
            aRenderer.LoadPipeline ( *std::get<1> ( i ).Cast<Pipeline>() );
            aRenderer.LoadMaterial ( *std::get<2> ( i ).Cast<Material>() );
        }
    }

    void Model::UnloadRendererResources ( Renderer& aRenderer ) const
    {
        for ( const auto& i : mAssemblies )
        {
            aRenderer.UnloadMesh ( *std::get<0> ( i ).Cast<Mesh>() );
            aRenderer.UnloadPipeline ( *std::get<1> ( i ).Cast<Pipeline>() );
            aRenderer.UnloadMaterial ( *std::get<2> ( i ).Cast<Material>() );
        }
    }
}
<|endoftext|>


<commit_before>#ifndef MAP_HPP
#define MAP_HPP

#include <singleton.hpp>
#include <vector>
#include <string>
#include <engine.hpp>
#include <iostream>

using namespace std;

namespace fabric {

	class IMap {
	public:
		virtual void load() {}

		void unload() {
			for (unsigned int i = 0; i < Engine::get()->vLoadedGameObjects->size(); i++) {
				delete Engine::get()->vLoadedGameObjects->at(i);
			}
		}
	};

	class Map: public Singleton<Map> {
	public:
		IMap* m_mMap;
		int load(char* path);
		int unload();
	};

}

#endif<commit_msg>Removed IMap interface<commit_after>#ifndef MAP_HPP
#define MAP_HPP

#include <singleton.hpp>
#include <vector>
#include <string>
#include <engine.hpp>
#include <iostream>
#include <Windows.h>

using namespace std;

namespace fabric {

	class Map: public Singleton<Map> {
	public:
		HINSTANCE* m_mMap = 0;
		int load(char* path);
		int unload();
	};

}

#endif<|endoftext|>


<commit_before>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2010, OpenNebula Project Leads (OpenNebula.org)             */
/*                                                                            */
/* Licensed under the Apache License, Version 2.0 (the "License"); you may    */
/* not use this file except in compliance with the License. You may obtain    */
/* a copy of the License at                                                   */
/*                                                                            */
/* http://www.apache.org/licenses/LICENSE-2.0                                 */
/*                                                                            */
/* Unless required by applicable law or agreed to in writing, software        */
/* distributed under the License is distributed on an "AS IS" BASIS,          */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   */
/* See the License for the specific language governing permissions and        */
/* limitations under the License.                                             */
/* -------------------------------------------------------------------------- */

#include <string>
#include <iostream>
#include <stdlib.h>

#include "VirtualMachinePool.h"
#include "PoolTest.h"

using namespace std;

const int uids[] = {123, 261, 123};

const string names[] = {"VM one", "Second VM", "VM one"};

const string templates[] =
{
    "NAME   = \"VM one\"\n"
    "MEMORY = 128\n"
    "CPU    = 1",

    "NAME   = \"Second VM\"\n"
    "MEMORY = 256\n"
    "CPU    = 2",

    "NAME   = \"VM one\"\n"
    "MEMORY = 1024\n"
    "CPU    = 1"
};

const string xmls[] =
{
    "<VM><ID>0</ID><UID>123</UID><NAME>VM one</NAME><LAST_POLL>0</LAST_POLL><ST"
    "ATE>1</STATE><LCM_STATE>0</LCM_STATE><STIME>0000000000</STIME><ETIME>0</ET"
    "IME><DEPLOY_ID></DEPLOY_ID><MEMORY>0</MEMORY><CPU>0</CPU><NET_TX>0</NET_TX"
    "><NET_RX>0</NET_RX><TEMPLATE><CPU>1</CPU><MEMORY>128</MEMORY><NAME>VM one<"
    "/NAME><VMID>0</VMID></TEMPLATE></VM>",

    "<VM><ID>1</ID><UID>261</UID><NAME>Second VM</NAME><LAST_POLL>0</LAST_POLL>"
    "<STATE>1</STATE><LCM_STATE>0</LCM_STATE><STIME>0000000000</STIME><ETIME>0<"
    "/ETIME><DEPLOY_ID></DEPLOY_ID><MEMORY>0</MEMORY><CPU>0</CPU><NET_TX>0</NET"
    "_TX><NET_RX>0</NET_RX><TEMPLATE><CPU>2</CPU><MEMORY>256</MEMORY><NAME>Seco"
    "nd VM</NAME><VMID>1</VMID></TEMPLATE></VM>",

    "<VM><ID>0</ID><UID>123</UID><NAME>VM one</NAME><LAST_POLL>0</LAST_POLL><ST"
    "ATE>1</STATE><LCM_STATE>0</LCM_STATE><STIME>0000000000</STIME><ETIME>0</ET"
    "IME><DEPLOY_ID></DEPLOY_ID><MEMORY>0</MEMORY><CPU>0</CPU><NET_TX>0</NET_TX"
    "><NET_RX>0</NET_RX><TEMPLATE><CPU>1</CPU><MEMORY>1024</MEMORY><NAME>VM one"
    "</NAME><VMID>0</VMID></TEMPLATE></VM>"
};

// This xml dump result has the STIMEs modified to 0000000000
const string xml_dump =
    "<VM_POOL><VM><ID>0</ID><UID>1</UID><USERNAME>A user</USERNAME><NAME>VM one"
    "</NAME><LAST_POLL>0</LAST_POLL><STATE>1</STATE><LCM_STATE>0</LCM_STATE><ST"
    "IME>0000000000</STIME><ETIME>0</ETIME><DEPLOY_ID></DEPLOY_ID><MEMORY>0</ME"
    "MORY><CPU>0</CPU><NET_TX>0</NET_TX><NET_RX>0</NET_RX></VM><VM><ID>1</ID><U"
    "ID>2</UID><USERNAME>B user</USERNAME><NAME>Second VM</NAME><LAST_POLL>0</L"
    "AST_POLL><STATE>2</STATE><LCM_STATE>0</LCM_STATE><STIME>0000000000</STIME>"
    "<ETIME>0</ETIME><DEPLOY_ID></DEPLOY_ID><MEMORY>0</MEMORY><CPU>0</CPU><NET_"
    "TX>0</NET_TX><NET_RX>0</NET_RX></VM></VM_POOL>";

const string xml_dump_where =
    "<VM_POOL><VM><ID>0</ID><UID>1</UID><USERNAME>A user</USERNAME><NAME>VM one"
    "</NAME><LAST_POLL>0</LAST_POLL><STATE>1</STATE><LCM_STATE>0</LCM_STATE><ST"
    "IME>0000000000</STIME><ETIME>0</ETIME><DEPLOY_ID></DEPLOY_ID><MEMORY>0</ME"
    "MORY><CPU>0</CPU><NET_TX>0</NET_TX><NET_RX>0</NET_RX></VM></VM_POOL>";

const string replacement = "0000000000";

/* ************************************************************************* */
/* ************************************************************************* */

class VirtualMachinePoolTest : public PoolTest
{
    CPPUNIT_TEST_SUITE (VirtualMachinePoolTest);

    // Not all PoolTest tests can be used. Drop method isn't defined for
    // the VirtualMachinePool.
    CPPUNIT_TEST (oid_assignment);
    CPPUNIT_TEST (get_from_cache);
    CPPUNIT_TEST (get_from_db);
    CPPUNIT_TEST (wrong_get);

    CPPUNIT_TEST (update);
    CPPUNIT_TEST (dump);
    CPPUNIT_TEST (dump_where);
    CPPUNIT_TEST (history);

    CPPUNIT_TEST_SUITE_END ();

protected:

    virtual string database_name()
    {
        return "vmachine_pool_test";
    };

    virtual void bootstrap(SqlDB* db)
    {
        VirtualMachinePool::bootstrap(db);
    };

    virtual PoolSQL* create_pool(SqlDB* db)
    {
        // The VM pool needs a vector containing the vm hooks
        vector<const Attribute *> vm_hooks;
        return new VirtualMachinePool(db, vm_hooks);
    };

    virtual int allocate(int index)
    {
        int oid;
        ((VirtualMachinePool*)pool)->allocate(uids[index],
                                              templates[index], &oid, false);
        return oid;
    };

    void check(int index, PoolObjectSQL* obj)
    {
        CPPUNIT_ASSERT( obj != 0 );

        string xml_str = "";

        // Get the xml and replace the STIME to 0, so we can compare it
        ((VirtualMachine*)obj)->to_xml(xml_str);
        xml_str.replace( xml_str.find("<STIME>")+7, 10, replacement);

        CPPUNIT_ASSERT( ((VirtualMachine*)obj)->get_name() == names[index] );
        CPPUNIT_ASSERT( xml_str == xmls[index]);
    };

public:
    VirtualMachinePoolTest(){};

    ~VirtualMachinePoolTest(){};

    /* ********************************************************************* */
    /* ********************************************************************* */

    void update()
    {
        VirtualMachinePool*  vmp = static_cast<VirtualMachinePool*>(pool);
        VirtualMachine*      vm;
        int oid;

        string hostname     = "hostname";
        string vm_dir       = "vm_dir";
        string vmm_mad      = "vm_mad";
        string tm_mad       = "tm_mad";

        // Allocate two VMs
        oid = allocate(0);
        CPPUNIT_ASSERT( oid != -1 );

        // Get the first one, and change one of the templates attributes
        vm = vmp->get(oid, true);

        CPPUNIT_ASSERT( vm != 0 );

        string attribute = "MEMORY";
        string value     = "1024";

        vm->set_state(VirtualMachine::ACTIVE);

        // VirtualMachine object should be cached. Let's update the DB
        vmp->update_template_attribute(vm, attribute, value);

        vmp->update(vm);

        //In memory (cache) check
        string new_mem;

        vm->get_template_attribute("MEMORY",new_mem);

        CPPUNIT_ASSERT( new_mem == "1024" );
        CPPUNIT_ASSERT( vm->get_state() == VirtualMachine::ACTIVE );

        vm->unlock();

        //Now force access to DB

        pool->clean();
        vm = vmp->get(oid,false);

        new_mem.clear();

        vm->get_template_attribute("MEMORY",new_mem);

        CPPUNIT_ASSERT( new_mem == "1024" );
        CPPUNIT_ASSERT( vm->get_state() == VirtualMachine::ACTIVE );
    };

    void dump()
    {
        // TBD
    }

    void dump_where()
    {
        //TBD
    }

    void history()
    {
        VirtualMachine *      vm;
        VirtualMachinePool *  vmp = static_cast<VirtualMachinePool*>(pool);

        int rc, oid;

        string hostname     = "hostname";
        string new_hostname = "new_hostname";
        string vm_dir       = "vm_dir";
        string vmm_mad      = "vm_mad";
        string tm_mad       = "tm_mad";

        // Allocate a VM
        oid = allocate(0);
        CPPUNIT_ASSERT( oid != -1 );

        vm = vmp->get(oid, true);
        CPPUNIT_ASSERT( vm != 0 );

        // Add a history item
        vm->add_history(0, hostname, vm_dir, vmm_mad, tm_mad);

        rc = vmp->update_history(vm);
        CPPUNIT_ASSERT( rc == 0 );

        vm->add_history(0, new_hostname, vm_dir, vmm_mad, tm_mad);

        vm->set_reason(History::USER);
        vm->set_previous_reason(History::ERROR);

        rc = vmp->update_history(vm);
        rc = vmp->update_previous_history(vm);

        CPPUNIT_ASSERT( rc == 0 );

        vm->unlock();

        // Clean the DB cache
        pool->clean();

        vm = vmp->get(oid, false);

        CPPUNIT_ASSERT( vm != 0 );
        CPPUNIT_ASSERT( vm->hasHistory() == true );
        CPPUNIT_ASSERT( vm->hasPreviousHistory() == true );

        CPPUNIT_ASSERT( vm->get_hostname() == new_hostname );
        CPPUNIT_ASSERT( vm->get_previous_hostname() == hostname );

        CPPUNIT_ASSERT( vm->get_vmm_mad() == vmm_mad );
        CPPUNIT_ASSERT( vm->get_previous_vmm_mad() == vmm_mad );

        CPPUNIT_ASSERT( vm->get_previous_reason() == History::ERROR );
    }
};

/* ************************************************************************* */
/* ************************************************************************* */

int main(int argc, char ** argv)
{
    return PoolTest::main(argc, argv, VirtualMachinePoolTest::suite());
}
<commit_msg>feature #192: dump tests for VirtualMachinePool<commit_after>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2010, OpenNebula Project Leads (OpenNebula.org)             */
/*                                                                            */
/* Licensed under the Apache License, Version 2.0 (the "License"); you may    */
/* not use this file except in compliance with the License. You may obtain    */
/* a copy of the License at                                                   */
/*                                                                            */
/* http://www.apache.org/licenses/LICENSE-2.0                                 */
/*                                                                            */
/* Unless required by applicable law or agreed to in writing, software        */
/* distributed under the License is distributed on an "AS IS" BASIS,          */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   */
/* See the License for the specific language governing permissions and        */
/* limitations under the License.                                             */
/* -------------------------------------------------------------------------- */

#include <string>
#include <iostream>
#include <stdlib.h>

#include "VirtualMachinePool.h"
#include "PoolTest.h"

using namespace std;

const int uids[] = {123, 261, 123};

const string names[] = {"VM one", "Second VM", "VM one"};

const string templates[] =
{
    "NAME   = \"VM one\"\n"
    "MEMORY = 128\n"
    "CPU    = 1",

    "NAME   = \"Second VM\"\n"
    "MEMORY = 256\n"
    "CPU    = 2",

    "NAME   = \"VM one\"\n"
    "MEMORY = 1024\n"
    "CPU    = 1"
};

const string xmls[] =
{
    "<VM><ID>0</ID><UID>123</UID><NAME>VM one</NAME><LAST_POLL>0</LAST_POLL><ST"
    "ATE>1</STATE><LCM_STATE>0</LCM_STATE><STIME>0000000000</STIME><ETIME>0</ET"
    "IME><DEPLOY_ID></DEPLOY_ID><MEMORY>0</MEMORY><CPU>0</CPU><NET_TX>0</NET_TX"
    "><NET_RX>0</NET_RX><TEMPLATE><CPU>1</CPU><MEMORY>128</MEMORY><NAME>VM one<"
    "/NAME><VMID>0</VMID></TEMPLATE></VM>",

    "<VM><ID>1</ID><UID>261</UID><NAME>Second VM</NAME><LAST_POLL>0</LAST_POLL>"
    "<STATE>1</STATE><LCM_STATE>0</LCM_STATE><STIME>0000000000</STIME><ETIME>0<"
    "/ETIME><DEPLOY_ID></DEPLOY_ID><MEMORY>0</MEMORY><CPU>0</CPU><NET_TX>0</NET"
    "_TX><NET_RX>0</NET_RX><TEMPLATE><CPU>2</CPU><MEMORY>256</MEMORY><NAME>Seco"
    "nd VM</NAME><VMID>1</VMID></TEMPLATE></VM>",

    "<VM><ID>0</ID><UID>123</UID><NAME>VM one</NAME><LAST_POLL>0</LAST_POLL><ST"
    "ATE>1</STATE><LCM_STATE>0</LCM_STATE><STIME>0000000000</STIME><ETIME>0</ET"
    "IME><DEPLOY_ID></DEPLOY_ID><MEMORY>0</MEMORY><CPU>0</CPU><NET_TX>0</NET_TX"
    "><NET_RX>0</NET_RX><TEMPLATE><CPU>1</CPU><MEMORY>1024</MEMORY><NAME>VM one"
    "</NAME><VMID>0</VMID></TEMPLATE></VM>"
};

// This xml dump result has the STIMEs modified to 0000000000
const string xml_dump =
    "<VM_POOL><VM><ID>0</ID><UID>1</UID><USERNAME>A user</USERNAME><NAME>VM one"
    "</NAME><LAST_POLL>0</LAST_POLL><STATE>1</STATE><LCM_STATE>0</LCM_STATE><ST"
    "IME>0000000000</STIME><ETIME>0</ETIME><DEPLOY_ID></DEPLOY_ID><MEMORY>0</ME"
    "MORY><CPU>0</CPU><NET_TX>0</NET_TX><NET_RX>0</NET_RX></VM><VM><ID>1</ID><U"
    "ID>2</UID><USERNAME>B user</USERNAME><NAME>Second VM</NAME><LAST_POLL>0</L"
    "AST_POLL><STATE>2</STATE><LCM_STATE>0</LCM_STATE><STIME>0000000000</STIME>"
    "<ETIME>0</ETIME><DEPLOY_ID></DEPLOY_ID><MEMORY>0</MEMORY><CPU>0</CPU><NET_"
    "TX>0</NET_TX><NET_RX>0</NET_RX></VM></VM_POOL>";

const string xml_dump_where =
    "<VM_POOL><VM><ID>0</ID><UID>1</UID><USERNAME>A user</USERNAME><NAME>VM one"
    "</NAME><LAST_POLL>0</LAST_POLL><STATE>1</STATE><LCM_STATE>0</LCM_STATE><ST"
    "IME>0000000000</STIME><ETIME>0</ETIME><DEPLOY_ID></DEPLOY_ID><MEMORY>0</ME"
    "MORY><CPU>0</CPU><NET_TX>0</NET_TX><NET_RX>0</NET_RX></VM></VM_POOL>";

const string replacement = "0000000000";

/* ************************************************************************* */
/* ************************************************************************* */

class VirtualMachinePoolTest : public PoolTest
{
    CPPUNIT_TEST_SUITE (VirtualMachinePoolTest);

    // Not all PoolTest tests can be used. Drop method isn't defined for
    // the VirtualMachinePool.
    CPPUNIT_TEST (oid_assignment);
    CPPUNIT_TEST (get_from_cache);
    CPPUNIT_TEST (get_from_db);
    CPPUNIT_TEST (wrong_get);

    CPPUNIT_TEST (update);
    CPPUNIT_TEST (dump);
    CPPUNIT_TEST (dump_where);
    CPPUNIT_TEST (history);

    CPPUNIT_TEST_SUITE_END ();

protected:

    string database_name()
    {
        return "vmachine_pool_test";
    };

    void bootstrap(SqlDB* db)
    {
        VirtualMachinePool::bootstrap(db);
    };

    PoolSQL* create_pool(SqlDB* db)
    {
        // The VM pool needs a vector containing the vm hooks
        vector<const Attribute *> vm_hooks;
        return new VirtualMachinePool(db, vm_hooks);
    };

    int allocate(int index)
    {
        int oid;
        ((VirtualMachinePool*)pool)->allocate(uids[index],
                                              templates[index], &oid, false);
        return oid;
    };

    void check(int index, PoolObjectSQL* obj)
    {
        CPPUNIT_ASSERT( obj != 0 );

        string xml_str = "";

        // Get the xml and replace the STIME to 0, so we can compare it
        ((VirtualMachine*)obj)->to_xml(xml_str);
        xml_str.replace( xml_str.find("<STIME>")+7, 10, replacement);

        CPPUNIT_ASSERT( ((VirtualMachine*)obj)->get_name() == names[index] );
        CPPUNIT_ASSERT( xml_str == xmls[index]);
    };

    void set_up_user_pool()
    {
        UserPool::bootstrap(db);
        UserPool * user_pool = new UserPool(db);
        int uid_1, uid_2;

        string username_1 = "A user";
        string username_2 = "B user";

        string pass_1     = "A pass";
        string pass_2     = "B pass";

        user_pool->allocate(&uid_1, username_1, pass_1, true);
        user_pool->allocate(&uid_2, username_2, pass_2, true);

        delete user_pool;
    };

public:
    VirtualMachinePoolTest(){};

    ~VirtualMachinePoolTest(){};

    /* ********************************************************************* */
    /* ********************************************************************* */

    void update()
    {
        VirtualMachinePool * vmp = static_cast<VirtualMachinePool*>(pool);
        VirtualMachine *     vm;
        int oid;

        string hostname     = "hostname";
        string vm_dir       = "vm_dir";
        string vmm_mad      = "vm_mad";
        string tm_mad       = "tm_mad";

        // Allocate two VMs
        oid = allocate(0);
        CPPUNIT_ASSERT( oid != -1 );

        // Get the first one, and change one of the templates attributes
        vm = vmp->get(oid, true);

        CPPUNIT_ASSERT( vm != 0 );

        string attribute = "MEMORY";
        string value     = "1024";

        vm->set_state(VirtualMachine::ACTIVE);

        // VirtualMachine object should be cached. Let's update the DB
        vmp->update_template_attribute(vm, attribute, value);

        vmp->update(vm);

        //In memory (cache) check
        string new_mem;

        vm->get_template_attribute("MEMORY",new_mem);

        CPPUNIT_ASSERT( new_mem == "1024" );
        CPPUNIT_ASSERT( vm->get_state() == VirtualMachine::ACTIVE );

        vm->unlock();

        //Now force access to DB

        pool->clean();
        vm = vmp->get(oid,false);

        new_mem.clear();

        vm->get_template_attribute("MEMORY",new_mem);

        CPPUNIT_ASSERT( new_mem == "1024" );
        CPPUNIT_ASSERT( vm->get_state() == VirtualMachine::ACTIVE );
    };

    void dump()
    {
        VirtualMachinePool * vmp = static_cast<VirtualMachinePool*>(pool);

        set_up_user_pool();

        ostringstream oss;
        int oid, rc;

        vmp->allocate(1, templates[0], &oid, false);
        vmp->allocate(2, templates[1], &oid, true);

        rc = vmp->dump(oss, "");
        CPPUNIT_ASSERT(rc == 0);

        string result = oss.str();
        result.replace(152, 10, replacement);
        result.replace(426, 10, replacement);

        CPPUNIT_ASSERT( result == xml_dump );
    }

    void dump_where()
    {
        VirtualMachinePool * vmp = static_cast<VirtualMachinePool*>(pool);

        set_up_user_pool();

        int oid, rc;
        ostringstream oss;
        ostringstream where;

        vmp->allocate(1, templates[0], &oid, false);
        vmp->allocate(2, templates[1], &oid, true);

        where << "uid < 2";
        rc = vmp->dump(oss, where.str());
        CPPUNIT_ASSERT(rc == 0);

        string result = oss.str();
        result.replace(152, 10, replacement);
        CPPUNIT_ASSERT( result == xml_dump_where );
    }

    void history()
    {
        VirtualMachine *      vm;
        VirtualMachinePool *  vmp = static_cast<VirtualMachinePool*>(pool);

        int rc, oid;

        string hostname     = "hostname";
        string new_hostname = "new_hostname";
        string vm_dir       = "vm_dir";
        string vmm_mad      = "vm_mad";
        string tm_mad       = "tm_mad";

        // Allocate a VM
        oid = allocate(0);
        CPPUNIT_ASSERT( oid != -1 );

        vm = vmp->get(oid, true);
        CPPUNIT_ASSERT( vm != 0 );

        // Add a history item
        vm->add_history(0, hostname, vm_dir, vmm_mad, tm_mad);

        rc = vmp->update_history(vm);
        CPPUNIT_ASSERT( rc == 0 );

        vm->add_history(0, new_hostname, vm_dir, vmm_mad, tm_mad);

        vm->set_reason(History::USER);
        vm->set_previous_reason(History::ERROR);

        rc = vmp->update_history(vm);
        rc = vmp->update_previous_history(vm);

        CPPUNIT_ASSERT( rc == 0 );

        vm->unlock();

        // Clean the DB cache
        pool->clean();

        vm = vmp->get(oid, false);

        CPPUNIT_ASSERT( vm != 0 );
        CPPUNIT_ASSERT( vm->hasHistory() == true );
        CPPUNIT_ASSERT( vm->hasPreviousHistory() == true );

        CPPUNIT_ASSERT( vm->get_hostname() == new_hostname );
        CPPUNIT_ASSERT( vm->get_previous_hostname() == hostname );

        CPPUNIT_ASSERT( vm->get_vmm_mad() == vmm_mad );
        CPPUNIT_ASSERT( vm->get_previous_vmm_mad() == vmm_mad );

        CPPUNIT_ASSERT( vm->get_previous_reason() == History::ERROR );
    }
};

/* ************************************************************************* */
/* ************************************************************************* */

int main(int argc, char ** argv)
{
    return PoolTest::main(argc, argv, VirtualMachinePoolTest::suite());
}
<|endoftext|>


<commit_before>#ifndef MAP_HPP
#define MAP_HPP

namespace fabric {

	class Map {

	};

}

#endif<commit_msg>Inital Commit<commit_after>#ifndef MAP_HPP
#define MAP_HPP

#include <singleton.hpp>
#include <vector>
#include <string>
#include <engine.hpp>
#include <iostream>

using namespace std;

namespace fabric {

	class IMap {
	public:
		virtual void load() {}

		void unload() {
			for (unsigned int i = 0; i < Engine::get()->vLoadedGameObjects->size(); i++) {
				delete Engine::get()->vLoadedGameObjects->at(i);
			}
		}
	};

	class Map: public Singleton<Map> {
	public:
		IMap* m_mMap;
		int load(IMap* map);
		int unload();
	};

}

#endif<|endoftext|>