<commit_before>#include <SDL.h>
#include <vector>

#include "opengl.h"

int Abs(int num) {
	return num > 0 ? num : -num;
}

int PingPong(int num, int length) {
	return length - Abs((num % (length * 2)) - length);
}

int main() {

	const int WindowWidth = 720;
	const int WindowHeight = 720;

	if (SDL_Init(SDL_INIT_EVERYTHING)) {
		SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: %s\n", SDL_GetError());
		return 1;
	}

	SDL_Window* window = SDL_CreateWindow("SDL OpenGL", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, WindowWidth, WindowHeight, SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE);
	if (!window) {
		SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: %s\n", SDL_GetError());
		return 1;
	}

	//// OpenGL Setup

	// Options
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);

	// Connect window
	SDL_GLContext context = SDL_GL_CreateContext(window);

	if (!context) {
		SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: %s\n", SDL_GetError());
		return 1;
	}

	OpenGL_Init();

	{
		int value = 0;
		SDL_GL_GetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, &value);
		SDL_Log("SDL_GL_CONTEXT_MAJOR_VERSION: %d\n", value);

		SDL_GL_GetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, &value);
		SDL_Log("SDL_GL_CONTEXT_MINOR_VERSION: %d\n", value);
	}

	int r = 0;
	int g = 0;
	int b = 0;
	glViewport(0, 0, WindowWidth, WindowHeight);
	glClearColor(0.39f, 0.58f, 0.92f, 1.0f);

	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

	// Shaders
	const GLchar* vertexShaderSource = "#version 330 core\n"
		"layout (location = 0) in vec3 position;\n"
		"layout (location = 1) in vec2 texCoord;\n"
		"out vec2 TexCoord;\n"
		"void main()\n"
		"{\n"
		"gl_Position = vec4(position.x, position.y, position.z, 1.0);\n"
		"TexCoord = texCoord;\n"
		"}\0";

	const GLchar* fragmentShaderSource = "#version 330 core\n"
		"in vec2 TexCoord;\n"
		"out vec4 color;\n"
		"uniform sampler2D ourTexture;\n"
		"void main()\n"
		"{\n"
		"color = texture(ourTexture, TexCoord);\n"
		"}\n\0";

	GLint success;
	GLchar logBuffer[512];

	// Vertex
	GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
	glShaderSource(vertexShader, 1, &vertexShaderSource, NULL);
	glCompileShader(vertexShader);

	glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success);
	if (!success) {
		glGetShaderInfoLog(vertexShader, 512, NULL, logBuffer);
		SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Vertex Compile Error: %s", logBuffer);
	}

	// Fragment
	GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
	glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL);
	glCompileShader(fragmentShader);

	glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success);
	if (!success) {
		glGetShaderInfoLog(fragmentShader, 512, NULL, logBuffer);
		SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Fragment Compile Error: %s", logBuffer);
	}

	// Program
	GLuint shaderProgram = glCreateProgram();
	glAttachShader(shaderProgram, vertexShader);
	glAttachShader(shaderProgram, fragmentShader);
	glLinkProgram(shaderProgram);

	glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success);
	if (!success) {
		glGetProgramInfoLog(shaderProgram, 512, NULL, logBuffer);
		SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Shader Linking Error: %s", logBuffer);
	}

	glDeleteShader(vertexShader);
	glDeleteShader(fragmentShader);

	//glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);

	GLfloat vertices[] = {
		// Positions          // Colors           	  // Texture Coords
		0.5f,  0.5f, 0.0f,   1.0f, 1.0f, 1.0f,   1.0f, 1.0f, // Top Right
		0.5f, -0.5f, 0.0f,   1.0f, 1.0f, 1.0f,   1.0f, 0.0f, // Bottom Right
		-0.5f, -0.5f, 0.0f,   1.0f, 1.0f, 1.0f,   0.0f, 0.0f, // Bottom Left
		-0.5f,  0.5f, 0.0f,   1.0f, 1.0f, 0.0f,   0.0f, 1.0f  // Top Left
    };

	GLuint indices[] = {
        0, 1, 3,
        1, 2, 3,
	};

    GLuint VBO, VAO, EBO;
    glGenVertexArrays(1, &VAO);
    glGenBuffers(1, &VBO);
    glGenBuffers(1, &EBO);

    // Bind the Vertex Array Object first, then bind and set vertex buffer(s) and attribute pointer(s).
    glBindVertexArray(VAO);
	{
		// Now the VBO..
		glBindBuffer(GL_ARRAY_BUFFER, VBO);
		glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

		// Finally the EBO
		glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
		glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);

		// Vertex Attributes

		glVertexAttribPointer(0, // Layout
							3, // Size
							GL_FLOAT, // Type
							GL_FALSE, // Normalised
							8 * sizeof(GLfloat), // Stride
							(void*) 0); // Array Buffer Offset
		glEnableVertexAttribArray(0);

		// glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
		// glEnableVertexAttribArray(1);

		glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(6 * sizeof(GLfloat)));
		glEnableVertexAttribArray(1);
	}

	glBindVertexArray(0);

	// Texture loading

	SDL_Surface* image = SDL_LoadBMP("texture.bmp");
	if (!image) {
		SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Unable to load texture.bmp! %s", SDL_GetError());
		return 1;
	}

	GLuint texture = 0;
	glGenTextures(1, &texture);
	{
		glBindTexture(GL_TEXTURE_2D, texture); // All texture functions will now operate on this texture

		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); // X wrapping
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // Y wrapping

		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); // Far away
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // Close up

		// Use GL_BGR because bitmaps are silly
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, image->w, image->h, 0, GL_BGR, GL_UNSIGNED_BYTE, image->pixels);
		SDL_FreeSurface(image);
	}
	glBindTexture(GL_TEXTURE_2D, 0); // Unbind

	for(GLenum err; (err = glGetError()) != GL_NO_ERROR;) {
		SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "OpenGL Init: 0x%x", err);
	}

	bool running = true;
	SDL_Event event;

	float current = SDL_GetTicks();
	float last = current;
	float interval = 1000 / 60;

	while (running) {

		// Limit frame rate
		current = SDL_GetTicks();

		float dt = current - last;

		if (dt < interval) {
			SDL_Delay(interval - dt);
			continue;
		}

		last = current;

		// Input
		while(SDL_PollEvent(&event)) {
			if (event.type == SDL_QUIT) {
				running = false;
				break;
			}

			if (event.type == SDL_WINDOWEVENT && event.window.event == SDL_WINDOWEVENT_RESIZED) {
				int x = event.window.data1;
				int y = event.window.data2;
				glViewport(0, 0, x, y);
			}
		}

		r = (r + 2) % (255 * 2);
		g = (g + 4) % (255 * 2);
		b = (b + 8) % (255 * 2);

		//Rendering
		glClearColor((float)PingPong(r, 255) / 255, (float)PingPong(g, 255) / 255, (float)PingPong(b, 255) / 255, 1.0f);
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

		// Draw Triangle
		glUseProgram(shaderProgram);

		// Bind texture
		glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, texture);
        glUniform1i(glGetUniformLocation(shaderProgram, "ourTexture"), 0);

		glBindVertexArray(VAO);
		glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
		glBindVertexArray(0);

		SDL_GL_SwapWindow(window);
	}
    // Properly de-allocate all resources once they've outlived their purpose
    glDeleteVertexArrays(1, &VAO);
    glDeleteBuffers(1, &VBO);
    glDeleteBuffers(1, &EBO);
	return 0;
}<commit_msg>Colours are properly working.<commit_after>#include <SDL.h>
#include <vector>

#include "opengl.h"

int Abs(int num) {
	return num > 0 ? num : -num;
}

int PingPong(int num, int length) {
	return length - Abs((num % (length * 2)) - length);
}

int main() {

	const int WindowWidth = 720;
	const int WindowHeight = 720;

	if (SDL_Init(SDL_INIT_EVERYTHING)) {
		SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: %s\n", SDL_GetError());
		return 1;
	}

	SDL_Window* window = SDL_CreateWindow("SDL OpenGL", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, WindowWidth, WindowHeight, SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE);
	if (!window) {
		SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: %s\n", SDL_GetError());
		return 1;
	}

	//// OpenGL Setup

	// Options
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);

	// Connect window
	SDL_GLContext context = SDL_GL_CreateContext(window);

	if (!context) {
		SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: %s\n", SDL_GetError());
		return 1;
	}

	OpenGL_Init();

	{
		int value = 0;
		SDL_GL_GetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, &value);
		SDL_Log("SDL_GL_CONTEXT_MAJOR_VERSION: %d\n", value);

		SDL_GL_GetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, &value);
		SDL_Log("SDL_GL_CONTEXT_MINOR_VERSION: %d\n", value);
	}

	int r = 0;
	int g = 0;
	int b = 0;
	glViewport(0, 0, WindowWidth, WindowHeight);
	glClearColor(0.39f, 0.58f, 0.92f, 1.0f);

	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

	// Shaders
	const GLchar* vertexShaderSource = "#version 330 core\n"
		"layout (location = 0) in vec3 position;\n"
		"layout (location = 1) in vec3 color;\n"
		"layout (location = 2) in vec2 texCoord;\n"
		"out vec3 ourColor;\n"
		"out vec2 TexCoord;\n"
		"void main()\n"
		"{\n"
		"gl_Position = vec4(position.x, position.y, position.z, 1.0);\n"
		"TexCoord = texCoord;\n"
		"ourColor = color;\n"
		"}\0";

	const GLchar* fragmentShaderSource = "#version 330 core\n"
		"in vec3 ourColor;\n"
		"in vec2 TexCoord;\n"
		"out vec4 color;\n"
		"uniform sampler2D ourTexture;\n"
		"void main()\n"
		"{\n"
		"color = texture(ourTexture, TexCoord);\n"
		"color.rgb *= ourColor;\n"
		"}\n\0";

	GLint success;
	GLchar logBuffer[512];

	// Vertex
	GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
	glShaderSource(vertexShader, 1, &vertexShaderSource, NULL);
	glCompileShader(vertexShader);

	glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success);
	if (!success) {
		glGetShaderInfoLog(vertexShader, 512, NULL, logBuffer);
		SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Vertex Compile Error: %s", logBuffer);
	}

	// Fragment
	GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
	glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL);
	glCompileShader(fragmentShader);

	glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success);
	if (!success) {
		glGetShaderInfoLog(fragmentShader, 512, NULL, logBuffer);
		SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Fragment Compile Error: %s", logBuffer);
	}

	// Program
	GLuint shaderProgram = glCreateProgram();
	glAttachShader(shaderProgram, vertexShader);
	glAttachShader(shaderProgram, fragmentShader);
	glLinkProgram(shaderProgram);

	glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success);
	if (!success) {
		glGetProgramInfoLog(shaderProgram, 512, NULL, logBuffer);
		SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Shader Linking Error: %s", logBuffer);
	}

	glDeleteShader(vertexShader);
	glDeleteShader(fragmentShader);

	//glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);

	GLfloat vertices[] = {
		// Positions          // Colors           	  // Texture Coords
		0.5f,  0.5f, 0.0f,   1.0f, 1.0f, 1.0f,   1.0f, 1.0f, // Top Right
		0.5f, -0.5f, 0.0f,   1.0f, 1.0f, 1.0f,   1.0f, 0.0f, // Bottom Right
		-0.5f, -0.5f, 0.0f,   1.0f, 1.0f, 1.0f,   0.0f, 0.0f, // Bottom Left
		-0.5f,  0.5f, 0.0f,   1.0f, 1.0f, 1.0f,   0.0f, 1.0f  // Top Left
    };

	GLuint indices[] = {
        0, 1, 3,
        1, 2, 3,
	};

    GLuint VBO, VAO, EBO;
    glGenVertexArrays(1, &VAO);
    glGenBuffers(1, &VBO);
    glGenBuffers(1, &EBO);

    // Bind the Vertex Array Object first, then bind and set vertex buffer(s) and attribute pointer(s).
    glBindVertexArray(VAO);
	{
		// Now the VBO..
		glBindBuffer(GL_ARRAY_BUFFER, VBO);
		glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

		// Finally the EBO
		glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
		glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);

		// Vertex Attributes

		glVertexAttribPointer(0, // Layout
							3, // Size
							GL_FLOAT, // Type
							GL_FALSE, // Normalised
							8 * sizeof(GLfloat), // Stride
							(void*) 0); // Array Buffer Offset
		glEnableVertexAttribArray(0);

		glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
		glEnableVertexAttribArray(1);

		glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(6 * sizeof(GLfloat)));
		glEnableVertexAttribArray(2);
	}

	glBindVertexArray(0);

	// Texture loading

	SDL_Surface* image = SDL_LoadBMP("texture.bmp");
	if (!image) {
		SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Unable to load texture.bmp! %s", SDL_GetError());
		return 1;
	}

	GLuint texture = 0;
	glGenTextures(1, &texture);
	{
		glBindTexture(GL_TEXTURE_2D, texture); // All texture functions will now operate on this texture

		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); // X wrapping
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // Y wrapping

		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); // Far away
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // Close up

		// Use GL_BGR because bitmaps are silly
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, image->w, image->h, 0, GL_BGR, GL_UNSIGNED_BYTE, image->pixels);
		SDL_FreeSurface(image);
	}
	glBindTexture(GL_TEXTURE_2D, 0); // Unbind

	for(GLenum err; (err = glGetError()) != GL_NO_ERROR;) {
		SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "OpenGL Init: 0x%x", err);
	}

	bool running = true;
	SDL_Event event;

	float current = SDL_GetTicks();
	float last = current;
	float interval = 1000 / 60;

	while (running) {

		// Limit frame rate
		current = SDL_GetTicks();

		float dt = current - last;

		if (dt < interval) {
			SDL_Delay(interval - dt);
			continue;
		}

		last = current;

		// Input
		while(SDL_PollEvent(&event)) {
			if (event.type == SDL_QUIT) {
				running = false;
				break;
			}

			if (event.type == SDL_WINDOWEVENT && event.window.event == SDL_WINDOWEVENT_RESIZED) {
				int x = event.window.data1;
				int y = event.window.data2;
				glViewport(0, 0, x, y);
			}
		}

		r = (r + 2) % (255 * 2);
		g = (g + 4) % (255 * 2);
		b = (b + 8) % (255 * 2);

		//Rendering
		glClearColor((float)PingPong(r, 255) / 255, (float)PingPong(g, 255) / 255, (float)PingPong(b, 255) / 255, 1.0f);
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

		// Draw Triangle
		glUseProgram(shaderProgram);

		// Bind texture
		glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, texture);
        glUniform1i(glGetUniformLocation(shaderProgram, "ourTexture"), 0);

		glBindVertexArray(VAO);
		glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
		glBindVertexArray(0);

		SDL_GL_SwapWindow(window);
	}
    // Properly de-allocate all resources once they've outlived their purpose
    glDeleteVertexArrays(1, &VAO);
    glDeleteBuffers(1, &VBO);
    glDeleteBuffers(1, &EBO);
	return 0;
}<|endoftext|>


<commit_before>8e9bbfc7-4b02-11e5-821d-28cfe9171a43<commit_msg>Stuff changed<commit_after>8ea62402-4b02-11e5-83df-28cfe9171a43<|endoftext|>


<commit_before>/*
 * noice - ...
 * Copyright (C) 2016 Filipe Coelho <falktx@falktx.com>
 *
 * Permission to use, copy, modify, and/or distribute this software for any purpose with
 * or without fee is hereby granted, provided that the above copyright notice and this
 * permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
 * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN
 * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
 * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
 * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <cstdio>
#include <cstring>

#include <fcntl.h>
#include <signal.h>
#include <unistd.h>

// --------------------------------------------------------------------------------------------------------------------

#include "devices/guitarhero.hpp"
#include "devices/ps3.hpp"
#include "devices/ps4.hpp"

// --------------------------------------------------------------------------------------------------------------------

static const int kJoystickAnalogStart = 0;
static const int kJoystickAnalogEnd   = 7;
static const int kJoystickButtonStart = 8;
static const int kJoystickButtonEnd   = 63;
static const int kJoystickMaxAnalog   = kJoystickAnalogEnd-kJoystickAnalogStart;
static const int kJoystickMaxButton   = kJoystickButtonEnd-kJoystickButtonStart;

// --------------------------------------------------------------------------------------------------------------------

struct js_event {
    unsigned int time;      /* event timestamp in milliseconds */
    short value;            /* value */
    unsigned char type;     /* event type */
    unsigned char number;   /* axis/button number */
};

JackData::JackData() noexcept
    : joystick(false),
      device(kNull),
      fd(-1),
      nr(-1),
      thread(0),
      client(nullptr),
      midiport(nullptr)
{
    pthread_mutex_init(&mutex, nullptr);
    std::memset(buf, 0, kBufSize);
    std::memset(oldbuf, 0, kBufSize);
}

JackData::~JackData()
{
    if (client != nullptr)
    {
        jack_deactivate(client);
        jack_client_close(client);
    }

    if (fd >= 0)
        close(fd);

    pthread_mutex_destroy(&mutex);
}

// --------------------------------------------------------------------------------------------------------------------

static void shutdown_callback(void* const arg)
{
    JackData* const jackdata = (JackData*)arg;

    jackdata->client = nullptr;
}

static int process_callback(const jack_nframes_t frames, void* const arg)
{
    JackData* const jackdata = (JackData*)arg;

    // try lock asap, not fatal yet
    bool locked = pthread_mutex_trylock(&jackdata->mutex) == 0;

    // stack data
    unsigned char tmpbuf[JackData::kBufSize];

    // get jack midi port buffer
    void* const midibuf = jack_port_get_buffer(jackdata->midiport, frames);
    jack_midi_clear_buffer(midibuf);

    // try lock again
    if (! locked)
    {
        locked = pthread_mutex_trylock(&jackdata->mutex) == 0;

        // could not try-lock until here, stop
        if (! locked)
            return 0;
    }

    // copy buf data into a temp location so we can release the lock
    std::memcpy(tmpbuf, jackdata->buf, jackdata->nr);
    pthread_mutex_unlock(&jackdata->mutex);

    switch (jackdata->device)
    {
    case JackData::kNull:
        break;
    case JackData::kDualShock3:
        PS3::process(jackdata, midibuf, tmpbuf);
        break;
    case JackData::kDualShock4:
        PS4::process(jackdata, midibuf, tmpbuf);
        break;
    case JackData::kGuitarHero:
        GuitarHero::process(jackdata, midibuf, tmpbuf);
        break;
    }

    // cache current buf for comparison on next call
    std::memcpy(jackdata->oldbuf, tmpbuf, jackdata->nr);
    return 0;
}

// --------------------------------------------------------------------------------------------------------------------

static bool noice_init(JackData* const jackdata, const char* const device)
{
    if (device == nullptr || device[0] == '\0')
        return false;

    int nr;
    unsigned char buf[JackData::kBufSize];

    jackdata->joystick = strncmp(device, "/dev/input/js", 13) == 0;

    if ((jackdata->fd = open(device, O_RDONLY)) < 0)
    {
        fprintf(stderr, "noice::open(\"%s\") - failed to open hidraw device\n", device);
        return false;
    }

    const char* const deviceNum = device+(strlen(device)-1);

    if ((nr = read(jackdata->fd, buf, jackdata->joystick ? sizeof(js_event) : JackData::kBufSize)) < 0)
    {
        fprintf(stderr, "noice::read(%i) - failed to read from device\n", jackdata->fd);
        return false;
    }

    printf("noice::read(%i) - nr = %d\n", jackdata->fd, nr);

    if (jackdata->joystick)
    {
        if (nr != sizeof(js_event))
        {
            fprintf(stderr, "noice::read(%i) - failed to read device (nr = %d)\n", jackdata->fd, nr);
            return false;
        }

        memset(buf, 0, JackData::kBufSize);

        // TODO - ask joystick to know what it is
        jackdata->device = JackData::kGuitarHero;
        jackdata->nr = 9;
    }
    else
    {
        switch (nr)
        {
        case 49:
            jackdata->device = JackData::kDualShock3;
            break;
        case 64:
            jackdata->device = JackData::kDualShock4;
            break;
        default:
            fprintf(stderr, "noice::read(%i) - unsuppported device (nr = %d)\n", jackdata->fd, nr);
            return false;
        }

        jackdata->nr = nr;
    }

    char tmpName[32];
    std::strcpy(tmpName, "noice");
    std::strcat(tmpName, deviceNum);

    if (jackdata->client == nullptr)
    {
        jackdata->client = jack_client_open(tmpName, JackNoStartServer, nullptr);

        if (jackdata->client == nullptr)
        {
            fprintf(stderr, "noice:: failed to register jack client\n");
            return false;
        }
    }

    std::strcpy(tmpName, "noice_capture_");
    std::strcat(tmpName, deviceNum);

    jackdata->midiport = jack_port_register(jackdata->client, tmpName, JACK_DEFAULT_MIDI_TYPE, JackPortIsOutput|JackPortIsPhysical|JackPortIsTerminal, 0);

    if (jackdata->midiport == nullptr)
    {
        fprintf(stderr, "noice:: failed to register jack midi port\n");
        return false;
    }

    switch (jackdata->device)
    {
    case JackData::kNull:
        break;
    case JackData::kDualShock3:
        jack_port_set_alias(jackdata->midiport, "PS3 DualShock");
        break;
    case JackData::kDualShock4:
        jack_port_set_alias(jackdata->midiport, "PS4 DualShock");
        break;
    case JackData::kGuitarHero:
        jack_port_set_alias(jackdata->midiport, "Guitar Hero");
        break;
    }

    std::memcpy(jackdata->buf, buf, jackdata->nr);

    jack_on_shutdown(jackdata->client, shutdown_callback, jackdata);
    jack_set_process_callback(jackdata->client, process_callback, jackdata);
    jack_activate(jackdata->client);

    return true;
}

static bool noice_idle(JackData* const jackdata, unsigned char buf[JackData::kBufSize])
{
    if (jackdata->client == nullptr)
        return false;

    if (jackdata->joystick)
    {
        js_event ev;
        const int nr = read(jackdata->fd, &ev, sizeof(js_event));

        if (nr != sizeof(js_event))
        {
            fprintf(stderr, "noice::read(%i, buf) - failed to read from device (nr: %d)\n", jackdata->nr, nr);
            jack_deactivate(jackdata->client);
            return false;
        }

        // ignore synthetic events
        ev.type &= ~0x80;

        // put data into buf to simulate a raw device
        switch (ev.type)
        {
        case 1: { // button
            if (ev.number > kJoystickMaxButton)
                break;
            if (jackdata->device == JackData::kGuitarHero && ev.number > 5)
                --ev.number;

            const int mask = 1 << ev.number;
            const int offs = kJoystickButtonStart + (ev.number / 8);

            if (ev.value)
                buf[offs] |= mask;
            else
                buf[offs] &= ~mask;
            break;
        }
        case 2: { // axis
            if (ev.number > kJoystickMaxAnalog)
                break;
            const int offs = kJoystickAnalogStart + ev.number;

            buf[offs] = (ev.value + 32767) / 256;
            break;
        }
        }
    }
    else
    {
        const int nr = read(jackdata->fd, buf, jackdata->nr);

        if (nr != jackdata->nr)
        {
            fprintf(stderr, "noice::read(%i, buf) - failed to read from device (nr: %d)\n", jackdata->nr, nr);
            jack_deactivate(jackdata->client);
            return false;
        }
    }

    pthread_mutex_lock(&jackdata->mutex);
    std::memcpy(jackdata->buf, buf, jackdata->nr);
    pthread_mutex_unlock(&jackdata->mutex);

#if 0
        printf("\n==========================================\n");
        for (int j=0; j<jackdata->nr; j++)
        {
            printf("%02X ", buf[j]);

            if ((j+1) % 16 == 0)
                printf("\n");
        }
#endif

    return true;
}

// --------------------------------------------------------------------------------------------------------------------

static volatile bool gRunning;

static void signalHandler(int)
{
    gRunning = false;
}

int main(int argc, char **argv)
{
    if (argc < 2)
    {
        printf("Usage: %s /dev/hidrawX|/dev/input/jsX\n", argv[0]);
        return 1;
    }

    JackData jackdata;

    if (! noice_init(&jackdata, argv[1]))
        return 1;

    gRunning = true;

    struct sigaction sig;
    sig.sa_handler  = signalHandler;
    sig.sa_flags    = SA_RESTART;
    sig.sa_restorer = nullptr;
    sigemptyset(&sig.sa_mask);
    sigaction(SIGINT,  &sig, nullptr);
    sigaction(SIGTERM, &sig, nullptr);

    unsigned char buf[JackData::kBufSize];
    memset(buf, 0, JackData::kBufSize);
    while (gRunning && noice_idle(&jackdata, buf)) {}

    return 0;
}

// --------------------------------------------------------------------------------------------------------------------

static void* gInternalClientRun(void* arg)
{
    JackData* const jackdata = (JackData*)arg;

    unsigned char buf[JackData::kBufSize];
    memset(buf, 0, JackData::kBufSize);
    while (noice_idle(jackdata, buf)) {}

    return nullptr;
}

extern "C" __attribute__ ((visibility("default")))
int jack_initialize(jack_client_t* client, const char* load_init);

int jack_initialize(jack_client_t* client, const char* load_init)
{
    JackData* const jackdata = new JackData();

    jackdata->client = client;
    if (! noice_init(jackdata, load_init))
        return 1;

    pthread_create(&jackdata->thread, nullptr, gInternalClientRun, jackdata);
    return 0;
}

extern "C" __attribute__ ((visibility("default")))
void jack_finish(void* arg);

void jack_finish(void* arg)
{
    if (arg == nullptr)
        return;

    JackData* const jackdata = (JackData*)arg;

    jackdata->client = nullptr;
    pthread_join(jackdata->thread, nullptr);

    delete jackdata;
}

// --------------------------------------------------------------------------------------------------------------------
<commit_msg>Prevent conflicts between js and hidraw used at the same time<commit_after>/*
 * noice - ...
 * Copyright (C) 2016 Filipe Coelho <falktx@falktx.com>
 *
 * Permission to use, copy, modify, and/or distribute this software for any purpose with
 * or without fee is hereby granted, provided that the above copyright notice and this
 * permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
 * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN
 * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
 * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
 * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <cstdio>
#include <cstring>

#include <fcntl.h>
#include <signal.h>
#include <unistd.h>

// --------------------------------------------------------------------------------------------------------------------

#include "devices/guitarhero.hpp"
#include "devices/ps3.hpp"
#include "devices/ps4.hpp"

// --------------------------------------------------------------------------------------------------------------------

static const int kJoystickAnalogStart = 0;
static const int kJoystickAnalogEnd   = 7;
static const int kJoystickButtonStart = 8;
static const int kJoystickButtonEnd   = 63;
static const int kJoystickMaxAnalog   = kJoystickAnalogEnd-kJoystickAnalogStart;
static const int kJoystickMaxButton   = kJoystickButtonEnd-kJoystickButtonStart;

// --------------------------------------------------------------------------------------------------------------------

struct js_event {
    unsigned int time;      /* event timestamp in milliseconds */
    short value;            /* value */
    unsigned char type;     /* event type */
    unsigned char number;   /* axis/button number */
};

JackData::JackData() noexcept
    : joystick(false),
      device(kNull),
      fd(-1),
      nr(-1),
      thread(0),
      client(nullptr),
      midiport(nullptr)
{
    pthread_mutex_init(&mutex, nullptr);
    std::memset(buf, 0, kBufSize);
    std::memset(oldbuf, 0, kBufSize);
}

JackData::~JackData()
{
    if (client != nullptr)
    {
        jack_deactivate(client);
        jack_client_close(client);
    }

    if (fd >= 0)
        close(fd);

    pthread_mutex_destroy(&mutex);
}

// --------------------------------------------------------------------------------------------------------------------

static void shutdown_callback(void* const arg)
{
    JackData* const jackdata = (JackData*)arg;

    jackdata->client = nullptr;
}

static int process_callback(const jack_nframes_t frames, void* const arg)
{
    JackData* const jackdata = (JackData*)arg;

    // try lock asap, not fatal yet
    bool locked = pthread_mutex_trylock(&jackdata->mutex) == 0;

    // stack data
    unsigned char tmpbuf[JackData::kBufSize];

    // get jack midi port buffer
    void* const midibuf = jack_port_get_buffer(jackdata->midiport, frames);
    jack_midi_clear_buffer(midibuf);

    // try lock again
    if (! locked)
    {
        locked = pthread_mutex_trylock(&jackdata->mutex) == 0;

        // could not try-lock until here, stop
        if (! locked)
            return 0;
    }

    // copy buf data into a temp location so we can release the lock
    std::memcpy(tmpbuf, jackdata->buf, jackdata->nr);
    pthread_mutex_unlock(&jackdata->mutex);

    switch (jackdata->device)
    {
    case JackData::kNull:
        break;
    case JackData::kDualShock3:
        PS3::process(jackdata, midibuf, tmpbuf);
        break;
    case JackData::kDualShock4:
        PS4::process(jackdata, midibuf, tmpbuf);
        break;
    case JackData::kGuitarHero:
        GuitarHero::process(jackdata, midibuf, tmpbuf);
        break;
    }

    // cache current buf for comparison on next call
    std::memcpy(jackdata->oldbuf, tmpbuf, jackdata->nr);
    return 0;
}

// --------------------------------------------------------------------------------------------------------------------

static bool noice_init(JackData* const jackdata, const char* const device)
{
    if (device == nullptr || device[0] == '\0')
        return false;

    int nr;
    unsigned char buf[JackData::kBufSize];

    jackdata->joystick = strncmp(device, "/dev/input/js", 13) == 0;

    if ((jackdata->fd = open(device, O_RDONLY)) < 0)
    {
        fprintf(stderr, "noice::open(\"%s\") - failed to open hidraw device\n", device);
        return false;
    }

    int deviceNum = atoi(device+(strlen(device)-1));

    if ((nr = read(jackdata->fd, buf, jackdata->joystick ? sizeof(js_event) : JackData::kBufSize)) < 0)
    {
        fprintf(stderr, "noice::read(%i) - failed to read from device\n", jackdata->fd);
        return false;
    }

    printf("noice::read(%i) - nr = %d\n", jackdata->fd, nr);

    if (jackdata->joystick)
    {
        if (nr != sizeof(js_event))
        {
            fprintf(stderr, "noice::read(%i) - failed to read device (nr = %d)\n", jackdata->fd, nr);
            return false;
        }

        memset(buf, 0, JackData::kBufSize);

        // TODO - ask joystick to know what it is
        jackdata->device = JackData::kGuitarHero;
        jackdata->nr = 9;
        deviceNum += 20;
    }
    else
    {
        switch (nr)
        {
        case 49:
            jackdata->device = JackData::kDualShock3;
            break;
        case 64:
            jackdata->device = JackData::kDualShock4;
            break;
        default:
            fprintf(stderr, "noice::read(%i) - unsuppported device (nr = %d)\n", jackdata->fd, nr);
            return false;
        }

        jackdata->nr = nr;
    }

    char tmpName[32];
    std::snprintf(tmpName, 32, "noice%i", deviceNum);

    if (jackdata->client == nullptr)
    {
        jackdata->client = jack_client_open(tmpName, JackNoStartServer, nullptr);

        if (jackdata->client == nullptr)
        {
            fprintf(stderr, "noice:: failed to register jack client\n");
            return false;
        }
    }

    std::snprintf(tmpName, 32, "noice_capture_%i", deviceNum);

    jackdata->midiport = jack_port_register(jackdata->client, tmpName, JACK_DEFAULT_MIDI_TYPE, JackPortIsOutput|JackPortIsPhysical|JackPortIsTerminal, 0);

    if (jackdata->midiport == nullptr)
    {
        fprintf(stderr, "noice:: failed to register jack midi port\n");
        return false;
    }

    switch (jackdata->device)
    {
    case JackData::kNull:
        break;
    case JackData::kDualShock3:
        jack_port_set_alias(jackdata->midiport, "PS3 DualShock");
        break;
    case JackData::kDualShock4:
        jack_port_set_alias(jackdata->midiport, "PS4 DualShock");
        break;
    case JackData::kGuitarHero:
        jack_port_set_alias(jackdata->midiport, "Guitar Hero");
        break;
    }

    std::memcpy(jackdata->buf, buf, jackdata->nr);

    jack_on_shutdown(jackdata->client, shutdown_callback, jackdata);
    jack_set_process_callback(jackdata->client, process_callback, jackdata);
    jack_activate(jackdata->client);

    return true;
}

static bool noice_idle(JackData* const jackdata, unsigned char buf[JackData::kBufSize])
{
    if (jackdata->client == nullptr)
        return false;

    if (jackdata->joystick)
    {
        js_event ev;
        const int nr = read(jackdata->fd, &ev, sizeof(js_event));

        if (nr != sizeof(js_event))
        {
            fprintf(stderr, "noice::read(%i, buf) - failed to read from device (nr: %d)\n", jackdata->nr, nr);
            jack_deactivate(jackdata->client);
            return false;
        }

        // ignore synthetic events
        ev.type &= ~0x80;

        // put data into buf to simulate a raw device
        switch (ev.type)
        {
        case 1: { // button
            if (ev.number > kJoystickMaxButton)
                break;
            if (jackdata->device == JackData::kGuitarHero && ev.number > 5)
                --ev.number;

            const int mask = 1 << ev.number;
            const int offs = kJoystickButtonStart + (ev.number / 8);

            if (ev.value)
                buf[offs] |= mask;
            else
                buf[offs] &= ~mask;
            break;
        }
        case 2: { // axis
            if (ev.number > kJoystickMaxAnalog)
                break;
            const int offs = kJoystickAnalogStart + ev.number;

            buf[offs] = (ev.value + 32767) / 256;
            break;
        }
        }
    }
    else
    {
        const int nr = read(jackdata->fd, buf, jackdata->nr);

        if (nr != jackdata->nr)
        {
            fprintf(stderr, "noice::read(%i, buf) - failed to read from device (nr: %d)\n", jackdata->nr, nr);
            jack_deactivate(jackdata->client);
            return false;
        }
    }

    pthread_mutex_lock(&jackdata->mutex);
    std::memcpy(jackdata->buf, buf, jackdata->nr);
    pthread_mutex_unlock(&jackdata->mutex);

#if 0
        printf("\n==========================================\n");
        for (int j=0; j<jackdata->nr; j++)
        {
            printf("%02X ", buf[j]);

            if ((j+1) % 16 == 0)
                printf("\n");
        }
#endif

    return true;
}

// --------------------------------------------------------------------------------------------------------------------

static volatile bool gRunning;

static void signalHandler(int)
{
    gRunning = false;
}

int main(int argc, char **argv)
{
    if (argc < 2)
    {
        printf("Usage: %s /dev/hidrawX|/dev/input/jsX\n", argv[0]);
        return 1;
    }

    JackData jackdata;

    if (! noice_init(&jackdata, argv[1]))
        return 1;

    gRunning = true;

    struct sigaction sig;
    sig.sa_handler  = signalHandler;
    sig.sa_flags    = SA_RESTART;
    sig.sa_restorer = nullptr;
    sigemptyset(&sig.sa_mask);
    sigaction(SIGINT,  &sig, nullptr);
    sigaction(SIGTERM, &sig, nullptr);

    unsigned char buf[JackData::kBufSize];
    memset(buf, 0, JackData::kBufSize);
    while (gRunning && noice_idle(&jackdata, buf)) {}

    return 0;
}

// --------------------------------------------------------------------------------------------------------------------

static void* gInternalClientRun(void* arg)
{
    JackData* const jackdata = (JackData*)arg;

    unsigned char buf[JackData::kBufSize];
    memset(buf, 0, JackData::kBufSize);
    while (noice_idle(jackdata, buf)) {}

    return nullptr;
}

extern "C" __attribute__ ((visibility("default")))
int jack_initialize(jack_client_t* client, const char* load_init);

int jack_initialize(jack_client_t* client, const char* load_init)
{
    JackData* const jackdata = new JackData();

    jackdata->client = client;
    if (! noice_init(jackdata, load_init))
        return 1;

    pthread_create(&jackdata->thread, nullptr, gInternalClientRun, jackdata);
    return 0;
}

extern "C" __attribute__ ((visibility("default")))
void jack_finish(void* arg);

void jack_finish(void* arg)
{
    if (arg == nullptr)
        return;

    JackData* const jackdata = (JackData*)arg;

    jackdata->client = nullptr;
    pthread_join(jackdata->thread, nullptr);

    delete jackdata;
}

// --------------------------------------------------------------------------------------------------------------------
<|endoftext|>


<commit_before>#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <stdlib.h>
#include <stdio.h>

static void error_callback(int error, const char* description)
{
    fputs(description, stderr);
}
static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
    if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
	glfwSetWindowShouldClose(window, GL_TRUE);
}
int main(void)
{

    GLFWwindow* window;
    glfwSetErrorCallback(error_callback);
    if (!glfwInit())
	exit(EXIT_FAILURE);
    window = glfwCreateWindow(640, 480, "Simple example", NULL, NULL);
    if (!window)
    {
	glfwTerminate();
	exit(EXIT_FAILURE);
    }
    glfwMakeContextCurrent(window);
    glfwSetKeyCallback(window, key_callback);
    glewInit();

    while (!glfwWindowShouldClose(window))
    {
	float ratio;
	int width, height;
	glfwGetFramebufferSize(window, &width, &height);
	ratio = width / (float) height;
	glViewport(0, 0, width, height);
	glClear(GL_COLOR_BUFFER_BIT);
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glOrtho(-ratio, ratio, -1.f, 1.f, 1.f, -1.f);
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
	glRotatef((float) glfwGetTime() * 50.f, 0.f, 0.f, 1.f);
	glBegin(GL_TRIANGLES);
	glColor3f(1.f, 0.f, 0.f);
	glVertex3f(-0.6f, -0.4f, 0.f);
	glColor3f(0.f, 1.f, 0.f);
	glVertex3f(0.6f, -0.4f, 0.f);
	glColor3f(0.f, 0.f, 1.f);
	glVertex3f(0.f, 0.6f, 0.f);
	glEnd();
	glfwSwapBuffers(window);
	glfwPollEvents();
    }
    glfwDestroyWindow(window);
    glfwTerminate();
    exit(EXIT_SUCCESS);
}
<commit_msg>sfml main<commit_after>#include <SFML/Graphics.hpp>
//#include <GL/glew.h>
int main()
{
  	//  glewinit();
    sf::RenderWindow window(sf::VideoMode(200, 200), "SFML works!");
    sf::CircleShape shape(100.f);
    shape.setFillColor(sf::Color::Green);

    while (window.isOpen())
    {
	sf::Event event;
	while (window.pollEvent(event))
        {
	    if (event.type == sf::Event::Closed)
		window.close();
        }

	window.clear();
	window.draw(shape);
	window.display();
    }

    return 0;
}
<|endoftext|>


<commit_before>ff7c6235-2747-11e6-a85a-e0f84713e7b8<commit_msg>Deal with it<commit_after>ff8e486e-2747-11e6-8dc8-e0f84713e7b8<|endoftext|>


<commit_before>#include <sys/mman.h>
#include "asmtest.h"
#include "Operand-x86_64.h"
#include "Assembler-x86_64.h"
using namespace x86_64;

template<typename X, typename Y>
void print_mem(X* start, Y* end) {
	unsigned char* i = (unsigned char*)start;
	unsigned char* j = (unsigned char*)end;
	for (; i < j; ++i) {
		printf("0x%.2x ", *i);
	}
	puts("");
}

void say_hello() {
	printf("HELLO WORLD!\n");
}

int main (int argc, char const *argv[])
{
	Assembler masm;
	#define __ masm.

	__ enter();
	__ call("say_hello");
	__ call("count_up");
	__ inc(rax);
	__ leave();
	__ ret();

	__ define_symbol("count_up");
	__ enter();
	__ bin_xor(rax, rax);
	__ mov(Immediate(200), rbx);
	Assembler::Label loop_cond, loop_exit;
	__ bind(loop_cond);
	__ cmp(rax, rbx);
	__ j(CC_EQUAL, loop_exit);
	__ inc(rax);
	__ jmp(loop_cond);
	__ bind(loop_exit);
	__ leave();
	__ ret();

	unsigned char* code = (unsigned char*)valloc(masm.length());
	Assembler::SymbolTable table;
	table["say_hello"] = Assembler::Symbol((void*)say_hello);
	masm.compile_to(code, table);

	mprotect(code, masm.length(), PROT_EXEC);

	int(*func)(int a, int b) = (int(*)(int, int))code;
	printf("add: %d\n", func(6772, 2123));

	return 0;
}
<commit_msg>test relative offset call<commit_after>#include <sys/mman.h>
#include "asmtest.h"
#include "Operand-x86_64.h"
#include "Assembler-x86_64.h"
using namespace x86_64;

template<typename X, typename Y>
void print_mem(X* start, Y* end) {
	unsigned char* i = (unsigned char*)start;
	unsigned char* j = (unsigned char*)end;
	for (; i < j; ++i) {
		printf("0x%.2x ", *i);
	}
	puts("");
}

void say_hello() {
	printf("HELLO WORLD!\n");
}

int main (int argc, char const *argv[])
{
	Assembler masm;
	#define __ masm.

	__ enter();
	__ call("say_hello");
	__ call("count_up");
	__ inc(rax);
	__ leave();
	__ ret();

	Assembler::Symbol s = __ define_symbol("do_the_count_up");
	__ enter();
	__ bin_xor(rax, rax);
	__ mov(Immediate(200), rbx);
	Assembler::Label loop_cond, loop_exit;
	__ bind(loop_cond);
	__ cmp(rax, rbx);
	__ j(CC_EQUAL, loop_exit);
	__ inc(rax);
	__ jmp(loop_cond);
	__ bind(loop_exit);
	__ leave();
	__ ret();

	__ define_symbol("count_up");
	__ enter();
	__ call(s);
	__ leave();
	__ ret();

	unsigned char* code = (unsigned char*)valloc(masm.length());
	Assembler::SymbolTable table;
	table["say_hello"] = Assembler::Symbol((void*)say_hello);
	masm.compile_to(code, table);

	mprotect(code, masm.length(), PROT_EXEC);

	int(*func)(int a, int b) = (int(*)(int, int))code;
	printf("add: %d\n", func(6772, 2123));

	return 0;
}
<|endoftext|>


<commit_before>d64082a8-4b02-11e5-a4ce-28cfe9171a43<commit_msg>My Backup<commit_after>d650c391-4b02-11e5-af9e-28cfe9171a43<|endoftext|>


<commit_before>a804d06b-4b02-11e5-bb61-28cfe9171a43<commit_msg>My Backup<commit_after>a814673d-4b02-11e5-af45-28cfe9171a43<|endoftext|>


<commit_before>708fd78c-2749-11e6-b2b1-e0f84713e7b8<commit_msg>my cat is cute<commit_after>709ed94f-2749-11e6-80ee-e0f84713e7b8<|endoftext|>


<commit_before>#include <irrlicht/irrlicht.h>
#include <irrlicht/driverChoice.h>
#include "controlterm.cpp"

const char* disp = ":1";

//#pragma comment(lib, "Irrlicht.lib")

using namespace irr;
//using namespace core;
//using namespace scene;
//using namespace video;
//using namespace io;
//using namespace gui;
//
enum {
  ID_IsNotPickable = 0,

  IDFlag_IsSolid = 1 << 0,

  IDFlag_IsInteractable = 1 << 1
};

X11Display xdisp(disp);

class VREventReceiver : public IEventReceiver {
  public:
    virtual bool OnEvent(const SEvent& event){
      if(event.EventType == irr::EET_KEY_INPUT_EVENT){
        if(IsModKey(event.KeyInput.Key)){
          if(event.KeyInput.PressedDown){
            CurrentMod |= mapKeyCode(event.KeyInput.Key);
          } else {
            CurrentMod &= ~mapKeyCode(event.KeyInput.Key);
          }
        } else {
          KeyIsDown[event.KeyInput.Key] = event.KeyInput.PressedDown;
          xdisp.sendKeyEvent(mapKeyCode(event.KeyInput.Key), event.KeyInput.PressedDown, CurrentMod);
        }
      }
      return false;
    }
    virtual bool IsKeyDown(EKEY_CODE keyCode) const {
      return KeyIsDown[keyCode];
    }
  private:
    bool KeyIsDown[KEY_KEY_CODES_COUNT];
    // FIXME: can initialise to nonzero
    int CurrentMod;
};

int main() {
  // Uses driverChoiceConsole() from driverChoice.h

  VREventReceiver receiver;
  IrrlichtDevice *device = createDevice(driverChoiceConsole(), core::dimension2d<u32>(512, 384), 16, false, false, false, &receiver);
  device->setWindowCaption(L"Grimmware VRHackspace::Mk I");

  // set up video driver, scene manager and gui environment
  video::IVideoDriver* driver = device->getVideoDriver();
  scene::ISceneManager* smgr = device->getSceneManager();
  gui::IGUIEnvironment* guienv = device->getGUIEnvironment();

  video::SMaterial selectMaterial;
  selectMaterial.Wireframe = true;
  selectMaterial.Lighting = false;

  scene::IBillboardSceneNode * bill = smgr->addBillboardSceneNode();
  bill->setMaterialType(video::EMT_TRANSPARENT_ADD_COLOR );
  bill->setMaterialTexture(0, driver->getTexture("media/particle.jpg"));
  bill->setMaterialFlag(video::EMF_LIGHTING, false);
  bill->setMaterialFlag(video::EMF_ZBUFFER, false);
  bill->setSize(core::dimension2d<f32>(20.0f, 20.0f));
  bill->setID(ID_IsNotPickable); // This ensures that we don't accidentally ray-pick it

  scene::IMeshSceneNode *cube = smgr->addCubeSceneNode(15.0f, 0, -1, core::vector3df(10,-10,10), core::vector3df(0,0,0), core::vector3df(4, 4, 1));
  cube->setMaterialFlag(video::EMF_LIGHTING, true);
  if(cube){
    scene::ITriangleSelector* selector = smgr->createTriangleSelectorFromBoundingBox( cube );
    cube->setTriangleSelector( selector );
    selector->drop();
  }
  scene::ITriangleSelector* cubeSelector = cube->getTriangleSelector();

  // Create the level and the collision levelSelector
  device->getFileSystem()->addFileArchive("models/map-20kdm2.pk3");
  scene::IAnimatedMesh* levelMesh = smgr->getMesh("20kdm2.bsp");
  scene::IMeshSceneNode* levelNode = 0;
  scene::ITriangleSelector* levelSelector = 0;
  scene::IMetaTriangleSelector* cameraCollisionSelector =
    smgr->createMetaTriangleSelector();
  if (levelMesh) {
    levelNode = smgr->addOctreeSceneNode(levelMesh->getMesh(0), 0, IDFlag_IsSolid);
//      node = smgr->addMeshSceneNode(mesh->getMesh(0));
    if(levelNode){
      levelNode->setPosition(core::vector3df(-1350,-130,-1400));
      levelSelector = smgr->createOctreeTriangleSelector(
                 levelNode->getMesh(), levelNode, 128);
      cameraCollisionSelector->addTriangleSelector(levelSelector);
      cameraCollisionSelector->addTriangleSelector(cubeSelector);
      levelNode->setTriangleSelector(levelSelector);
    }
  }

  //Create camera and pin it to the floor
  scene::ICameraSceneNode *camera = smgr->addCameraSceneNodeFPS(0, 100.0f, .3f, ID_IsNotPickable, 0, 0, true, 3.f);
  camera->setPosition(core::vector3df(50,50,-60));

  //Add collision to the camera
  if (levelSelector) {
    scene::ISceneNodeAnimator* levelAnim = smgr->createCollisionResponseAnimator(
      cameraCollisionSelector, camera, core::vector3df(30,50,30),
      core::vector3df(0,-10,0), core::vector3df(0,30,0));
    levelSelector->drop(); // As soon as we're done with the levelSelector, drop it.
    camera->addAnimator(levelAnim);
    levelAnim->drop();  // And likewise, drop the animator when we're done referring to it.
  }

  device->getCursorControl()->setVisible(false);
  //camera->setTarget(cube->getAbsolutePosition());
  int lastFPS = -1;
  video::ITexture * texture;
  while(device->run()) {
    device->getVideoDriver()->removeTexture(texture);
    texture = driver->getTexture("/tmp/vrhs/shot.png");
    cube->setMaterialTexture(0, texture);
    // Make the pointy pointer thingy
    core::line3d<f32> ray;
    ray.start = camera->getPosition();
    ray.end = ray.start + (camera->getTarget() - ray.start).normalize() * 1000.0f;

    scene::ISceneCollisionManager* collMan = smgr->getSceneCollisionManager();

    core::vector3df intersection;
    core::triangle3df hitTriangle;

    driver->beginScene(true, true, video::SColor(255,100,101,140));
    scene::ISceneNode * selectedSceneNode =
      collMan->getSceneNodeAndCollisionPointFromRay(
          ray,
          intersection,
          hitTriangle,
          IDFlag_IsInteractable,
          0);

    if(selectedSceneNode)
    {
      bill->setPosition(intersection);
      driver->setTransform(video::ETS_WORLD, core::matrix4());
      driver->setMaterial(selectMaterial);
      driver->draw3DTriangle(hitTriangle, video::SColor(0, 255, 0, 0));
    }

    smgr->drawAll();
    guienv->drawAll();
    driver->endScene();
  }
  device->drop();
  return 0;

}
<commit_msg>Some weird shit<commit_after>#include <irrlicht/irrlicht.h>
#include <irrlicht/driverChoice.h>
#include "controlterm.cpp"

const char* disp = ":1";

//#pragma comment(lib, "Irrlicht.lib")

using namespace irr;
//using namespace core;
//using namespace scene;
//using namespace video;
//using namespace io;
//using namespace gui;
//
enum {
  ID_IsNotPickable = 0,

  IDFlag_IsSolid = 1 << 0,

  IDFlag_IsInteractable = 1 << 1
};

X11Display xdisp(disp);

class VREventReceiver : public IEventReceiver {
  public:
    virtual bool OnEvent(const SEvent& event){
      if(event.EventType == irr::EET_KEY_INPUT_EVENT){
        if(IsModKey(event.KeyInput.Key)){
          if(event.KeyInput.PressedDown){
            //FIXME: shit sometimes gets weird here
            CurrentMod |= mapKeyCode(event.KeyInput.Key);
          } else {
            CurrentMod &= ~mapKeyCode(event.KeyInput.Key);
          }
        } else {
          KeyIsDown[event.KeyInput.Key] = event.KeyInput.PressedDown;
          xdisp.sendKeyEvent(mapKeyCode(event.KeyInput.Key), event.KeyInput.PressedDown, CurrentMod);
        }
      }
      return false;
    }
    virtual bool IsKeyDown(EKEY_CODE keyCode) const {
      return KeyIsDown[keyCode];
    }
  private:
    bool KeyIsDown[KEY_KEY_CODES_COUNT];
    // FIXME: can initialise to nonzero
    int CurrentMod;
};

int main() {
  // Uses driverChoiceConsole() from driverChoice.h

  VREventReceiver receiver;
  IrrlichtDevice *device = createDevice(driverChoiceConsole(), core::dimension2d<u32>(512, 384), 16, false, false, false, &receiver);
  device->setWindowCaption(L"Grimmware VRHackspace::Mk I");

  // set up video driver, scene manager and gui environment
  video::IVideoDriver* driver = device->getVideoDriver();
  scene::ISceneManager* smgr = device->getSceneManager();
  gui::IGUIEnvironment* guienv = device->getGUIEnvironment();

  video::SMaterial selectMaterial;
  selectMaterial.Wireframe = true;
  selectMaterial.Lighting = false;

  scene::IBillboardSceneNode * bill = smgr->addBillboardSceneNode();
  bill->setMaterialType(video::EMT_TRANSPARENT_ADD_COLOR );
  bill->setMaterialTexture(0, driver->getTexture("media/particle.jpg"));
  bill->setMaterialFlag(video::EMF_LIGHTING, false);
  bill->setMaterialFlag(video::EMF_ZBUFFER, false);
  bill->setSize(core::dimension2d<f32>(20.0f, 20.0f));
  bill->setID(ID_IsNotPickable); // This ensures that we don't accidentally ray-pick it

  // Set up terminal
  scene::IMeshSceneNode *cube = smgr->addCubeSceneNode(15.0f, 0, -1, core::vector3df(10,-10,10), core::vector3df(0,0,0), core::vector3df(4, 4, 1));
  cube->setMaterialFlag(video::EMF_LIGHTING, true);
  if(cube){
    scene::ITriangleSelector* selector = smgr->createTriangleSelectorFromBoundingBox( cube );
    cube->setTriangleSelector( selector );
    selector->drop();
  }
  scene::ITriangleSelector* cubeSelector = cube->getTriangleSelector();

  // Add lighting
  scene::ISceneNode* light = smgr->addLightSceneNode(0, core::vector3df(10,20,20),
      video::SColorf(1.0f, 0.6f, 0.7f, 1.0f), 800.0f);

  scene::IMeshSceneNode *room = smgr->addCubeSceneNode(15.0f, 0, -1, core::vector3df(10,-10,10), core::vector3df(0,0,0), core::vector3df(30, 30, 30));
  smgr->getMeshManipulator()->flipSurfaces(room->getMesh());
  room->setMaterialFlag(video::EMF_LIGHTING, false);
  room->setMaterialTexture(0, driver->getTexture("media/texture.jpg"));
  room->setTriangleSelector(smgr->createTriangleSelector( room->getMesh(), room ));

  bool yesLevel = true;
  int collideablesNumber = 3;
  scene::ITriangleSelector* collideables[collideablesNumber];
  collideables[0] = cubeSelector;
  collideables[1] = room->getTriangleSelector();

  scene::IMetaTriangleSelector* cameraCollisionSelector =
    smgr->createMetaTriangleSelector();
  if(yesLevel){
    // Create the level and the collision levelSelector
    device->getFileSystem()->addFileArchive("models/map-20kdm2.pk3");
    scene::IAnimatedMesh* levelMesh = smgr->getMesh("20kdm2.bsp");
    scene::IMeshSceneNode* levelNode = 0;
    scene::ITriangleSelector* levelSelector = 0;
    if (levelMesh) {
      levelNode = smgr->addOctreeSceneNode(levelMesh->getMesh(0), 0, IDFlag_IsSolid);
//        node = smgr->addMeshSceneNode(mesh->getMesh(0));
      if(levelNode){
        levelNode->setMaterialFlag(video::EMF_LIGHTING, true);
        levelNode->setPosition(core::vector3df(-1350,-130,-1400));
        levelSelector = smgr->createOctreeTriangleSelector(
                   levelNode->getMesh(), levelNode, 128);
        collideables[2] = levelSelector;
        levelNode->setTriangleSelector(levelSelector);
        levelSelector->drop(); // As soon as we're done with the levelSelector, drop it.
      }
    }
  } else {
    collideablesNumber = 2;
  }
  for(int i=0; i<collideablesNumber; i++){
    cameraCollisionSelector->addTriangleSelector(collideables[i]);
  }

  //Create camera and pin it to the floor
  scene::ICameraSceneNode *camera = smgr->addCameraSceneNodeFPS(0, 100.0f, .3f, ID_IsNotPickable, 0, 0, true, 3.f);
  camera->setPosition(core::vector3df(50,50,-60));

  //Add collision to the camera
  scene::ISceneNodeAnimator* levelAnim = smgr->createCollisionResponseAnimator(
    cameraCollisionSelector, camera, core::vector3df(30,50,30),
    core::vector3df(0,-10,0), core::vector3df(0,30,0));
  camera->addAnimator(levelAnim);
  levelAnim->drop();  // And likewise, drop the animator when we're done referring to it.

  device->getCursorControl()->setVisible(false);
  //camera->setTarget(cube->getAbsolutePosition());
  int lastFPS = -1;
  video::ITexture * texture;
  scene::ISceneNode* lastSelectedSceneNode = NULL;
  while(device->run()) {
    device->getVideoDriver()->removeTexture(texture);
    texture = driver->getTexture("/tmp/vrhs/shot.png");
    cube->setMaterialTexture(0, texture);
    // Make the pointy pointer thingy
    core::line3d<f32> ray;
    ray.start = camera->getPosition();
    ray.end = ray.start + (camera->getTarget() - ray.start).normalize() * 1000.0f;

    scene::ISceneCollisionManager* collMan = smgr->getSceneCollisionManager();

    core::vector3df intersection;
    core::triangle3df hitTriangle;

    driver->beginScene(true, true, video::SColor(255,100,101,140));
    scene::ISceneNode * selectedSceneNode =
      collMan->getSceneNodeAndCollisionPointFromRay(
          ray,
          intersection,
          hitTriangle,
          IDFlag_IsInteractable,
          0);

    if(lastSelectedSceneNode) lastSelectedSceneNode->setMaterialFlag(video::EMF_LIGHTING, true);
    if(selectedSceneNode)
    {
      bill->setPosition(intersection);
      driver->setTransform(video::ETS_WORLD, core::matrix4());
      driver->setMaterial(selectMaterial);
      driver->draw3DTriangle(hitTriangle, video::SColor(0, 255, 0, 0));
      selectedSceneNode->setMaterialFlag(video::EMF_LIGHTING, false);
      lastSelectedSceneNode = selectedSceneNode;
    }

    smgr->drawAll();
    guienv->drawAll();
    driver->endScene();
  }
  device->drop();
  return 0;

}
<|endoftext|>


<commit_before>#include <iostream>
#include <string.h>
#include <stdio.h>
#include <vector>
#include <map>
#include <bits/stl_algo.h>
#include <bitset>
#include <fstream>
#include <chrono>

using namespace std;

typedef struct GraphTree {
    unsigned char symbol;
    unsigned char symbolExtended;
    unsigned long long int nrOfApp;
    GraphTree *parent;
    GraphTree *left;
    GraphTree *right;
    unsigned long long int index;
} ShannonTree;

typedef std::vector<GraphTree *> GraphIndex;

typedef std::map<int, std::pair<GraphTree *, std::string>> MappedSymbols;
typedef std::chrono::duration<int, std::milli> miliseconds_type;

typedef struct GraphSearch {
    std::string code;
    bool type;
    GraphTree *reference;
};

int ENCODE_BITS = 8;
int ESC_VALUE = 257;
int EOS_VALUE = 256;
MappedSymbols symbolMap;
GraphIndex indexedGraph;

auto
        cmp = [](std::pair<unsigned char, unsigned long int> const &a, std::pair<unsigned char, unsigned long int> const &b) {
    return a.second != b.second ? a.second > b.second : a.first < b.first;
};

GraphTree *initGraph() {

    GraphTree *parent, *left, *right;
    parent = new GraphTree;
    left = new GraphTree;
    right = new GraphTree;
    parent->symbol = 0;
    parent->symbolExtended = 0;
    parent->nrOfApp = 2;

    parent->parent = NULL;
    parent->left = left;
    parent->right = right;
    parent->index = 1;

    indexedGraph.push_back(parent);

    left->parent = parent;
    right->parent = parent;

    left->left = NULL;
    left->right = NULL;

    right->left = NULL;
    right->right = NULL;

    left->symbol = 255;
    left->symbolExtended = 1;

    right->symbol = 255;
    right->symbolExtended = 2;

    left->nrOfApp = 1;
    right->nrOfApp = 1;

    left->index = 2;
    right->index = 3;

    indexedGraph.push_back(left);
    indexedGraph.push_back(right);

    symbolMap[right->symbol + right->symbolExtended].first = right;
    symbolMap[right->symbol + right->symbolExtended].second = "1";

    symbolMap[left->symbol + left->symbolExtended].first = left;
    symbolMap[left->symbol + left->symbolExtended].second = "0";

    return parent;

}

/**
* find symbol in alphabet map, if it is first occurence for symbol return a reference for ESC symbol
*/
GraphSearch findSymbol(unsigned char symbol) {
    GraphSearch result;
    if (symbolMap.count(symbol) > 0) {
        result.code = symbolMap[symbol].second;
        result.type = true;
        result.reference = symbolMap[symbol].first;
    } else {
        result.code = symbolMap[ESC_VALUE].second;
        result.type = false;
        result.reference = symbolMap[ESC_VALUE].first;
    }
    return result;

}

void updateSymbol(GraphSearch result) {
    (result.reference)->nrOfApp = (result.reference)->nrOfApp + 1;
}

void addSymbol(GraphSearch result, unsigned char symbol) {
    GraphTree *left, *right;

    left = new GraphTree;
    left->nrOfApp = 1;
    left->right = NULL;
    left->left = NULL;
    left->symbol = symbol;
    left->symbolExtended = 0;
    left->parent = result.reference;
    left->index = (result.reference)->index + 1;

    right = new GraphTree;
    right->nrOfApp = 1;
    right->right = NULL;
    right->left = NULL;
    right->symbol = 255;
    right->symbolExtended = 2;
    right->parent = result.reference;
    right->index = (result.reference)->index + 2;

    (result.reference)->left = left;
    (result.reference)->right = right;
    (result.reference)->nrOfApp = 2;
    (result.reference)->symbol = 0;
    (result.reference)->symbolExtended = 0;

    indexedGraph.push_back(left);
    indexedGraph.push_back(right);

    symbolMap[ESC_VALUE].first = right;

}

void displayIndexedGraph() {
    GraphIndex::size_type iterator;
    for (iterator = 0; iterator < indexedGraph.size(); ++iterator) {
        std::cout << (indexedGraph[iterator])->nrOfApp << " " << (indexedGraph[iterator])->index << " -> " << iterator + 1 << "\n";
    }
}

void displayGraph(GraphTree *root) {
    if ((root->symbol + root->symbolExtended) == 0) {
        std::cout << "Pondere: " << root->nrOfApp << "\n";
        displayGraph(root->left);
        displayGraph(root->right);
    } else {
        std::cout << "Simbol: " << (root->symbol + root->symbolExtended) << "\n";
    }

}

void balanceGraph(GraphTree *node) {
    GraphTree *aux, *changeAux, *parent;
    GraphIndex::size_type iterator, auxIndex;

    for (iterator = node->index - 1; iterator > 0; iterator--) {
        if ((indexedGraph[iterator - 1])->nrOfApp >= node->nrOfApp) {
            break;
        }
    }
    if (iterator == node->index - 1) {
        node->parent->nrOfApp++;
        if (node->parent->parent != NULL) {
            balanceGraph(node->parent);
        }
        return void();
    }

    if (iterator == node->index - 2) {
        (indexedGraph[iterator - 1])->right = indexedGraph[iterator];
        (indexedGraph[iterator - 1])->left = node;
        indexedGraph[iterator]->index++;
        node->index--;
        indexedGraph[iterator] = node;
        indexedGraph[iterator + 1] = (indexedGraph[iterator - 1])->right;
        balanceGraph(node);
        return void();
    }

    if ((iterator - (node->index - 2)) > 0 && node->index - 2 >= 0) {
        aux = indexedGraph[iterator - 1];
        indexedGraph[iterator - 1] = node;
        auxIndex = node->index;
        parent = aux->parent;
        changeAux = node->parent;
        if (iterator % 2 == 0) {
            parent->left = node;
        } else {
            parent->right = node;
        }
        node->parent = parent;

        indexedGraph[auxIndex - 1] = aux;
        if (auxIndex % 2 == 0) {
            changeAux->left = node;
        } else {
            changeAux->right = node;
        }
        balanceGraph(indexedGraph[iterator - 1]);
        //return void();
    }
    //return void();
}

void encodeSymbol(unsigned char symbol, GraphTree *parent) {
    GraphSearch result;

    result = findSymbol(symbol);
    if (result.type == true) {
        updateSymbol(result);
    } else {
        addSymbol(result, symbol);
    }

    balanceGraph(result.reference);

}

void swapChild(GraphTree *root) {
    GraphTree *aux;
    aux = root->left;
    root->left = root->right;
    root->right = aux;
}

void balanceTree(GraphTree *root) {

    if ((root->symbol + root->symbolExtended) == 0) {
        if (root->left->nrOfApp < root->right->nrOfApp) {
            swapChild(root);
        }
    }
}

void encodeFile() {

}

void compressFile(std::string fileName) {

    GraphTree *huffmanTree;
    huffmanTree = initGraph();
    encodeSymbol('a', huffmanTree);
    encodeSymbol('b', huffmanTree);
    displayIndexedGraph();
    std::cout << "\n\n";
    displayGraph(huffmanTree);
//    balanceTree(huffmanTree);
//    encodeSymbol('b', huffmanTree);
//    balanceTree(huffmanTree);
//    std::cout << "\n\n";
//    displayGraph(huffmanTree);
}

void uncompressFile(std::string fileName) {

}

void displayOptions() {
    std::cout << "Alege fisierul!" << "\n\n Audio:\n";
    std::cout << "\t1.)instr_01.wav\n";
    std::cout << "\t2.)sound_01.wav\n";
    std::cout << "\t3.)speech_01.wav\n";
    std::cout << "\nDocuments:\n";
    std::cout << "\t4.)Documentatie_UMAPID.doc\n";
    std::cout << "\t5.)Documentatie_UMAPID.pdf\n";
    std::cout << "\t6.)Prefata_Undine.txt\n";
    std::cout << "\t7.)show_audio.m\n";
    std::cout << "\t8.)Y04.M\n";
    std::cout << "\nExecutables:\n";
    std::cout << "\t9.)KARMA_DATA482#1_5_V7.mat\n";
    std::cout << "\t10.)quartz.dll\n";
    std::cout << "\t11.)WinRar.exe\n";
    std::cout << "\t12.)WINZIP32.EXE\n";

}

std::ifstream::pos_type filesize(std::string fileName) {
    std::ifstream in(fileName.c_str(), std::ifstream::ate | std::ifstream::binary);
    return in.tellg();
}

void displayInformations(std::string fileName) {
    std::ifstream::pos_type compressedFileSize, fileSize, uncompressedFileSize;
    std::string compressedFileName, uncompressedFileName;

    compressedFileName = fileName + ".psh";
    uncompressedFileName = fileName + ".pshu";

    compressedFileSize = filesize(compressedFileName);
    fileSize = filesize(fileName);
    uncompressedFileSize = filesize(uncompressedFileName);

    std::cout << "Norma: " << (fileSize - uncompressedFileSize) * (fileSize - uncompressedFileSize) << "\n";
    std::cout << "Rata compresie: " << (1 - ((float) compressedFileSize) / ((float) uncompressedFileSize)) * 100 << "%\n";
    std::cout << "Factor compresie:  " << (((float) compressedFileSize) / ((float) fileSize)) * 100 << "%\n";

}

int main() {

    std::vector<std::string> files = {
            ".\\audio\\instr_01.wav",
            ".\\audio\\sound_01.wav",
            ".\\audio\\speech_01.wav",
            ".\\documents\\Documentatie_UMAPID.doc",
            ".\\documents\\Documentatie_UMAPID.pdf",
            ".\\documents\\Prefata_Undine.txt",
            ".\\documents\\show_audio.m",
            ".\\documents\\Y04.M",
            ".\\executables\\KARMA_DATA482#1_5_V7.mat",
            ".\\executables\\quartz.dll",
            ".\\executables\\WinRar.exe",
            ".\\executables\\WINZIP32.EXE",
            ".\\documents\\input.txt",
            "D:\\input.txt",
    };

    int option;
    //displayOptions();
    //std::cout << "Select file!..\n";
    //std::cin >> option;
//    if (option < 1 && option > 14) {
//        std::cout << "Invalid option!";
//        return 0;
//    }
    auto startC = std::chrono::high_resolution_clock::now();

    compressFile(files[2]);
    auto endC = std::chrono::high_resolution_clock::now();
    auto timeC = endC - startC;
    std::cout << "Compressed time: " << std::chrono::duration_cast<miliseconds_type>(timeC).count() << " miliseconds.\n";

    auto startU = std::chrono::high_resolution_clock::now();
//    uncompressFile(files[option - 1]);

    auto endU = std::chrono::high_resolution_clock::now();
    auto timeU = endU - startU;
    std::cout << "Uncompressed time: " << std::chrono::duration_cast<miliseconds_type>(timeU).count() << " miliseconds.\n";
//    displayInformations(files[option - 1]);

    //std::cin >> option;

    return 0;
}<commit_msg>update encodeSymbol method to work for "abc" string<commit_after>#include <iostream>
#include <string.h>
#include <stdio.h>
#include <vector>
#include <map>
#include <bits/stl_algo.h>
#include <bitset>
#include <fstream>
#include <chrono>

using namespace std;

typedef struct GraphTree {
    unsigned char symbol;
    unsigned char symbolExtended;
    unsigned long long int nrOfApp;
    GraphTree *parent;
    GraphTree *left;
    GraphTree *right;
    unsigned long long int index;
} ShannonTree;

typedef std::vector<GraphTree *> GraphIndex;

typedef std::map<int, std::pair<GraphTree *, std::string>> MappedSymbols;
typedef std::chrono::duration<int, std::milli> miliseconds_type;

typedef struct GraphSearch {
    std::string code;
    bool type;
    GraphTree *reference;
};

int ENCODE_BITS = 8;
int ESC_VALUE = 257;
int EOS_VALUE = 256;
MappedSymbols symbolMap;
GraphIndex indexedGraph;

auto
        cmp = [](std::pair<unsigned char, unsigned long int> const &a, std::pair<unsigned char, unsigned long int> const &b) {
    return a.second != b.second ? a.second > b.second : a.first < b.first;
};

GraphTree *initGraph() {

    GraphTree *parent, *left, *right;
    parent = new GraphTree;
    left = new GraphTree;
    right = new GraphTree;
    parent->symbol = 0;
    parent->symbolExtended = 0;
    parent->nrOfApp = 2;

    parent->parent = NULL;
    parent->left = left;
    parent->right = right;
    parent->index = 1;

    indexedGraph.push_back(parent);

    left->parent = parent;
    right->parent = parent;

    left->left = NULL;
    left->right = NULL;

    right->left = NULL;
    right->right = NULL;

    left->symbol = 255;
    left->symbolExtended = 1;

    right->symbol = 255;
    right->symbolExtended = 2;

    left->nrOfApp = 1;
    right->nrOfApp = 1;

    left->index = 2;
    right->index = 3;

    indexedGraph.push_back(left);
    indexedGraph.push_back(right);

    symbolMap[right->symbol + right->symbolExtended].first = right;
    symbolMap[right->symbol + right->symbolExtended].second = "1";

    symbolMap[left->symbol + left->symbolExtended].first = left;
    symbolMap[left->symbol + left->symbolExtended].second = "0";

    return parent;

}

/**
* find symbol in alphabet map, if it is first occurence for symbol return a reference for ESC symbol
*/
GraphSearch findSymbol(unsigned char symbol) {
    GraphSearch result;
    if (symbolMap.count(symbol) > 0) {
        result.code = symbolMap[symbol].second;
        result.type = true;
        result.reference = symbolMap[symbol].first;
    } else {
        result.code = symbolMap[ESC_VALUE].second;
        result.type = false;
        result.reference = symbolMap[ESC_VALUE].first;
    }
    return result;

}

void updateSymbol(GraphSearch result) {
    (result.reference)->nrOfApp = (result.reference)->nrOfApp + 1;
}

void addSymbol(GraphSearch result, unsigned char symbol) {
    GraphTree *left, *right;

    left = new GraphTree;
    left->nrOfApp = 1;
    left->right = NULL;
    left->left = NULL;
    left->symbol = symbol;
    left->symbolExtended = 0;
    left->parent = result.reference;
    left->index = (result.reference)->index + 1;

    right = new GraphTree;
    right->nrOfApp = 1;
    right->right = NULL;
    right->left = NULL;
    right->symbol = 255;
    right->symbolExtended = 2;
    right->parent = result.reference;
    right->index = (result.reference)->index + 2;

    (result.reference)->left = left;
    (result.reference)->right = right;
    (result.reference)->nrOfApp = 2;
    (result.reference)->symbol = 0;
    (result.reference)->symbolExtended = 0;

    indexedGraph.push_back(left);
    indexedGraph.push_back(right);

    symbolMap[ESC_VALUE].first = right;

}

void displayIndexedGraph() {
    GraphIndex::size_type iterator;
    for (iterator = 0; iterator < indexedGraph.size(); ++iterator) {
        std::cout << ((indexedGraph[iterator])->symbol + (indexedGraph[iterator])->symbolExtended) << " " << (indexedGraph[iterator])->index << " -> " << iterator + 1 << " " << (indexedGraph[iterator])->nrOfApp << "\n";
    }
    std::cout << "\n\n";
}

void displayGraph(GraphTree *root) {
    if ((root->symbol + root->symbolExtended) == 0) {
        std::cout << "Pondere: " << root->nrOfApp << "\n";
        displayGraph(root->left);
        displayGraph(root->right);
    } else {
        std::cout << "Simbol: " << (root->symbol + root->symbolExtended) << "\n";
    }

}

void balanceGraph(GraphTree *node) {
    GraphTree *aux, *changeAux, *parent;
    GraphIndex::size_type iterator, auxIndex;

    for (iterator = node->index - 1; iterator > 0; iterator--) {
        if ((indexedGraph[iterator - 1])->nrOfApp >= node->nrOfApp) {
            break;
        }
    }
    if (iterator == node->index - 1) {
        node->parent->nrOfApp++;
        if (node->parent->parent != NULL) {
            balanceGraph(node->parent);
        }
        return void();
    }

    if (iterator == node->index - 2) {
        (indexedGraph[iterator - 1])->right = indexedGraph[iterator];
        (indexedGraph[iterator - 1])->left = node;
        indexedGraph[iterator]->index++;
        node->index--;
        indexedGraph[iterator] = node;
        indexedGraph[iterator + 1] = (indexedGraph[iterator - 1])->right;
        balanceGraph(node);
        return void();
    }

    if ((iterator - (node->index - 2)) > 0 && node->index - 2 >= 0) {
        aux = indexedGraph[iterator];
        auxIndex = node->index;
        node->index = aux->index;
        aux->index = auxIndex;
        indexedGraph[iterator] = node;

        parent = aux->parent;
        changeAux = node->parent;
        if (iterator % 2 == 1) {
            parent->left = node;
        } else {
            parent->right = node;
        }
        node->parent = parent;

        indexedGraph[auxIndex - 1] = aux;
        if (auxIndex % 2 == 0) {
            changeAux->left = aux;
        } else {
            changeAux->right = aux;
        }
        balanceGraph(indexedGraph[iterator]);
        //return void();
    }
    //return void();
}

/**
* Update symbol map
*/
void updateMap() {
    int symbol;
    GraphIndex::size_type iterator;
    for (iterator = 0; iterator < indexedGraph.size(); iterator++) {
        symbol = indexedGraph[iterator]->symbolExtended + indexedGraph[iterator]->symbol;
        if (symbol > 0) {
            symbolMap[symbol].first = indexedGraph[iterator];
        }
    }
}

void encodeSymbol(unsigned char symbol, GraphTree *parent) {
    GraphSearch result;

    result = findSymbol(symbol);
    if (result.type == true) {
        updateSymbol(result);
    } else {
        addSymbol(result, symbol);
    }
    balanceGraph(result.reference);
    updateMap();

}

void swapChild(GraphTree *root) {
    GraphTree *aux;
    aux = root->left;
    root->left = root->right;
    root->right = aux;
}

void balanceTree(GraphTree *root) {

    if ((root->symbol + root->symbolExtended) == 0) {
        if (root->left->nrOfApp < root->right->nrOfApp) {
            swapChild(root);
        }
    }
}

void encodeFile() {

}

void compressFile(std::string fileName) {

    GraphTree *huffmanTree;
    huffmanTree = initGraph();
    encodeSymbol('a', huffmanTree);
    encodeSymbol('b', huffmanTree);
    encodeSymbol('c', huffmanTree);
    encodeSymbol('a', huffmanTree);
//    encodeSymbol('e', huffmanTree);
//    encodeSymbol('f', huffmanTree);
//    encodeSymbol('g', huffmanTree);
    displayIndexedGraph();
    displayGraph(huffmanTree);
}

void uncompressFile(std::string fileName) {

}

void displayOptions() {
    std::cout << "Alege fisierul!" << "\n\n Audio:\n";
    std::cout << "\t1.)instr_01.wav\n";
    std::cout << "\t2.)sound_01.wav\n";
    std::cout << "\t3.)speech_01.wav\n";
    std::cout << "\nDocuments:\n";
    std::cout << "\t4.)Documentatie_UMAPID.doc\n";
    std::cout << "\t5.)Documentatie_UMAPID.pdf\n";
    std::cout << "\t6.)Prefata_Undine.txt\n";
    std::cout << "\t7.)show_audio.m\n";
    std::cout << "\t8.)Y04.M\n";
    std::cout << "\nExecutables:\n";
    std::cout << "\t9.)KARMA_DATA482#1_5_V7.mat\n";
    std::cout << "\t10.)quartz.dll\n";
    std::cout << "\t11.)WinRar.exe\n";
    std::cout << "\t12.)WINZIP32.EXE\n";

}

std::ifstream::pos_type filesize(std::string fileName) {
    std::ifstream in(fileName.c_str(), std::ifstream::ate | std::ifstream::binary);
    return in.tellg();
}

void displayInformations(std::string fileName) {
    std::ifstream::pos_type compressedFileSize, fileSize, uncompressedFileSize;
    std::string compressedFileName, uncompressedFileName;

    compressedFileName = fileName + ".psh";
    uncompressedFileName = fileName + ".pshu";

    compressedFileSize = filesize(compressedFileName);
    fileSize = filesize(fileName);
    uncompressedFileSize = filesize(uncompressedFileName);

    std::cout << "Norma: " << (fileSize - uncompressedFileSize) * (fileSize - uncompressedFileSize) << "\n";
    std::cout << "Rata compresie: " << (1 - ((float) compressedFileSize) / ((float) uncompressedFileSize)) * 100 << "%\n";
    std::cout << "Factor compresie:  " << (((float) compressedFileSize) / ((float) fileSize)) * 100 << "%\n";

}

int main() {

    std::vector<std::string> files = {
            ".\\audio\\instr_01.wav",
            ".\\audio\\sound_01.wav",
            ".\\audio\\speech_01.wav",
            ".\\documents\\Documentatie_UMAPID.doc",
            ".\\documents\\Documentatie_UMAPID.pdf",
            ".\\documents\\Prefata_Undine.txt",
            ".\\documents\\show_audio.m",
            ".\\documents\\Y04.M",
            ".\\executables\\KARMA_DATA482#1_5_V7.mat",
            ".\\executables\\quartz.dll",
            ".\\executables\\WinRar.exe",
            ".\\executables\\WINZIP32.EXE",
            ".\\documents\\input.txt",
            "D:\\input.txt",
    };

    int option;
    //displayOptions();
    //std::cout << "Select file!..\n";
    //std::cin >> option;
//    if (option < 1 && option > 14) {
//        std::cout << "Invalid option!";
//        return 0;
//    }
    auto startC = std::chrono::high_resolution_clock::now();

    compressFile(files[2]);
    auto endC = std::chrono::high_resolution_clock::now();
    auto timeC = endC - startC;
    std::cout << "Compressed time: " << std::chrono::duration_cast<miliseconds_type>(timeC).count() << " miliseconds.\n";

    auto startU = std::chrono::high_resolution_clock::now();
//    uncompressFile(files[option - 1]);

    auto endU = std::chrono::high_resolution_clock::now();
    auto timeU = endU - startU;
    std::cout << "Uncompressed time: " << std::chrono::duration_cast<miliseconds_type>(timeU).count() << " miliseconds.\n";
//    displayInformations(files[option - 1]);

    //std::cin >> option;

    return 0;
}<|endoftext|>


<commit_before>//90% finished
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <mach/mach_traps.h>
#include <mach/mach_init.h>
#include <mach/mach_error.h>
#include <mach/mach.h>
#include <mach-o/dyld_images.h>
#include <mach-o/loader.h>
#include <libproc.h>
#include <sys/stat.h>
#include <string>
#include <sstream>

using namespace std;

mach_port_t task;
uint64_t Client, SizeClient;
uint8_t * buffer;
////
// define global patterns
////

string LocalPlayer = "4839DF74??4885FF74??4889DEE8????????EB??";
string EntityList = "554889E54156534889FBBE??000000E8????????8B??????????83F8FF";
string Glow = "48C7????e?2E05????????488D??????????488D??????????E8";
////
// copy client.dylib to our program memory
////
int GetCSpid() {
    int csgopid ;
    int numberOfProcesses = proc_listpids(PROC_ALL_PIDS, 0, NULL, 0);
    pid_t pids[numberOfProcesses];
    bzero(pids, sizeof(pids));
    proc_listpids(PROC_ALL_PIDS, 0, pids, sizeof(pids));
    for (int i = 0; i < numberOfProcesses; ++i) {
        if (pids[i] == 0) { continue; }
        char pathBuffer[PROC_PIDPATHINFO_MAXSIZE];
        bzero(pathBuffer, PROC_PIDPATHINFO_MAXSIZE);
        proc_pidpath(pids[i], pathBuffer, sizeof(pathBuffer));
        char nameBuffer[256];
        int position = strlen(pathBuffer);
        while(position >= 0 && pathBuffer[position] != '/')
        {
            position--;
        }
        strcpy(nameBuffer, pathBuffer + position + 1);
        if (strcmp(nameBuffer, "csgo_osx64")==0) {
            return pids[i];
        }
    }

    return 0;

}

void ClientToBuffer() {
    kern_return_t kret;
    mach_vm_address_t address;
    int csgopid = GetCSpid();
    kret = task_for_pid(mach_task_self(), csgopid, &task);
    if (kret!=KERN_SUCCESS)
    {
        printf("task_for_pid() failed with message %s!\n",mach_error_string(kret));
        exit(0);
    }
    struct task_dyld_info dyld_info;
    mach_msg_type_number_t count = TASK_DYLD_INFO_COUNT;
    if (task_info(task, TASK_DYLD_INFO, (task_info_t)&dyld_info, &count) == KERN_SUCCESS)
    {
        address = dyld_info.all_image_info_addr;
    }
    mach_msg_type_number_t size = sizeof(struct dyld_all_image_infos);
    vm_offset_t readMem;
    vm_read(task,address,size,&readMem,&size);
    struct dyld_all_image_infos* infos = (struct dyld_all_image_infos *) readMem;
    size = sizeof(struct dyld_image_info) * infos->infoArrayCount;
    vm_read(task,(mach_vm_address_t) infos->infoArray,size,&readMem,&size);
    struct dyld_image_info* info = (struct dyld_image_info*) readMem;
    mach_msg_type_number_t sizeMax=512;
    for (int i=0; i < infos->infoArrayCount; i++) {
        vm_read(task,(mach_vm_address_t) info[i].imageFilePath,sizeMax,&readMem,&sizeMax);
        char *path = (char *) readMem ;
        if(strstr(path, "/client.dylib") != NULL){
            Client = (mach_vm_address_t)info[i].imageLoadAddress ;
            struct stat st;
            stat(path, &st);
            printf("client: 0x%llx %lld\n", Client, st.st_size);
            uint8_t * m_data;
            m_data = new uint8_t[st.st_size];
            sizeMax = st.st_size;
            vm_read(task,(vm_address_t)Client,sizeMax,&readMem,&sizeMax);
            uint64_t address = (uint64_t)readMem;
            buffer = (uint8_t *)address;
            SizeClient = st.st_size;

        }
    }
}

uint64_t Scan(string s){
    stringstream ss;
    bool flag = true;
    for (int j=0;j<(SizeClient-(s.size())/2 + 1);j++){
        flag = true;
        for (int i=0; i<(s.size())/2; i++){
            string bytechar = s.substr(2*i,2);
            if (bytechar.compare("??") != 0){
                if (bytechar.substr(1,1).compare("?") == 0){
                    char byte[2];
                    int out;
                    out = sprintf(byte, "%x",buffer[i+j]);
                    string bytebuffer (byte);
                    if (bytebuffer.length()==1){
                        bytebuffer = "0"+bytebuffer;
                    }
                    //cout << bytebuffer << endl;
                    if (bytechar.substr(0,1).compare(bytebuffer.substr(0,1))!=0){
                        //cout << bytechar << bytebuffer << endl;
                        flag=false;
                        break;
                    }
                    continue;
                }
                uint8_t byte = std::stoi(bytechar, NULL,16);
                if (byte != buffer[j+i]){
                    flag = false;
                    break;
                }
            }
        }
        if (flag){
            return (Client+j);
        }
    }
    return 0;
}

int main(int argc, const char * argv[]) {
    // insert code here...
    ClientToBuffer();
    printf("%x\n",buffer[0]);
    printf("%llx\n",Scan(LocalPlayer));
    printf("%llx\n",Scan(EntityList));
    printf("%llx\n",Scan(Glow));
    uint8_t test = 0x1e ;
    string conv = std::to_string(test);
    cout << conv << endl;
    return 0;
}
<commit_msg>Final commit<commit_after>#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <mach/mach_traps.h>
#include <mach/mach_init.h>
#include <mach/mach_error.h>
#include <mach/mach.h>
#include <mach-o/dyld_images.h>
#include <mach-o/loader.h>
#include <libproc.h>
#include <sys/stat.h>
#include <string>
#include <sstream>

using namespace std;

mach_port_t task;
uint64_t Client, SizeClient;
uint8_t * buffer;
////
// define global patterns
////

string LocalPlayer = "4839DF74??4885FF74??4889DEE8????????EB??";
string EntityList = "554889E54156534889FBBE??000000E8????????8B??????????83F8FF";
string Glow = "48C7????e?2E05????????488D??????????488D??????????E8";
////
// copy client.dylib to our program memory
////
int GetCSpid() {
    int csgopid ;
    int numberOfProcesses = proc_listpids(PROC_ALL_PIDS, 0, NULL, 0);
    pid_t pids[numberOfProcesses];
    bzero(pids, sizeof(pids));
    proc_listpids(PROC_ALL_PIDS, 0, pids, sizeof(pids));
    for (int i = 0; i < numberOfProcesses; ++i) {
        if (pids[i] == 0) { continue; }
        char pathBuffer[PROC_PIDPATHINFO_MAXSIZE];
        bzero(pathBuffer, PROC_PIDPATHINFO_MAXSIZE);
        proc_pidpath(pids[i], pathBuffer, sizeof(pathBuffer));
        char nameBuffer[256];
        int position = strlen(pathBuffer);
        while(position >= 0 && pathBuffer[position] != '/')
        {
            position--;
        }
        strcpy(nameBuffer, pathBuffer + position + 1);
        if (strcmp(nameBuffer, "csgo_osx64")==0) {
            return pids[i];
        }
    }

    return 0;

}

void ClientToBuffer() {
    kern_return_t kret;
    mach_vm_address_t address;
    int csgopid = GetCSpid();
    kret = task_for_pid(mach_task_self(), csgopid, &task);
    if (kret!=KERN_SUCCESS)
    {
        printf("task_for_pid() failed with message %s!\n",mach_error_string(kret));
        exit(0);
    }
    struct task_dyld_info dyld_info;
    mach_msg_type_number_t count = TASK_DYLD_INFO_COUNT;
    if (task_info(task, TASK_DYLD_INFO, (task_info_t)&dyld_info, &count) == KERN_SUCCESS)
    {
        address = dyld_info.all_image_info_addr;
    }
    mach_msg_type_number_t size = sizeof(struct dyld_all_image_infos);
    vm_offset_t readMem;
    vm_read(task,address,size,&readMem,&size);
    struct dyld_all_image_infos* infos = (struct dyld_all_image_infos *) readMem;
    size = sizeof(struct dyld_image_info) * infos->infoArrayCount;
    vm_read(task,(mach_vm_address_t) infos->infoArray,size,&readMem,&size);
    struct dyld_image_info* info = (struct dyld_image_info*) readMem;
    mach_msg_type_number_t sizeMax=512;
    for (int i=0; i < infos->infoArrayCount; i++) {
        vm_read(task,(mach_vm_address_t) info[i].imageFilePath,sizeMax,&readMem,&sizeMax);
        char *path = (char *) readMem ;
        if(strstr(path, "/client.dylib") != NULL){
            Client = (mach_vm_address_t)info[i].imageLoadAddress ;
            struct stat st;
            stat(path, &st);
            printf("client: 0x%llx %lld\n", Client, st.st_size);
            uint8_t * m_data;
            m_data = new uint8_t[st.st_size];
            sizeMax = st.st_size;
            vm_read(task,(vm_address_t)Client,sizeMax,&readMem,&sizeMax);
            uint64_t address = (uint64_t)readMem;
            buffer = (uint8_t *)address;
            SizeClient = st.st_size;

        }
    }
}

uint64_t Scan(string s){
    stringstream ss;
    bool flag = true;
    for (int j=0;j<(SizeClient-(s.size())/2 + 1);j++){
        flag = true;
        for (int i=0; i<(s.size())/2; i++){
            string bytechar = s.substr(2*i,2);
            if (bytechar.compare("??") != 0){
                if (bytechar.substr(1,1).compare("?") == 0){
                    char byte[2];
                    int out;
                    out = sprintf(byte, "%x",buffer[i+j]);
                    string bytebuffer (byte);
                    if (bytebuffer.length()==1){
                        bytebuffer = "0"+bytebuffer;
                    }
                    if (bytechar.substr(0,1).compare(bytebuffer.substr(0,1))!=0){
                        flag=false;
                        break;
                    }
                    continue;
                }
                uint8_t byte = std::stoi(bytechar, NULL,16);
                if (byte != buffer[j+i]){
                    flag = false;
                    break;
                }
            }
        }
        if (flag){
            return (Client+j);
        }
    }
    return 0;
}

int main(int argc, const char * argv[]) {
    // insert code here...
    ClientToBuffer();
    uint64_t LocalPlayerArr=Scan(LocalPlayer);
    uint64_t EntityArr=Scan(EntityList);
    uint64_t GlowArr=Scan(Glow);
    uint32_t int1 = (int)*((int*)(LocalPlayerArr-Client+buffer + 0x17));
    LocalPlayerArr = LocalPlayerArr + 0x1F + int1 - Client;
    printf("%llx\n",LocalPlayerArr);
    uint32_t int2 = (int)*((int*)(EntityArr-Client+buffer + 0x22));
    uint64_t int3 = (uint64_t) *(uint64_t *)(EntityArr-Client+buffer + 0x26 + int2);
    EntityArr = int3 + 0x8 + 0x20 -Client;
    printf("%llx\n",EntityArr);
    uint32_t int4 = (int)*((int*)(GlowArr-Client+buffer + 0x2D));
    GlowArr = GlowArr + 0x31 + int4 - Client;
    printf("%llx\n",GlowArr);
    return 0;
}
<|endoftext|>