<commit_before>
#include "demhandlers.h"
#include "demmessages.h"

#define DECLARE_DEM_HANDLER_ARRAY(funcname) \
    { \
        &DemHandlers::Dem_Unknown_##funcname, \
        &DemHandlers::Dem_Packet_##funcname, \
        &DemHandlers::Dem_Packet_##funcname, \
        &DemHandlers::Dem_SyncTick_##funcname, \
        &DemHandlers::Dem_ConsoleCmd_##funcname, \
        &DemHandlers::Dem_UserCmd_##funcname, \
        &DemHandlers::Dem_DataTables_##funcname, \
        &DemHandlers::Dem_Stop_##funcname, \
        &DemHandlers::Dem_StringTables_##funcname \
    }

typedef bool (*DemMsgFileReadFn)(FileRead& demofile, void* data);
typedef bool (*DemMsgFileWriteFn)(FileWrite& demofile, void* data);
typedef bool (*DemMsgJsonReadFn)(JsonRead& jsonbuf, void* data);
typedef bool (*DemMsgJsonWriteFn)(JsonWrite& jsonbuf, void* data);

bool DemHandlers::DemMsg_FileRead(uint32_t type, FileRead& demofile, void* data)
{
    static const DemMsgFileReadFn demHandlers[] = DECLARE_DEM_HANDLER_ARRAY(FileRead);
    return demHandlers[type](demofile, data);
}

bool DemHandlers::DemMsg_FileWrite(uint32_t type, FileWrite& demofile, void* data)
{
    static const DemMsgFileWriteFn demHandlers[] = DECLARE_DEM_HANDLER_ARRAY(FileWrite);
    return demHandlers[type](demofile, data);
}

bool DemHandlers::DemMsg_JsonRead(uint32_t type, JsonRead& jsonbuf, void* data)
{
    static const DemMsgJsonReadFn demHandlers[] = DECLARE_DEM_HANDLER_ARRAY(JsonRead);
    return demHandlers[type](jsonbuf, data);
}

bool DemHandlers::DemMsg_JsonWrite(uint32_t type, JsonWrite& jsonbuf, void* data)
{
    static const DemMsgJsonWriteFn demHandlers[] = DECLARE_DEM_HANDLER_ARRAY(JsonWrite);
    return demHandlers[type](jsonbuf, data);
}
<commit_msg>Added guards around DemHandlers functions<commit_after>
#include "demhandlers.h"
#include "demmessages.h"

#define DECLARE_DEM_HANDLER_ARRAY(funcname) \
    { \
        &DemHandlers::Dem_Unknown_##funcname, \
        &DemHandlers::Dem_Packet_##funcname, \
        &DemHandlers::Dem_Packet_##funcname, \
        &DemHandlers::Dem_SyncTick_##funcname, \
        &DemHandlers::Dem_ConsoleCmd_##funcname, \
        &DemHandlers::Dem_UserCmd_##funcname, \
        &DemHandlers::Dem_DataTables_##funcname, \
        &DemHandlers::Dem_Stop_##funcname, \
        &DemHandlers::Dem_StringTables_##funcname \
    }

typedef bool (*DemMsgFileReadFn)(FileRead& demofile, void* data);
typedef bool (*DemMsgFileWriteFn)(FileWrite& demofile, void* data);
typedef bool (*DemMsgJsonReadFn)(JsonRead& jsonbuf, void* data);
typedef bool (*DemMsgJsonWriteFn)(JsonWrite& jsonbuf, void* data);

bool DemHandlers::DemMsg_FileRead(uint32_t type, FileRead& demofile, void* data)
{
    static const DemMsgFileReadFn demHandlers[] = DECLARE_DEM_HANDLER_ARRAY(FileRead);
    if (type >= (sizeof(demHandlers) / sizeof(DemMsgFileReadFn)))
    {
        return false;
    }
    return demHandlers[type](demofile, data);
}

bool DemHandlers::DemMsg_FileWrite(uint32_t type, FileWrite& demofile, void* data)
{
    static const DemMsgFileWriteFn demHandlers[] = DECLARE_DEM_HANDLER_ARRAY(FileWrite);
    if (type >= (sizeof(demHandlers) / sizeof(DemMsgFileWriteFn)))
    {
        return false;
    }
    return demHandlers[type](demofile, data);
}

bool DemHandlers::DemMsg_JsonRead(uint32_t type, JsonRead& jsonbuf, void* data)
{
    static const DemMsgJsonReadFn demHandlers[] = DECLARE_DEM_HANDLER_ARRAY(JsonRead);
    if (type >= (sizeof(demHandlers) / sizeof(DemMsgJsonReadFn)))
    {
        return false;
    }
    return demHandlers[type](jsonbuf, data);
}

bool DemHandlers::DemMsg_JsonWrite(uint32_t type, JsonWrite& jsonbuf, void* data)
{
    static const DemMsgJsonWriteFn demHandlers[] = DECLARE_DEM_HANDLER_ARRAY(JsonWrite);
    if (type >= (sizeof(demHandlers) / sizeof(DemMsgJsonWriteFn)))
    {
        return false;
    }
    return demHandlers[type](jsonbuf, data);
}
<|endoftext|>


<commit_before>#include "stdafx.h"
#include <windows.h>
#include "..\includes\CPatch.h"
#include "..\includes\IniReader.h"

HMODULE h_e2mfc_dll = NULL;
HMODULE comics = NULL;

float iniFOV, FOV;
float fAspectRatio, stdViewPortSize, fWidthFactor, fDiffFactor;
float fVisibilityFactor1, fVisibilityFactor2;
unsigned int ScreenWidth, ScreenHeight;
DWORD jmpAddress, jmpFOV;
DWORD _EAX, _EBX, _nEDX; float _EDX;
bool bComicsMode;

int __fastcall PDriverGetWidth(int a1)
{
	int result; // eax@2

	if (*(DWORD *)(a1 + 48))
		result = *(DWORD *)(a1 + 52);
	else
		result = *(DWORD *)(a1 + 4);

	ScreenWidth = result;
	return result;
}

int __fastcall PDriverGetHeight(int a1)
{
	int result; // eax@2

	if (*(DWORD *)(a1 + 48))
		result = *(DWORD *)(a1 + 56);
	else
		result = *(DWORD *)(a1 + 8);

	ScreenHeight = result;
	return result;
}

void __declspec(naked)PatchFOV()
{
	__asm mov ebx, FOV
	__asm push    ebx //FOV value
	__asm mov     ecx, esi
	__asm call    ebp
	__asm jmp jmpFOV
}

void __fastcall P_CameraSetFOV(DWORD P_Camera, float FOVvalue)
{
	float v2; // eax@4

	FOVvalue *= iniFOV;

	if (*(float *)&FOVvalue != *(float *)(P_Camera + 284))
	{
		if (*(float *)&FOVvalue >= 0.0)
		{
			v2 = 3.1241393f;
			if (*(float *)&FOVvalue <= 3.1241393)
				v2 = FOVvalue;
			*(BYTE *)(P_Camera + 236) |= 0x40u;
			*(float *)(P_Camera + 284) = v2;
		}
		else
		{
			*(BYTE *)(P_Camera + 236) |= 0x40u;
			*(DWORD *)(P_Camera + 284) = 0;
		}
	}
}

void __declspec(naked)ForceEntireViewport()
{
	__asm mov ax, 1
	__asm ret
}

void __declspec(naked)DisableSubViewport()
{
	__asm ret 10h
}

void __declspec(naked)PCameraValidateHook()
{
	__asm mov _EAX, eax
	__asm mov _EBX, ebx
	__asm mov     edx, [esp + 4]
	__asm mov _EDX, edx
	__asm mov _nEDX, edx

	if (_EDX >= 0.7f && _EDX <= 0.8f)
	{
		if ((_EBX == 1 && _EAX == 8) || (_EBX == 0 && _EAX != 8))
		{
			if (!fDiffFactor)
			{
				fDiffFactor = fWidthFactor / _EDX;
			}

			if (fDiffFactor)
				_EDX *= fDiffFactor;
			__asm mov edx, _EDX
		}
	}
	else
	{
		if (_EAX == 8 && _EDX < 0.7f)
		{
			if (fDiffFactor)
				_EDX *= fDiffFactor;
			if ((_EBX == 1 && _EAX == 8 && _nEDX != 0x3ED413CD)) //0.414213568, it's to avoid comics stretching
				__asm mov edx, _EDX
		}
	}

	__asm mov[esi + 20Ch], edx
	__asm jmp jmpAddress
}

DWORD WINAPI Thread(LPVOID)
{
	CIniReader iniReader("");
	iniFOV = iniReader.ReadFloat("MAIN", "FOV", 0.0f);

	do
	{
		Sleep(100);
		h_e2mfc_dll = GetModuleHandle("e2mfc.dll");
	} while (h_e2mfc_dll == NULL);

	CPatch::RedirectCall((DWORD)h_e2mfc_dll + 0x176AF, PDriverGetWidth);
	CPatch::RedirectCall((DWORD)h_e2mfc_dll + 0x176F4, PDriverGetHeight);

	CPatch::RedirectJump((DWORD)h_e2mfc_dll + 0x156A0, DisableSubViewport);
	CPatch::RedirectJump((DWORD)h_e2mfc_dll + 0x14C80, ForceEntireViewport);

	do
	{
		Sleep(0);
	} while (ScreenWidth == 0 || ScreenHeight == 0);

	/*if (iniFOV)
	{
		//FOV = iniFOV;
		//jmpFOV = 0x428F86;
		//CPatch::RedirectJump(0x428F81, PatchFOV); //fov hack
		//CPatch::RedirectJump((DWORD)h_e2mfc_dll + 0x14E70, P_CameraSetFOV);
		//CPatch::SetPointer(0x428F7B, P_CameraSetFOV);
	}*/

	fAspectRatio = static_cast<float>(ScreenWidth) / static_cast<float>(ScreenHeight);

	fWidthFactor = fAspectRatio / (16.0f / 9.0f);

	if (fAspectRatio >= 1.4f)
	{
		jmpAddress = (DWORD)h_e2mfc_dll + 0x15041;
		CPatch::RedirectJump((DWORD)h_e2mfc_dll + 0x15037, PCameraValidateHook);

		//object disappearance fix
		CPatch::SetFloat((DWORD)h_e2mfc_dll + 0x15B87 + 0x6, 0.0f);

		stdViewPortSize = 640.0f;
		CPatch::SetPointer((DWORD)h_e2mfc_dll + 0x176D4 + 0x2, &stdViewPortSize);

		DWORD nComicsCheck = (DWORD)h_e2mfc_dll + 0x61183;

		//doors graphics fix
		fVisibilityFactor1 = 0.5f;
		fVisibilityFactor2 = 1.5f;
		//CPatch::SetPointer((DWORD)GetModuleHandle("X_GameObjectsMFC.dll") + 0xA8D0 + 0x4F5 + 0x2, &fVisibilityFactor4);
		CPatch::SetPointer((DWORD)GetModuleHandle("X_GameObjectsMFC.dll") + 0xA8D0 + 0x4CE + 0x2, &fVisibilityFactor1);
		//CPatch::SetPointer((DWORD)GetModuleHandle("X_GameObjectsMFC.dll") + 0xA8D0 + 0x4AC + 0x2, &fVisibilityFactor3);
		CPatch::SetPointer((DWORD)GetModuleHandle("X_GameObjectsMFC.dll") + 0xA8D0 + 0x485 + 0x2, &fVisibilityFactor2);

		//CPatch::SetPointer((DWORD)GetModuleHandle("X_GameObjectsMFC.dll") + 0x101F39 + 0x2, &fVisibilityFactor1);
		//CPatch::SetPointer((DWORD)GetModuleHandle("X_GameObjectsMFC.dll") + 0x101F67 + 0x2, &fVisibilityFactor2);

		if (iniReader.ReadInteger("MAIN", "COMICS_MODE", 0))
			bComicsMode = !bComicsMode;

		while (true)
		{
			Sleep(0);

			if ((GetAsyncKeyState(VK_F2) & 1) && ((unsigned char)*(DWORD*)nComicsCheck == 0xAE))
			{
				bComicsMode = !bComicsMode;
				iniReader.WriteInteger("MAIN", "COMICS_MODE", bComicsMode);
				while ((GetAsyncKeyState(VK_F2) & 0x8000) > 0) { Sleep(0); }
			}

			if (bComicsMode)
			{
				Sleep(1);
				if ((unsigned char)*(DWORD*)nComicsCheck == 0xAE)
				{
					stdViewPortSize = 480.0f * (fAspectRatio);
					CPatch::SetFloat((DWORD)h_e2mfc_dll + 0x434F4, 480.0f); //480.0f
				}
				else
				{
					stdViewPortSize = 640.0f;
					CPatch::SetFloat((DWORD)h_e2mfc_dll + 0x434F4, 480.0f); //480.0f
				}
			}
			else
			{
				Sleep(1);
				if ((unsigned char)*(DWORD*)nComicsCheck == 0xAE)
				{
					stdViewPortSize = (480.0f * (fAspectRatio) / 1.17936117936f);
					CPatch::SetFloat((DWORD)h_e2mfc_dll + 0x434F4, 480.0f / 1.17936117936f); //480.0f
				}
				else
				{
					stdViewPortSize = 640.0f;
					CPatch::SetFloat((DWORD)h_e2mfc_dll + 0x434F4, 480.0f); //480.0f
				}
			}
		}

	}
	return 0;
}

BOOL APIENTRY DllMain(HMODULE /*hModule*/, DWORD reason, LPVOID /*lpReserved*/)
{
	if (reason == DLL_PROCESS_ATTACH)
	{
		CreateThread(0, 0, (LPTHREAD_START_ROUTINE)&Thread, NULL, 0, NULL);
	}
	return TRUE;
}<commit_msg>Widescreen Fixes Pack v2.5.2<commit_after>#include "stdafx.h"
#include <windows.h>
#include "..\includes\CPatch.h"
#include "..\includes\IniReader.h"

HMODULE h_e2mfc_dll = NULL;
HMODULE comics = NULL;

float iniFOV, FOV;
float fAspectRatio, stdViewPortSize, fWidthFactor, fDiffFactor;
float fVisibilityFactor1, fVisibilityFactor2;
unsigned int ScreenWidth, ScreenHeight;
DWORD jmpAddress, jmpFOV;
DWORD _EAX, _EBX, _nEDX; float _EDX;
bool bComicsMode;

int __fastcall PDriverGetWidth(int a1)
{
	int result; // eax@2

	if (*(DWORD *)(a1 + 48))
		result = *(DWORD *)(a1 + 52);
	else
		result = *(DWORD *)(a1 + 4);

	ScreenWidth = result;
	return result;
}

int __fastcall PDriverGetHeight(int a1)
{
	int result; // eax@2

	if (*(DWORD *)(a1 + 48))
		result = *(DWORD *)(a1 + 56);
	else
		result = *(DWORD *)(a1 + 8);

	ScreenHeight = result;
	return result;
}

void __declspec(naked)PatchFOV()
{
	__asm mov ebx, FOV
	__asm push    ebx //FOV value
	__asm mov     ecx, esi
	__asm call    ebp
	__asm jmp jmpFOV
}

void __fastcall P_CameraSetFOV(DWORD P_Camera, float FOVvalue)
{
	FOVvalue *= iniFOV;

	if (*(float *)&FOVvalue != *(float *)(P_Camera + 284))
	{
		if (*(float *)&FOVvalue >= 0.0)
		{

			if (FOVvalue <= 3.1241393f)
			{
				*(BYTE *)(P_Camera + 236) |= 0x40u;
				*(float *)(P_Camera + 284) = FOVvalue;
			}
		}
		else
		{
			*(BYTE *)(P_Camera + 236) |= 0x40u;
			*(DWORD *)(P_Camera + 284) = 0;
		}
	}
}

void __declspec(naked)ForceEntireViewport()
{
	__asm mov ax, 1
	__asm ret
}

void __declspec(naked)DisableSubViewport()
{
	__asm ret 10h
}

void __declspec(naked)PCameraValidateHook()
{
	__asm mov _EAX, eax
	__asm mov _EBX, ebx
	__asm mov     edx, [esp + 4]
	__asm mov _EDX, edx
	__asm mov _nEDX, edx

	if (_EDX >= 0.7f && _EDX <= 0.8f)
	{
		if ((_EBX == 1 && _EAX == 8) || (_EBX == 0 && _EAX != 8))
		{
			if (!fDiffFactor)
			{
				fDiffFactor = fWidthFactor / _EDX;
			}

			if (fDiffFactor)
			_EDX *= fDiffFactor;
			__asm mov edx, _EDX
		}
	}
	else
	{
		if (_EAX == 8 && _EDX < 0.7f)
		{
			if (fDiffFactor)
				_EDX *= fDiffFactor;
			if (_EBX == 1 && _EAX == 8 && _nEDX != 0x3ED413CD) //0.414213568, it's to avoid comics stretching
				__asm mov edx, _EDX
		}
		else
		{
			if ((_EDX > 0.8f && _EDX <= 1.5f) && _nEDX != 0x3F800000)
			{
				if (fDiffFactor)
				_EDX *= fDiffFactor;
				if ((_EBX == 1 && _EAX == 8) || (_EBX == 0 && _EAX != 8))
				__asm mov edx, _EDX
			}
		}
	}

	__asm mov[esi + 20Ch], edx
	__asm jmp jmpAddress
}

DWORD WINAPI Thread(LPVOID)
{
	CIniReader iniReader("");
	iniFOV = iniReader.ReadFloat("MAIN", "FOV", 0.0f);

	do
	{
		Sleep(100);
		h_e2mfc_dll = GetModuleHandle("e2mfc.dll");
	} while (h_e2mfc_dll == NULL);

	CPatch::RedirectCall((DWORD)h_e2mfc_dll + 0x176AF, PDriverGetWidth);
	CPatch::RedirectCall((DWORD)h_e2mfc_dll + 0x176F4, PDriverGetHeight);

	CPatch::RedirectJump((DWORD)h_e2mfc_dll + 0x156A0, DisableSubViewport);
	CPatch::RedirectJump((DWORD)h_e2mfc_dll + 0x14C80, ForceEntireViewport);

	do
	{
		Sleep(0);
	} while (ScreenWidth == 0 || ScreenHeight == 0);

	/*if (iniFOV)
	{
		//FOV = iniFOV;
		//jmpFOV = 0x428F86;
		//CPatch::RedirectJump(0x428F81, PatchFOV); //fov hack
		//CPatch::RedirectJump((DWORD)h_e2mfc_dll + 0x14E70, P_CameraSetFOV);
		//CPatch::SetPointer(0x428F7B, P_CameraSetFOV);
	}*/

	fAspectRatio = static_cast<float>(ScreenWidth) / static_cast<float>(ScreenHeight);

	fWidthFactor = fAspectRatio / (16.0f / 9.0f);

	if (fAspectRatio >= 1.4f)
	{
		jmpAddress = (DWORD)h_e2mfc_dll + 0x15041;
		CPatch::RedirectJump((DWORD)h_e2mfc_dll + 0x15037, PCameraValidateHook);

		//object disappearance fix
		CPatch::SetFloat((DWORD)h_e2mfc_dll + 0x15B87 + 0x6, 0.0f);

		stdViewPortSize = 640.0f;
		CPatch::SetPointer((DWORD)h_e2mfc_dll + 0x176D4 + 0x2, &stdViewPortSize);

		DWORD nComicsCheck = (DWORD)h_e2mfc_dll + 0x61183;

		//doors graphics fix
		fVisibilityFactor1 = 0.5f;
		fVisibilityFactor2 = 1.5f;
		//CPatch::SetPointer((DWORD)GetModuleHandle("X_GameObjectsMFC.dll") + 0xA8D0 + 0x4F5 + 0x2, &fVisibilityFactor4);
		CPatch::SetPointer((DWORD)GetModuleHandle("X_GameObjectsMFC.dll") + 0xA8D0 + 0x4CE + 0x2, &fVisibilityFactor1);
		//CPatch::SetPointer((DWORD)GetModuleHandle("X_GameObjectsMFC.dll") + 0xA8D0 + 0x4AC + 0x2, &fVisibilityFactor3);
		CPatch::SetPointer((DWORD)GetModuleHandle("X_GameObjectsMFC.dll") + 0xA8D0 + 0x485 + 0x2, &fVisibilityFactor2);

		//CPatch::SetPointer((DWORD)GetModuleHandle("X_GameObjectsMFC.dll") + 0x101F39 + 0x2, &fVisibilityFactor1);
		//CPatch::SetPointer((DWORD)GetModuleHandle("X_GameObjectsMFC.dll") + 0x101F67 + 0x2, &fVisibilityFactor2);

		if (iniReader.ReadInteger("MAIN", "COMICS_MODE", 0))
			bComicsMode = !bComicsMode;

		while (true)
		{
			Sleep(0);

			if ((GetAsyncKeyState(VK_F2) & 1) && ((unsigned char)*(DWORD*)nComicsCheck == 0xAE))
			{
				bComicsMode = !bComicsMode;
				iniReader.WriteInteger("MAIN", "COMICS_MODE", bComicsMode);
				while ((GetAsyncKeyState(VK_F2) & 0x8000) > 0) { Sleep(0); }
			}

			if (bComicsMode)
			{
				Sleep(1);
				if ((unsigned char)*(DWORD*)nComicsCheck == 0xAE)
				{
					stdViewPortSize = 480.0f * (fAspectRatio);
					CPatch::SetFloat((DWORD)h_e2mfc_dll + 0x434F4, 480.0f); //480.0f
				}
				else
				{
					stdViewPortSize = 640.0f;
					CPatch::SetFloat((DWORD)h_e2mfc_dll + 0x434F4, 480.0f); //480.0f
				}
			}
			else
			{
				Sleep(1);
				if ((unsigned char)*(DWORD*)nComicsCheck == 0xAE)
				{
					stdViewPortSize = (480.0f * (fAspectRatio) / 1.17936117936f);
					CPatch::SetFloat((DWORD)h_e2mfc_dll + 0x434F4, 480.0f / 1.17936117936f); //480.0f
				}
				else
				{
					stdViewPortSize = 640.0f;
					CPatch::SetFloat((DWORD)h_e2mfc_dll + 0x434F4, 480.0f); //480.0f
				}
			}
		}

	}
	return 0;
}

BOOL APIENTRY DllMain(HMODULE /*hModule*/, DWORD reason, LPVOID /*lpReserved*/)
{
	if (reason == DLL_PROCESS_ATTACH)
	{
		CreateThread(0, 0, (LPTHREAD_START_ROUTINE)&Thread, NULL, 0, NULL);
	}
	return TRUE;
}<|endoftext|>


<commit_before>/*******************************************************
 * Copyright (c) 2014, ArrayFire
 * All rights reserved.
 *
 * This file is distributed under 3-clause BSD license.
 * The complete license agreement can be obtained at:
 * http://arrayfire.com/licenses/BSD-3-Clause
 ********************************************************/

#include <arrayfire.h>
#include <cstdio>
#include <math.h>

using namespace af;

static const int POINTS = 30;
static const int N = 2 * POINTS;

int main(int argc, char *argv[])
{
    try {
        // Initialize the kernel array just once
        af::info();
        af::Window myWindow(800, 800, "3D Surface example: ArrayFire");

        // Creates grid of between [-1 1] with precision of 1 / POINTS
        const array x = iota(dim4(N, 1), dim4(1, N)) / POINTS - 1;
        const array y = iota(dim4(1, N), dim4(N, 1)) / POINTS - 1;

        std::cout << x.dims()  << y.dims() << std::endl;

        static float t=0;
        while(!myWindow.close()) {
            t+=0.07;
            array z = 10*x*-abs(y) * cos(x*x*(y+t))+sin(y*(x+t))-1.5;
            myWindow.surface(x, y, z);
        }

    } catch (af::exception& e) {
        fprintf(stderr, "%s\n", e.what());
        throw;
    }
    return 0;
}
<commit_msg>Fixing surface.cpp example to work on windows<commit_after>/*******************************************************
 * Copyright (c) 2014, ArrayFire
 * All rights reserved.
 *
 * This file is distributed under 3-clause BSD license.
 * The complete license agreement can be obtained at:
 * http://arrayfire.com/licenses/BSD-3-Clause
 ********************************************************/

#include <arrayfire.h>
#include <cstdio>
#include <math.h>

using namespace af;

static const int M = 30;
static const int N = 2 * M;

int main(int argc, char *argv[])
{
    try {
        // Initialize the kernel array just once
        af::info();
        af::Window myWindow(800, 800, "3D Surface example: ArrayFire");

        // Creates grid of between [-1 1] with precision of 1 / M
        const array x = iota(dim4(N, 1), dim4(1, N)) / M - 1;
        const array y = iota(dim4(1, N), dim4(N, 1)) / M - 1;

        std::cout << x.dims()  << y.dims() << std::endl;

        static float t=0;
        while(!myWindow.close()) {
            t+=0.07;
            array z = 10*x*-abs(y) * cos(x*x*(y+t))+sin(y*(x+t))-1.5;
            myWindow.surface(x, y, z);
        }

    } catch (af::exception& e) {
        fprintf(stderr, "%s\n", e.what());
        throw;
    }
    return 0;
}
<|endoftext|>


<commit_before>/*
 * Software License Agreement (Apache License)
 *
 * Copyright (c) 2014, Dan Solomon
 *
 * 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.
 */
/*
 * joint_trajectory_pt.cpp
 *
 *  Created on: Oct 3, 2014
 *      Author: Dan Solomon
 */

#include <console_bridge/console.h>
#include "descartes_core/joint_trajectory_pt.h"

#define NOT_IMPLEMENTED_ERR(ret) logError("%s not implemented", __PRETTY_FUNCTION__); return ret;

namespace descartes_core
{

JointTrajectoryPt::JointTrajectoryPt():
    tool_(Eigen::Affine3d::Identity()),
    wobj_(Eigen::Affine3d::Identity())
{}

JointTrajectoryPt::JointTrajectoryPt(const std::vector<TolerancedJointValue> &joints,
                                     const Frame &tool, const Frame &wobj):
  joint_position_(joints),
  tool_(tool),
  wobj_(wobj)
{}

JointTrajectoryPt::JointTrajectoryPt(const std::vector<TolerancedJointValue> &joints):
  joint_position_(joints),
  tool_(Eigen::Affine3d::Identity()),
  wobj_(Eigen::Affine3d::Identity())
{}

JointTrajectoryPt::JointTrajectoryPt(const std::vector<double> &joints):
  tool_(Eigen::Affine3d::Identity()),
  wobj_(Eigen::Affine3d::Identity())
{
  for (size_t ii = 0; ii < joints.size(); ++ii)
  {
    joint_position_.push_back(TolerancedJointValue(joints[ii]));
  }
}

bool JointTrajectoryPt::getClosestCartPose(const std::vector<double> &seed_state,
                                           const RobotModel &model, Eigen::Affine3d &pose) const
{
  NOT_IMPLEMENTED_ERR(false)
}

bool JointTrajectoryPt::getNominalCartPose(const std::vector<double> &seed_state,
                                           const RobotModel &model, Eigen::Affine3d &pose) const
{
  std::vector<double> joints;
  for(auto& tj: joint_position_)
  {
    joints.push_back(tj.nominal);
  }
  return model.getFK(joints,pose);
}

void JointTrajectoryPt::getCartesianPoses(const RobotModel &model, EigenSTL::vector_Affine3d &poses) const
{
  poses.clear();
}

bool JointTrajectoryPt::getClosestJointPose(const std::vector<double> &seed_state,
                                            const RobotModel &model,
                                            std::vector<double> &joint_pose) const
{
  NOT_IMPLEMENTED_ERR(false);
}

bool JointTrajectoryPt::getNominalJointPose(const std::vector<double> &seed_state,
                                            const RobotModel &model,
                                            std::vector<double> &joint_pose) const
{
  joint_pose.resize(joint_position_.size());
  for (size_t ii=0; ii<joint_position_.size(); ++ii)
  {
    joint_pose[ii] = joint_position_[ii].nominal;
  }
  return true;
}

void JointTrajectoryPt::getJointPoses(const RobotModel &model,
                                      std::vector<std::vector<double> > &joint_poses) const
{
  std::vector<double> empty_seed;
  joint_poses.resize(1);
  getNominalJointPose(empty_seed,model,joint_poses[0]);
}

bool JointTrajectoryPt::isValid(const RobotModel &model) const
{
  std::vector<double> lower(joint_position_.size());
  std::vector<double> upper(joint_position_.size());
  for (size_t ii = 0; ii < joint_position_.size(); ++ii)
  {
    lower[ii] = joint_position_[ii].tolerance.lower;
    upper[ii] = joint_position_[ii].tolerance.upper;
  }
return model.isValid(lower) && model.isValid(upper);
}

bool JointTrajectoryPt::setDiscretization(const std::vector<double> &discretization)
{
  if (discretization.size() != 1 || discretization.size() != joint_position_.size())
  {
    logError("discretization must be size 1 or same size as joint count.");
    return false;
  }

  if (discretization.size() == 1)
  {
    discretization_ = std::vector<double>(joint_position_.size(), discretization[0]);
    return true;
  }

  /* Do not copy discretization values until all values are confirmed */
  for (size_t ii=0; ii<discretization.size(); ++ii)
  {
    if (discretization[ii] < 0. || discretization[ii] > joint_position_[ii].range())
    {
      logError("discretization value out of range.");
      return false;
    }
  }

  discretization_ = discretization;

  return true;
}

} /* namespace descartes_core */
<commit_msg>implemented Joint Trajectory point getClosestJointPose(...) method<commit_after>/*
 * Software License Agreement (Apache License)
 *
 * Copyright (c) 2014, Dan Solomon
 *
 * 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.
 */
/*
 * joint_trajectory_pt.cpp
 *
 *  Created on: Oct 3, 2014
 *      Author: Dan Solomon
 */

#include <console_bridge/console.h>
#include "descartes_core/joint_trajectory_pt.h"

#define NOT_IMPLEMENTED_ERR(ret) logError("%s not implemented", __PRETTY_FUNCTION__); return ret;

namespace descartes_core
{

JointTrajectoryPt::JointTrajectoryPt():
    tool_(Eigen::Affine3d::Identity()),
    wobj_(Eigen::Affine3d::Identity())
{}

JointTrajectoryPt::JointTrajectoryPt(const std::vector<TolerancedJointValue> &joints,
                                     const Frame &tool, const Frame &wobj):
  joint_position_(joints),
  tool_(tool),
  wobj_(wobj)
{}

JointTrajectoryPt::JointTrajectoryPt(const std::vector<TolerancedJointValue> &joints):
  joint_position_(joints),
  tool_(Eigen::Affine3d::Identity()),
  wobj_(Eigen::Affine3d::Identity())
{}

JointTrajectoryPt::JointTrajectoryPt(const std::vector<double> &joints):
  tool_(Eigen::Affine3d::Identity()),
  wobj_(Eigen::Affine3d::Identity())
{
  for (size_t ii = 0; ii < joints.size(); ++ii)
  {
    joint_position_.push_back(TolerancedJointValue(joints[ii]));
  }
}

bool JointTrajectoryPt::getClosestCartPose(const std::vector<double> &seed_state,
                                           const RobotModel &model, Eigen::Affine3d &pose) const
{
  NOT_IMPLEMENTED_ERR(false)
}

bool JointTrajectoryPt::getNominalCartPose(const std::vector<double> &seed_state,
                                           const RobotModel &model, Eigen::Affine3d &pose) const
{
  std::vector<double> joints;
  for(auto& tj: joint_position_)
  {
    joints.push_back(tj.nominal);
  }
  return model.getFK(joints,pose);
}

void JointTrajectoryPt::getCartesianPoses(const RobotModel &model, EigenSTL::vector_Affine3d &poses) const
{
  poses.clear();
}

bool JointTrajectoryPt::getClosestJointPose(const std::vector<double> &seed_state,
                                            const RobotModel &model,
                                            std::vector<double> &joint_pose) const
{
  joint_pose.assign(seed_state.begin(),seed_state.end());
}

bool JointTrajectoryPt::getNominalJointPose(const std::vector<double> &seed_state,
                                            const RobotModel &model,
                                            std::vector<double> &joint_pose) const
{
  joint_pose.resize(joint_position_.size());
  for (size_t ii=0; ii<joint_position_.size(); ++ii)
  {
    joint_pose[ii] = joint_position_[ii].nominal;
  }
  return true;
}

void JointTrajectoryPt::getJointPoses(const RobotModel &model,
                                      std::vector<std::vector<double> > &joint_poses) const
{
  std::vector<double> empty_seed;
  joint_poses.resize(1);
  getNominalJointPose(empty_seed,model,joint_poses[0]);
}

bool JointTrajectoryPt::isValid(const RobotModel &model) const
{
  std::vector<double> lower(joint_position_.size());
  std::vector<double> upper(joint_position_.size());
  for (size_t ii = 0; ii < joint_position_.size(); ++ii)
  {
    lower[ii] = joint_position_[ii].tolerance.lower;
    upper[ii] = joint_position_[ii].tolerance.upper;
  }
return model.isValid(lower) && model.isValid(upper);
}

bool JointTrajectoryPt::setDiscretization(const std::vector<double> &discretization)
{
  if (discretization.size() != 1 || discretization.size() != joint_position_.size())
  {
    logError("discretization must be size 1 or same size as joint count.");
    return false;
  }

  if (discretization.size() == 1)
  {
    discretization_ = std::vector<double>(joint_position_.size(), discretization[0]);
    return true;
  }

  /* Do not copy discretization values until all values are confirmed */
  for (size_t ii=0; ii<discretization.size(); ++ii)
  {
    if (discretization[ii] < 0. || discretization[ii] > joint_position_[ii].range())
    {
      logError("discretization value out of range.");
      return false;
    }
  }

  discretization_ = discretization;

  return true;
}

} /* namespace descartes_core */
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: services.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: obo $ $Date: 2005-03-15 12:23:44 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include "evaluation.hxx"

#ifndef _COM_SUN_STAR_BEANS_NAMEDVALUE_HPP_
#include <com/sun/star/beans/NamedValue.hpp>
#endif
#ifndef _COM_SUN_STAR_REGISTRY_XREGISTRYKEY_HPP_
#include <com/sun/star/registry/XRegistryKey.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_DATE_HPP_
#include <com/sun/star/util/Date.hpp>
#endif

#ifndef _UNO_ENVIRONMENT_H_
#include <uno/environment.h>
#endif
#ifndef _CPPUHELPER_FACTORY_HXX_
#include <cppuhelper/factory.hxx>
#endif
#ifndef _UTL_CONFIGMGR_HXX_
#include <unotools/configmgr.hxx>
#endif

#include "oemjob.hxx"
#include "evaluation.hxx"

using namespace rtl;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::registry;
using namespace ::desktop;

static const char* pServices[] =
{
    SOEvaluation::serviceName,
    OEMPreloadJob::serviceName,
    NULL
};

static const char* pImplementations[] =
{
    SOEvaluation::implementationName,
    OEMPreloadJob::implementationName,
    NULL
};

typedef Reference<XInterface>(* fProvider)(const Reference<XMultiServiceFactory>&);

static const fProvider pInstanceProviders[] =
{
    SOEvaluation::CreateInstance,
    OEMPreloadJob::CreateInstance,
    NULL
};

static const char** pSupportedServices[] =
{
    SOEvaluation::interfaces,
    OEMPreloadJob::interfaces,
    NULL
};

static Sequence<OUString>
getSupportedServiceNames(int p) {
    const char **names = pSupportedServices[p];
    Sequence<OUString> aSeq;
    for(int i = 0; names[i] != NULL; i++) {
        aSeq.realloc(i+1);
        aSeq[i] = OUString::createFromAscii(names[i]);
    }
    return aSeq;
}

extern "C"
{
void SAL_CALL
component_getImplementationEnvironment(
    const sal_Char** ppEnvironmentTypeName,
    uno_Environment** ppEnvironment)
{
    *ppEnvironmentTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME ;
}

sal_Bool SAL_CALL
component_writeInfo(
    void* pServiceManager,
    void* pRegistryKey)
{
    Reference<XMultiServiceFactory> xMan(
        reinterpret_cast< XMultiServiceFactory* >( pServiceManager ) ) ;
    Reference<XRegistryKey> xKey(
        reinterpret_cast< XRegistryKey* >( pRegistryKey ) ) ;

    // iterate over service names and register them...
    OUString aImpl;
    const char* pServiceName = NULL;
    const char* pImplName = NULL;
    for (int i = 0; (pServices[i]!=NULL)&&(pImplementations[i]!=NULL); i++) {
        pServiceName= pServices[i];
        pImplName = pImplementations[i];
        aImpl = OUString::createFromAscii("/")
              + OUString::createFromAscii(pImplName)
              + OUString::createFromAscii("/UNO/SERVICES");
        Reference<XRegistryKey> xNewKey = xKey->createKey(aImpl);
        xNewKey->createKey(OUString::createFromAscii(pServiceName));
    }
    return sal_True;
}

void* SAL_CALL
component_getFactory(
    const sal_Char* pImplementationName,
    void* pServiceManager,
    void* pRegistryKey)
{
    // Set default return value for this operation - if it failed.
    if  ( pImplementationName && pServiceManager )
    {
        Reference< XSingleServiceFactory > xFactory;
        Reference< XMultiServiceFactory > xServiceManager(
            reinterpret_cast< XMultiServiceFactory* >( pServiceManager ) ) ;

        // search implementation
        for (int i = 0; (pImplementations[i]!=NULL); i++) {
            if ( strcmp(pImplementations[i], pImplementationName ) == 0 ) {
                // found implementation
                xFactory = Reference<XSingleServiceFactory>(cppu::createSingleFactory(
                    xServiceManager, OUString::createFromAscii(pImplementationName),
                    pInstanceProviders[i], getSupportedServiceNames(i)));
                if ( xFactory.is() ) {
                    // Factory is valid - service was found.
                    xFactory->acquire();
                    return xFactory.get();
                }
            }
        } // for()
    }
    // Return with result of this operation.
    return NULL;
}
} // extern "C"
<commit_msg>INTEGRATION: CWS ooo19126 (1.4.126); FILE MERGED 2005/09/05 17:50:59 rt 1.4.126.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: services.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 17:48:36 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include "evaluation.hxx"

#ifndef _COM_SUN_STAR_BEANS_NAMEDVALUE_HPP_
#include <com/sun/star/beans/NamedValue.hpp>
#endif
#ifndef _COM_SUN_STAR_REGISTRY_XREGISTRYKEY_HPP_
#include <com/sun/star/registry/XRegistryKey.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_DATE_HPP_
#include <com/sun/star/util/Date.hpp>
#endif

#ifndef _UNO_ENVIRONMENT_H_
#include <uno/environment.h>
#endif
#ifndef _CPPUHELPER_FACTORY_HXX_
#include <cppuhelper/factory.hxx>
#endif
#ifndef _UTL_CONFIGMGR_HXX_
#include <unotools/configmgr.hxx>
#endif

#include "oemjob.hxx"
#include "evaluation.hxx"

using namespace rtl;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::registry;
using namespace ::desktop;

static const char* pServices[] =
{
    SOEvaluation::serviceName,
    OEMPreloadJob::serviceName,
    NULL
};

static const char* pImplementations[] =
{
    SOEvaluation::implementationName,
    OEMPreloadJob::implementationName,
    NULL
};

typedef Reference<XInterface>(* fProvider)(const Reference<XMultiServiceFactory>&);

static const fProvider pInstanceProviders[] =
{
    SOEvaluation::CreateInstance,
    OEMPreloadJob::CreateInstance,
    NULL
};

static const char** pSupportedServices[] =
{
    SOEvaluation::interfaces,
    OEMPreloadJob::interfaces,
    NULL
};

static Sequence<OUString>
getSupportedServiceNames(int p) {
    const char **names = pSupportedServices[p];
    Sequence<OUString> aSeq;
    for(int i = 0; names[i] != NULL; i++) {
        aSeq.realloc(i+1);
        aSeq[i] = OUString::createFromAscii(names[i]);
    }
    return aSeq;
}

extern "C"
{
void SAL_CALL
component_getImplementationEnvironment(
    const sal_Char** ppEnvironmentTypeName,
    uno_Environment** ppEnvironment)
{
    *ppEnvironmentTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME ;
}

sal_Bool SAL_CALL
component_writeInfo(
    void* pServiceManager,
    void* pRegistryKey)
{
    Reference<XMultiServiceFactory> xMan(
        reinterpret_cast< XMultiServiceFactory* >( pServiceManager ) ) ;
    Reference<XRegistryKey> xKey(
        reinterpret_cast< XRegistryKey* >( pRegistryKey ) ) ;

    // iterate over service names and register them...
    OUString aImpl;
    const char* pServiceName = NULL;
    const char* pImplName = NULL;
    for (int i = 0; (pServices[i]!=NULL)&&(pImplementations[i]!=NULL); i++) {
        pServiceName= pServices[i];
        pImplName = pImplementations[i];
        aImpl = OUString::createFromAscii("/")
              + OUString::createFromAscii(pImplName)
              + OUString::createFromAscii("/UNO/SERVICES");
        Reference<XRegistryKey> xNewKey = xKey->createKey(aImpl);
        xNewKey->createKey(OUString::createFromAscii(pServiceName));
    }
    return sal_True;
}

void* SAL_CALL
component_getFactory(
    const sal_Char* pImplementationName,
    void* pServiceManager,
    void* pRegistryKey)
{
    // Set default return value for this operation - if it failed.
    if  ( pImplementationName && pServiceManager )
    {
        Reference< XSingleServiceFactory > xFactory;
        Reference< XMultiServiceFactory > xServiceManager(
            reinterpret_cast< XMultiServiceFactory* >( pServiceManager ) ) ;

        // search implementation
        for (int i = 0; (pImplementations[i]!=NULL); i++) {
            if ( strcmp(pImplementations[i], pImplementationName ) == 0 ) {
                // found implementation
                xFactory = Reference<XSingleServiceFactory>(cppu::createSingleFactory(
                    xServiceManager, OUString::createFromAscii(pImplementationName),
                    pInstanceProviders[i], getSupportedServiceNames(i)));
                if ( xFactory.is() ) {
                    // Factory is valid - service was found.
                    xFactory->acquire();
                    return xFactory.get();
                }
            }
        } // for()
    }
    // Return with result of this operation.
    return NULL;
}
} // extern "C"
<|endoftext|>


<commit_before>// implementation for p_evaluate.h

#include <Rd/r_index.h>
#include <Rd/cdf_utils.h>
#include <utils/array1d.h>
#include <numerics/schoenberg_splines.h>

namespace WaveletTL
{
  template <int d, int dT>
  SampledMapping<1>
  evaluate(const PBasis<d,dT>& basis,
	   const typename PBasis<d,dT>::Index& lambda,
	   const bool primal,
	   const int resolution)
  {
    if (lambda.e() == 0) { // generator
      if (primal) {
	Grid<1> grid(0, 1, 1<<resolution);
 	MathTL::Array1D<double> values((1<<resolution)+1);
 	for (unsigned int i(0); i < values.size(); i++)
	  values[i] = evaluate(basis, 0, lambda, i*ldexp(1.0,-resolution));
	return SampledMapping<1>(grid, values);
      } else {
 	// dual
	int s0 = basis.get_s0();
	int s1 = basis.get_s1();
	const Matrix<double>& CLAT = basis.get_CLAT();
	// left boundary generator
	if (lambda.k() < basis.DeltaLTmin()+(int)CLAT.column_dimension()) {
	  if (s0 >= d-2) {
	    InfiniteVector<double, RIndex> coeffs;
	    for (unsigned int i(0); i < CLAT.row_dimension(); i++) {
	      double v(CLAT(i, lambda.k()-basis.DeltaLTmin()));
	      if (v != 0)
		coeffs.set_coefficient(RIndex(lambda.j(), 0, 1-ell2T<d,dT>()+i), v);
	    }
	    return basis.get_CDF_basis().evaluate(0, coeffs, primal, 0, 1, resolution);
	  }
	  else {
	    InfiniteVector<double, RIndex> coeffs;
	    for (unsigned int i(0); i < CLAT.row_dimension(); i++) {
	      double v(CLAT(i, lambda.k()-basis.DeltaLTmin()));
	      if (v != 0)
		coeffs.set_coefficient(RIndex(lambda.j()+1, 0, 1-ell2T<d,dT>()+i), v);
	    }
	    return basis.get_CDF_basis().evaluate(0, coeffs, primal, 0, 1, resolution);
	  }
	}
	// no left boundary generator
	else {
	  const Matrix<double>& CRAT = basis.get_CRAT();
	  if (lambda.k() > basis.DeltaRTmax(lambda.j())-(int)CRAT.column_dimension()) {
	    if (s1 >= d-2) {
	      // right boundary generator
	      InfiniteVector<double, RIndex> coeffs;
	      for (unsigned int i(0); i < CRAT.row_dimension(); i++) {
		double v(CRAT(i, basis.DeltaRTmax(lambda.j())-lambda.k()));
		if (v != 0)
		  coeffs.set_coefficient(RIndex(lambda.j(), 0, (1<<lambda.j())-ell1<d>()-ell2<d>()-(1-ell2T<d,dT>()+i)), v);
	      }
	      return basis.get_CDF_basis().evaluate(0, coeffs, primal, 0, 1, resolution);
	    }
	    else {
	      InfiniteVector<double, RIndex> coeffs;
	      for (unsigned int i(0); i < CRAT.row_dimension(); i++) {
		double v(CRAT(i, basis.DeltaRTmax(lambda.j())-lambda.k()));
		if (v != 0)
		  coeffs.set_coefficient(RIndex(lambda.j()+1, 0, (1<<lambda.j()+1)-ell1<d>()-ell2<d>()-(1-ell2T<d,dT>()+i)), v);
	      }
	      return basis.get_CDF_basis().evaluate(0, coeffs, primal, 0, 1, resolution);
	    }
	  }
	   // inner generator
	  else {
	    return basis.get_CDF_basis().evaluate(0, RIndex(lambda.j(), 0, lambda.k()),
						  primal, 0, 1, resolution);
	  }
	}
      }
    }
    else { // wavelet
      InfiniteVector<double, typename PBasis<d,dT>::Index> gcoeffs;
      if (primal)
	basis.reconstruct_1(lambda, lambda.j()+1, gcoeffs);
      else
	basis.reconstruct_t_1(lambda, lambda.j()+1, gcoeffs);

      return evaluate(basis, gcoeffs, primal, resolution);
    }

    return SampledMapping<1>(); // dummy return for the compiler
  }

  template <int d, int dT>
  SampledMapping<1>
  evaluate(const PBasis<d,dT>& basis,
	   const InfiniteVector<double, typename PBasis<d,dT>::Index>& coeffs,
	   const bool primal,
	   const int resolution)
  {
    SampledMapping<1> result(Grid<1>(0, 1, 1<<resolution)); // zero
    if (coeffs.size() > 0) {
      // determine maximal level
      int jmax(0);
      typedef typename PBasis<d,dT>::Index Index;
      for (typename InfiniteVector<double,Index>::const_iterator it(coeffs.begin()),
	     itend(coeffs.end()); it != itend; ++it)
	jmax = std::max(it.index().j()+it.index().e(), jmax);

      // switch to generator representation
      InfiniteVector<double,Index> gcoeffs;
      if (primal)
	basis.reconstruct(coeffs,jmax,gcoeffs);
      else
	basis.reconstruct_t(coeffs,jmax,gcoeffs);

      for (typename InfiniteVector<double,Index>::const_iterator it(gcoeffs.begin()),
	     itend(gcoeffs.end()); it != itend; ++it)
	result.add(*it, evaluate(basis, it.index(), primal, resolution));
    }

    return result;
  }

  template <int d, int dT>
  double evaluate(const PBasis<d,dT>& basis, const unsigned int derivative,
		  const typename PBasis<d,dT>::Index& lambda,
		  const double x)
  {
    assert(derivative <= 1); // we only support derivatives up to the first order

    double r = 0;

    if (lambda.e() == 0) {
      // generator
      if (lambda.k() > (1<<lambda.j())-ell1<d>()-d) {
	switch (derivative){
	case 0: r= MathTL::EvaluateSchoenbergBSpline_td<d>  (lambda.j(),
							 (1<<lambda.j())-d-lambda.k()-2*ell1<d>(),
								1-x);
	  break;
	case 1: r=MathTL::EvaluateSchoenbergBSpline_td_x<d>(lambda.j(),
							  (1<<lambda.j())-d-lambda.k()-2*ell1<d>(),
								1-x);
	  break;
	case 2: r=MathTL::EvaluateSchoenbergBSpline_td_xx<d>(lambda.j(),
							  (1<<lambda.j())-d-lambda.k()-2*ell1<d>(),
								1-x);
	  break;
	}
      } else {
	switch (derivative){
	  case 0: r=MathTL::EvaluateSchoenbergBSpline_td<d>  (lambda.j(), lambda.k(), x);
	  break;
	  case 1: r=MathTL::EvaluateSchoenbergBSpline_td_x<d>(lambda.j(), lambda.k(), x);
	  break;
	  case 2: r=MathTL::EvaluateSchoenbergBSpline_td_xx<d>(lambda.j(), lambda.k(), x);
	  break;
	}
      }
    } else {
      // wavelet
      typedef typename PBasis<d,dT>::Index Index;
      InfiniteVector<double,Index> gcoeffs;
      basis.reconstruct_1(lambda, lambda.j()+1, gcoeffs);
      for (typename InfiniteVector<double,Index>::const_iterator it(gcoeffs.begin());
 	   it != gcoeffs.end(); ++it)
 	r += *it * evaluate(basis, derivative, it.index(), x);
    }

    return r;
  }

  template <int d, int dT>
  void
  evaluate(const PBasis<d,dT>& basis, const unsigned int derivative,
	   const typename PBasis<d,dT>::Index& lambda,
	   const Array1D<double>& points, Array1D<double>& values)
  {
    assert(derivative <= 2); // we only support derivatives up to the second order

    values.resize(points.size());
    for (unsigned int i(0); i < values.size(); i++)
      values[i] = 0;

    if (lambda.e() == 0) {
      // generator
      if (lambda.k() > (1<<lambda.j())-ell1<d>()-d)
	switch (derivative) {
	case 0:
	  for (unsigned int m(0); m < points.size(); m++)
	    values[m] = MathTL::EvaluateSchoenbergBSpline_td<d>(lambda.j(),
								(1<<lambda.j())-d-lambda.k()-2*ell1<d>(),
								1-points[m]);
	  break;

	case 1:
	  for (unsigned int m(0); m < points.size(); m++)
	    values[m] = -MathTL::EvaluateSchoenbergBSpline_td_x<d>(lambda.j(),
								   (1<<lambda.j())-d-lambda.k()-2*ell1<d>(),
								   1-points[m]);
	  break;

	case 2:
	  for (unsigned int m(0); m < points.size(); m++)
	    values[m] = -MathTL::EvaluateSchoenbergBSpline_td_xx<d>(lambda.j(),
								   (1<<lambda.j())-d-lambda.k()-2*ell1<d>(),
								   1-points[m]);
	  break;
	}
      else
	switch (derivative) {
	  case 0:
	    for (unsigned int m(0); m < points.size(); m++)
	    values[m] = MathTL::EvaluateSchoenbergBSpline_td<d>(lambda.j(),
								lambda.k(),
								points[m]);
	    break;

	case 1:
	  for (unsigned int m(0); m < points.size(); m++)
	    values[m] = MathTL::EvaluateSchoenbergBSpline_td_x<d>(lambda.j(),
								  lambda.k(),
								  points[m]);
	  break;

	case 2:
	  for (unsigned int m(0); m < points.size(); m++)
	    values[m] = MathTL::EvaluateSchoenbergBSpline_td_xx<d>(lambda.j(),
								  lambda.k(),
								  points[m]);
	  break;

	}

    } else {
      // wavelet
      typedef typename PBasis<d,dT>::Index Index;
      InfiniteVector<double,Index> gcoeffs;
      basis.reconstruct_1(lambda, lambda.j()+1, gcoeffs);
      Array1D<double> help(points.size());
      for (typename InfiniteVector<double,Index>::const_iterator it(gcoeffs.begin());
	   it != gcoeffs.end(); ++it)
	{
	  evaluate(basis, derivative, it.index(), points, help);
	  for (unsigned int i = 0; i < points.size(); i++)
	    values[i] += *it * help[i];
	}
    }
  }

  template <int d, int dT>
  void evaluate(const PBasis<d,dT>& basis,
		const typename PBasis<d,dT>::Index& lambda,
		const Array1D<double>& points, Array1D<double>& funcvalues, Array1D<double>& dervalues)
  {
    const unsigned int npoints(points.size());
    funcvalues.resize(npoints);
    dervalues.resize(npoints);
    for (unsigned int i(0); i < npoints; i++) {
      funcvalues[i] = 0;
      dervalues[i] = 0;
    }

    if (lambda.e() == 0) {
      // generator
      if (lambda.k() > (1<<lambda.j())-ell1<d>()-d) {
	for (unsigned int m(0); m < npoints; m++) {
	  funcvalues[m] = MathTL::EvaluateSchoenbergBSpline_td<d>  (lambda.j(),
								    (1<<lambda.j())-d-lambda.k()-2*ell1<d>(),
								    1-points[m]);
	  dervalues[m]  = -MathTL::EvaluateSchoenbergBSpline_td_x<d>(lambda.j(),
								     (1<<lambda.j())-d-lambda.k()-2*ell1<d>(),
								     1-points[m]);
	}
      } else {
	for (unsigned int m(0); m < npoints; m++) {
	  funcvalues[m] = MathTL::EvaluateSchoenbergBSpline_td<d>  (lambda.j(),
								    lambda.k(),
								    points[m]);
	  dervalues[m]  = MathTL::EvaluateSchoenbergBSpline_td_x<d>(lambda.j(),
								    lambda.k(),
								    points[m]);
	}
      }
    } else {
      // wavelet
      typedef typename PBasis<d,dT>::Index Index;
      InfiniteVector<double,Index> gcoeffs;
      basis.reconstruct_1(lambda, lambda.j()+1, gcoeffs);
      Array1D<double> help1, help2;
      for (typename InfiniteVector<double,Index>::const_iterator it(gcoeffs.begin());
	   it != gcoeffs.end(); ++it)
	{
	  evaluate(basis, it.index(), points, help1, help2);
	  for (unsigned int i = 0; i < npoints; i++) {
	    funcvalues[i] += *it * help1[i];
	    dervalues[i]  += *it * help2[i];
	  }
	}
    }
  }
}
<commit_msg>Minor mistakes eliminated<commit_after>// implementation for p_evaluate.h

#include <Rd/r_index.h>
#include <Rd/cdf_utils.h>
#include <utils/array1d.h>
#include <numerics/schoenberg_splines.h>

namespace WaveletTL
{
  template <int d, int dT>
  SampledMapping<1>
  evaluate(const PBasis<d,dT>& basis,
	   const typename PBasis<d,dT>::Index& lambda,
	   const bool primal,
	   const int resolution)
  {
    if (lambda.e() == 0) { // generator
      if (primal) {
	Grid<1> grid(0, 1, 1<<resolution);
 	MathTL::Array1D<double> values((1<<resolution)+1);
 	for (unsigned int i(0); i < values.size(); i++)
	  values[i] = evaluate(basis, 0, lambda, i*ldexp(1.0,-resolution));
	return SampledMapping<1>(grid, values);
      } else {
 	// dual
	int s0 = basis.get_s0();
	int s1 = basis.get_s1();
	const Matrix<double>& CLAT = basis.get_CLAT();
	// left boundary generator
	if (lambda.k() < basis.DeltaLTmin()+(int)CLAT.column_dimension()) {
	  if (s0 >= d-2) {
	    InfiniteVector<double, RIndex> coeffs;
	    for (unsigned int i(0); i < CLAT.row_dimension(); i++) {
	      double v(CLAT(i, lambda.k()-basis.DeltaLTmin()));
	      if (v != 0)
		coeffs.set_coefficient(RIndex(lambda.j(), 0, 1-ell2T<d,dT>()+i), v);
	    }
	    return basis.get_CDF_basis().evaluate(0, coeffs, primal, 0, 1, resolution);
	  }
	  else {
	    InfiniteVector<double, RIndex> coeffs;
	    for (unsigned int i(0); i < CLAT.row_dimension(); i++) {
	      double v(CLAT(i, lambda.k()-basis.DeltaLTmin()));
	      if (v != 0)
		coeffs.set_coefficient(RIndex(lambda.j()+1, 0, 1-ell2T<d,dT>()+i), v);
	    }
	    return basis.get_CDF_basis().evaluate(0, coeffs, primal, 0, 1, resolution);
	  }
	}
	// no left boundary generator
	else {
	  const Matrix<double>& CRAT = basis.get_CRAT();
	  if (lambda.k() > basis.DeltaRTmax(lambda.j())-(int)CRAT.column_dimension()) {
	    if (s1 >= d-2) {
	      // right boundary generator
	      InfiniteVector<double, RIndex> coeffs;
	      for (unsigned int i(0); i < CRAT.row_dimension(); i++) {
		double v(CRAT(i, basis.DeltaRTmax(lambda.j())-lambda.k()));
		if (v != 0)
		  coeffs.set_coefficient(RIndex(lambda.j(), 0, (1<<lambda.j())-ell1<d>()-ell2<d>()-(1-ell2T<d,dT>()+i)), v);
	      }
	      return basis.get_CDF_basis().evaluate(0, coeffs, primal, 0, 1, resolution);
	    }
	    else {
	      InfiniteVector<double, RIndex> coeffs;
	      for (unsigned int i(0); i < CRAT.row_dimension(); i++) {
		double v(CRAT(i, basis.DeltaRTmax(lambda.j())-lambda.k()));
		if (v != 0)
		  coeffs.set_coefficient(RIndex(lambda.j()+1, 0, (1<<lambda.j()+1)-ell1<d>()-ell2<d>()-(1-ell2T<d,dT>()+i)), v);
	      }
	      return basis.get_CDF_basis().evaluate(0, coeffs, primal, 0, 1, resolution);
	    }
	  }
	   // inner generator
	  else {
	    return basis.get_CDF_basis().evaluate(0, RIndex(lambda.j(), 0, lambda.k()),
						  primal, 0, 1, resolution);
	  }
	}
      }
    }
    else { // wavelet
      InfiniteVector<double, typename PBasis<d,dT>::Index> gcoeffs;
      if (primal)
	basis.reconstruct_1(lambda, lambda.j()+1, gcoeffs);
      else
	basis.reconstruct_t_1(lambda, lambda.j()+1, gcoeffs);

      return evaluate(basis, gcoeffs, primal, resolution);
    }

    return SampledMapping<1>(); // dummy return for the compiler
  }

  template <int d, int dT>
  SampledMapping<1>
  evaluate(const PBasis<d,dT>& basis,
	   const InfiniteVector<double, typename PBasis<d,dT>::Index>& coeffs,
	   const bool primal,
	   const int resolution)
  {
    SampledMapping<1> result(Grid<1>(0, 1, 1<<resolution)); // zero
    if (coeffs.size() > 0) {
      // determine maximal level
      int jmax(0);
      typedef typename PBasis<d,dT>::Index Index;
      for (typename InfiniteVector<double,Index>::const_iterator it(coeffs.begin()),
	     itend(coeffs.end()); it != itend; ++it)
	jmax = std::max(it.index().j()+it.index().e(), jmax);

      // switch to generator representation
      InfiniteVector<double,Index> gcoeffs;
      if (primal)
	basis.reconstruct(coeffs,jmax,gcoeffs);
      else
	basis.reconstruct_t(coeffs,jmax,gcoeffs);

      for (typename InfiniteVector<double,Index>::const_iterator it(gcoeffs.begin()),
	     itend(gcoeffs.end()); it != itend; ++it)
	result.add(*it, evaluate(basis, it.index(), primal, resolution));
    }

    return result;
  }

  template <int d, int dT>
  double evaluate(const PBasis<d,dT>& basis, const unsigned int derivative,
		  const typename PBasis<d,dT>::Index& lambda,
		  const double x)
  {
    assert(derivative <= 1); // we only support derivatives up to the first order

    double r = 0;

    if (lambda.e() == 0) {
      // generator
      if (lambda.k() > (1<<lambda.j())-ell1<d>()-d) {
	switch (derivative){
	case 0: r= MathTL::EvaluateSchoenbergBSpline_td<d>  (lambda.j(),
							 (1<<lambda.j())-d-lambda.k()-2*ell1<d>(),
								1-x);
	  break;
	case 1: r=-MathTL::EvaluateSchoenbergBSpline_td_x<d>(lambda.j(),
							  (1<<lambda.j())-d-lambda.k()-2*ell1<d>(),
								1-x);
	  break;
	case 2: r=MathTL::EvaluateSchoenbergBSpline_td_xx<d>(lambda.j(),
							  (1<<lambda.j())-d-lambda.k()-2*ell1<d>(),
								1-x);
	  break;
	}
      } else {
	switch (derivative){
	  case 0: r=MathTL::EvaluateSchoenbergBSpline_td<d>  (lambda.j(), lambda.k(), x);
	  break;
	  case 1: r=MathTL::EvaluateSchoenbergBSpline_td_x<d>(lambda.j(), lambda.k(), x);
	  break;
	  case 2: r=MathTL::EvaluateSchoenbergBSpline_td_xx<d>(lambda.j(), lambda.k(), x);
	  break;
	}
      }
    } else {
      // wavelet
      typedef typename PBasis<d,dT>::Index Index;
      InfiniteVector<double,Index> gcoeffs;
      basis.reconstruct_1(lambda, lambda.j()+1, gcoeffs);
      for (typename InfiniteVector<double,Index>::const_iterator it(gcoeffs.begin());
 	   it != gcoeffs.end(); ++it)
 	r += *it * evaluate(basis, derivative, it.index(), x);
    }

    return r;
  }

  template <int d, int dT>
  void
  evaluate(const PBasis<d,dT>& basis, const unsigned int derivative,
	   const typename PBasis<d,dT>::Index& lambda,
	   const Array1D<double>& points, Array1D<double>& values)
  {
    assert(derivative <= 2); // we only support derivatives up to the second order

    values.resize(points.size());
    for (unsigned int i(0); i < values.size(); i++)
      values[i] = 0;

    if (lambda.e() == 0) {
      // generator
      if (lambda.k() > (1<<lambda.j())-ell1<d>()-d)
	switch (derivative) {
	case 0:
	  for (unsigned int m(0); m < points.size(); m++)
	    values[m] = MathTL::EvaluateSchoenbergBSpline_td<d>(lambda.j(),
								(1<<lambda.j())-d-lambda.k()-2*ell1<d>(),
								1-points[m]);
	  break;

	case 1:
	  for (unsigned int m(0); m < points.size(); m++)
	    values[m] = -MathTL::EvaluateSchoenbergBSpline_td_x<d>(lambda.j(),
								   (1<<lambda.j())-d-lambda.k()-2*ell1<d>(),
								   1-points[m]);
	  break;

	case 2:
	  for (unsigned int m(0); m < points.size(); m++)
	    values[m] = MathTL::EvaluateSchoenbergBSpline_td_xx<d>(lambda.j(),
								   (1<<lambda.j())-d-lambda.k()-2*ell1<d>(),
								   1-points[m]);
	  break;
	}
      else
	switch (derivative) {
	  case 0:
	    for (unsigned int m(0); m < points.size(); m++)
	    values[m] = MathTL::EvaluateSchoenbergBSpline_td<d>(lambda.j(),
								lambda.k(),
								points[m]);
	    break;

	case 1:
	  for (unsigned int m(0); m < points.size(); m++)
	    values[m] = MathTL::EvaluateSchoenbergBSpline_td_x<d>(lambda.j(),
								  lambda.k(),
								  points[m]);
	  break;

	case 2:
	  for (unsigned int m(0); m < points.size(); m++)
	    values[m] = MathTL::EvaluateSchoenbergBSpline_td_xx<d>(lambda.j(),
								  lambda.k(),
								  points[m]);
	  break;

	}

    } else {
      // wavelet
      typedef typename PBasis<d,dT>::Index Index;
      InfiniteVector<double,Index> gcoeffs;
      basis.reconstruct_1(lambda, lambda.j()+1, gcoeffs);
      Array1D<double> help(points.size());
      for (typename InfiniteVector<double,Index>::const_iterator it(gcoeffs.begin());
	   it != gcoeffs.end(); ++it)
	{
	  evaluate(basis, derivative, it.index(), points, help);
	  for (unsigned int i = 0; i < points.size(); i++)
	    values[i] += *it * help[i];
	}
    }
  }

  template <int d, int dT>
  void evaluate(const PBasis<d,dT>& basis,
		const typename PBasis<d,dT>::Index& lambda,
		const Array1D<double>& points, Array1D<double>& funcvalues, Array1D<double>& dervalues)
  {
    const unsigned int npoints(points.size());
    funcvalues.resize(npoints);
    dervalues.resize(npoints);
    for (unsigned int i(0); i < npoints; i++) {
      funcvalues[i] = 0;
      dervalues[i] = 0;
    }

    if (lambda.e() == 0) {
      // generator
      if (lambda.k() > (1<<lambda.j())-ell1<d>()-d) {
	for (unsigned int m(0); m < npoints; m++) {
	  funcvalues[m] = MathTL::EvaluateSchoenbergBSpline_td<d>  (lambda.j(),
								    (1<<lambda.j())-d-lambda.k()-2*ell1<d>(),
								    1-points[m]);
	  dervalues[m]  = -MathTL::EvaluateSchoenbergBSpline_td_x<d>(lambda.j(),
								     (1<<lambda.j())-d-lambda.k()-2*ell1<d>(),
								     1-points[m]);
	}
      } else {
	for (unsigned int m(0); m < npoints; m++) {
	  funcvalues[m] = MathTL::EvaluateSchoenbergBSpline_td<d>  (lambda.j(),
								    lambda.k(),
								    points[m]);
	  dervalues[m]  = MathTL::EvaluateSchoenbergBSpline_td_x<d>(lambda.j(),
								    lambda.k(),
								    points[m]);
	}
      }
    } else {
      // wavelet
      typedef typename PBasis<d,dT>::Index Index;
      InfiniteVector<double,Index> gcoeffs;
      basis.reconstruct_1(lambda, lambda.j()+1, gcoeffs);
      Array1D<double> help1, help2;
      for (typename InfiniteVector<double,Index>::const_iterator it(gcoeffs.begin());
	   it != gcoeffs.end(); ++it)
	{
	  evaluate(basis, it.index(), points, help1, help2);
	  for (unsigned int i = 0; i < npoints; i++) {
	    funcvalues[i] += *it * help1[i];
	    dervalues[i]  += *it * help2[i];
	  }
	}
    }
  }
}
<|endoftext|>


<commit_before>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2015, Youssef Kashef
// Copyright (c) 2015, ELM Library Project
// 3-clause BSD License
//
//M*/
#include "elm/layers/base_layer_derivations/base_filterbanklayer.h"

#include <opencv2/features2d/features2d.hpp>
#include <opencv2/imgproc/imgproc.hpp>

#include "elm/core/cv/mat_vector_utils.h"
#include "elm/core/layeroutputnames.h"
#include "elm/core/signal.h"

using namespace cv;
using namespace elm;

base_FilterBankLayer::~base_FilterBankLayer()
{
}

base_FilterBankLayer::base_FilterBankLayer()
    : base_SingleInputFeatureLayer()
{
}

base_FilterBankLayer::base_FilterBankLayer(const LayerConfig &cfg)
    : base_SingleInputFeatureLayer(cfg)
{
}

void base_FilterBankLayer::Clear()
{
    kernels_ = VecMat1f();
    response_ = VecMat1f();
}

void base_FilterBankLayer::Reset(const LayerConfig &config)
{
    Clear();
    Reconfigure(config);
    kernels_ = Kernels();
}

void base_FilterBankLayer::OutputNames(const LayerOutputNames &io)
{
    name_out_ = io.Output(KEY_OUTPUT_RESPONSE);
}

void base_FilterBankLayer::Activate(const Signal &signal)
{
    response_.clear();
    response_.reserve(kernels_.size());
    response_ = Convolve(signal.MostRecentMat1f(name_input_));
}

void base_FilterBankLayer::Response(Signal &signal)
{
    signal.Append(name_out_, response_);
}

VecMat1f base_FilterBankLayer::Convolve(const cv::Mat1f &stimulus)
{
    for(VecMat1f::const_iterator itr=kernels_.begin();
        itr != kernels_.end();
        itr++) {

        Mat1f r;
        filter2D(stimulus, r, -1, *itr, Point(-1, -1), 0, BORDER_REPLICATE);
        Rectify(r);
        response_.push_back(r);
    }
    return response_;
}

void base_FilterBankLayer::Rectify(Mat1f &response)
{
// default is to do nothing and leave response as is
}

Mat1f base_FilterBankLayer::ElementResponse(int r, int c) const
{
    return elm::ElementsAt(response_, r, c);
}

size_t base_FilterBankLayer::size() const
{
    return Kernels().size();
}
<commit_msg>responses are cleared with every call to Convolve()<commit_after>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2015, Youssef Kashef
// Copyright (c) 2015, ELM Library Project
// 3-clause BSD License
//
//M*/
#include "elm/layers/base_layer_derivations/base_filterbanklayer.h"

#include <opencv2/features2d/features2d.hpp>
#include <opencv2/imgproc/imgproc.hpp>

#include "elm/core/cv/mat_vector_utils.h"
#include "elm/core/layeroutputnames.h"
#include "elm/core/signal.h"

using namespace cv;
using namespace elm;

base_FilterBankLayer::~base_FilterBankLayer()
{
}

base_FilterBankLayer::base_FilterBankLayer()
    : base_SingleInputFeatureLayer()
{
}

base_FilterBankLayer::base_FilterBankLayer(const LayerConfig &cfg)
    : base_SingleInputFeatureLayer(cfg)
{
}

void base_FilterBankLayer::Clear()
{
    kernels_ = VecMat1f();
    response_ = VecMat1f();
}

void base_FilterBankLayer::Reset(const LayerConfig &config)
{
    Clear();
    Reconfigure(config);
    kernels_ = Kernels();
}

void base_FilterBankLayer::OutputNames(const LayerOutputNames &io)
{
    name_out_ = io.Output(KEY_OUTPUT_RESPONSE);
}

void base_FilterBankLayer::Activate(const Signal &signal)
{
    response_ = Convolve(signal.MostRecentMat1f(name_input_));
}

void base_FilterBankLayer::Response(Signal &signal)
{
    signal.Append(name_out_, response_);
}

VecMat1f base_FilterBankLayer::Convolve(const cv::Mat1f &stimulus)
{
    response_.clear();
    response_.reserve(kernels_.size());

    for(VecMat1f::const_iterator itr=kernels_.begin();
        itr != kernels_.end();
        itr++) {

        Mat1f r;
        filter2D(stimulus, r, -1, *itr, Point(-1, -1), 0, BORDER_REPLICATE);
        Rectify(r);
        response_.push_back(r);
    }
    return response_;
}

void base_FilterBankLayer::Rectify(Mat1f &response)
{
// default is to do nothing and leave response as is
}

Mat1f base_FilterBankLayer::ElementResponse(int r, int c) const
{
    return elm::ElementsAt(response_, r, c);
}

size_t base_FilterBankLayer::size() const
{
    return Kernels().size();
}
<|endoftext|>


<commit_before>//
//
// Copyright (C) 2004 SIPfoundry Inc.
// Licensed by SIPfoundry under the LGPL license.
//
// Copyright (C) 2004 Pingtel Corp.
// Licensed to SIPfoundry under a Contributor Agreement.
//
// $$
//////////////////////////////////////////////////////////////////////////////

// SYSTEM INCLUDES
#include <stdio.h>
#include <signal.h>
#include <iostream>

// APPLICATION INCLUDES
#ifndef SIPX_VERSION
#  include "sipxregistry-buildstamp.h"
#  define SIPXCHANGE_VERSION SipXregistryVersion
#  define SIPXCHANGE_VERSION_COMMENT SipXregistryBuildStamp
#else
#  define SIPXCHANGE_VERSION SIPX_VERSION
#  define SIPXCHANGE_VERSION_COMMENT ""
#endif

#include "os/OsConfigDb.h"
#include "os/OsFS.h"
#include "os/OsTask.h"

#include "net/NameValueTokenizer.h"
#include "sipdb/SIPDBManager.h"
#include "sipdb/ExtensionDB.h"
#include "SipRegistrar.h"

// DEFINES
#define CONFIG_SETTINGS_FILE  "registrar-config"
#define CONFIG_LOG_FILE       "sipregistrar.log"
#define CONFIG_LOG_DIR        SIPX_LOGDIR
#define CONFIG_ETC_DIR        SIPX_CONFDIR

#define CONFIG_SETTING_LOG_LEVEL      "SIP_REGISTRAR_LOG_LEVEL"
#define CONFIG_SETTING_LOG_CONSOLE    "SIP_REGISTRAR_LOG_CONSOLE"
#define CONFIG_SETTING_LOG_DIR        "SIP_REGISTRAR_LOG_DIR"
#define LOG_FACILITY                  FAC_SIP

// MACROS
// EXTERNAL FUNCTIONS
// EXTERNAL VARIABLES
// CONSTANTS
// STRUCTS
// TYPEDEFS
typedef void (*sighandler_t)(int);

using namespace std ;

// FUNCTIONS
extern "C" {
   void  sigHandler( int sig_num );
   sighandler_t pt_signal( int sig_num, sighandler_t handler );
}

// FORWARD DECLARATIONS
// EXTERNAL VARIABLES
// CONSTANTS
// STATIC VARIABLE INITIALIZATIONS
// GLOBAL VARIABLE INITIALIZATIONS
OsServerTask* pServerTask   = NULL;
UtlBoolean     gShutdownFlag = FALSE;
UtlBoolean     gClosingIMDB  = FALSE;
OsMutex*       gpLockMutex = new OsMutex(OsMutex::Q_FIFO);

/* ============================ FUNCTIONS ================================= */

/**
 * Description:
 * closes any open connections to the IMDB safely using a mutex lock
 */
void
closeIMDBConnections ()
{
   // Critical Section here
   OsLock lock( *gpLockMutex );
   SIPDBManager* db = SIPDBManager::getInstance();
   db->releaseAllDatabase();

   delete db;
}

/**
 * Description:
 * This is a replacement for signal() which registers a signal handler but sets
 * a flag causing system calls ( namely read() or getchar() ) not to bail out
 * upon recepit of that signal. We need this behavior, so we must call
 * sigaction() manually.
 */
sighandler_t
pt_signal( int sig_num, sighandler_t handler)
{
#if defined(__pingtel_on_posix__)
   struct sigaction action[2];
   action[0].sa_handler = handler;
   sigemptyset(&action[0].sa_mask);
   action[0].sa_flags = 0;
   sigaction ( sig_num, &action[0], &action[1] );
   return action[1].sa_handler;
#else
   return signal( sig_num, handler );
#endif
}

/**
 * Description:
 * This is the signal handler, When called this sets the
 * global gShutdownFlag allowing the main processing
 * loop to exit cleanly.
 */
void
sigHandler( int sig_num )
{
   // set a global shutdown flag
   gShutdownFlag = TRUE;

   // Unregister interest in the signal to prevent recursive callbacks
   pt_signal( sig_num, SIG_DFL );

   // Minimize the chance that we loose log data
   OsSysLog::flush();
   if (SIGTERM == sig_num)
   {
      OsSysLog::add( LOG_FACILITY, PRI_INFO, "sigHandler: terminate signal received.");
   }
   else
   {
      OsSysLog::add( LOG_FACILITY, PRI_CRIT, "sigHandler: caught signal: %d", sig_num );
   }
   OsSysLog::add( LOG_FACILITY, PRI_CRIT, "sigHandler: closing IMDB connections" );
   OsSysLog::flush();

   // Finally close the IMDB connections
   closeIMDBConnections();
}

// Initialize the OsSysLog
void
initSysLog(OsConfigDb* pConfig)
{
   UtlString logLevel;               // Controls Log Verbosity
   UtlString consoleLogging;         // Enable console logging by default?
   UtlString fileTarget;             // Path to store log file.
   UtlBoolean bSpecifiedDirError ;   // Set if the specified log dir does not
   // exist
   struct tagPriorityLookupTable
   {
      const char*      pIdentity;
      OsSysLogPriority ePriority;
   };

   struct tagPriorityLookupTable lkupTable[] =
      {
         { "DEBUG",   PRI_DEBUG},
         { "INFO",    PRI_INFO},
         { "NOTICE",  PRI_NOTICE},
         { "WARNING", PRI_WARNING},
         { "ERR",     PRI_ERR},
         { "CRIT",    PRI_CRIT},
         { "ALERT",   PRI_ALERT},
         { "EMERG",   PRI_EMERG},
      };
   OsSysLog::initialize(0, "SipRegistrar");

   //
   // Get/Apply Log Filename
   //
   fileTarget.remove(0) ;
   if ((pConfig->get(CONFIG_SETTING_LOG_DIR, fileTarget) != OS_SUCCESS) ||
       fileTarget.isNull() || !OsFileSystem::exists(fileTarget))
   {
      bSpecifiedDirError = !fileTarget.isNull() ;

      // If the log file directory exists use that, otherwise place the log
      // in the current directory
      OsPath workingDirectory;
      if (OsFileSystem::exists(CONFIG_LOG_DIR))
      {
         fileTarget = CONFIG_LOG_DIR;
         OsPath path(fileTarget);
         path.getNativePath(workingDirectory);

         osPrintf("%s : %s\n", CONFIG_SETTING_LOG_DIR, workingDirectory.data()) ;
         OsSysLog::add(LOG_FACILITY, PRI_INFO, "%s : %s", CONFIG_SETTING_LOG_DIR, workingDirectory.data()) ;
      }
      else
      {
         OsPath path;
         OsFileSystem::getWorkingDirectory(path);
         path.getNativePath(workingDirectory);

         osPrintf("%s : %s\n", CONFIG_SETTING_LOG_DIR, workingDirectory.data()) ;
         OsSysLog::add(LOG_FACILITY, PRI_INFO, "%s : %s", CONFIG_SETTING_LOG_DIR, workingDirectory.data()) ;
      }

      fileTarget = workingDirectory +
         OsPathBase::separator +
         CONFIG_LOG_FILE;
   }
   else
   {
      bSpecifiedDirError = false ;
      osPrintf("%s : %s\n", CONFIG_SETTING_LOG_DIR, fileTarget.data()) ;
      OsSysLog::add(LOG_FACILITY, PRI_INFO, "%s : %s", CONFIG_SETTING_LOG_DIR, fileTarget.data()) ;

      fileTarget = fileTarget +
         OsPathBase::separator +
         CONFIG_LOG_FILE;
   }
   OsSysLog::setOutputFile(0, fileTarget) ;

   //
   // Get/Apply Log Level
   //
   if ((pConfig->get(CONFIG_SETTING_LOG_LEVEL, logLevel) != OS_SUCCESS) ||
       logLevel.isNull())
   {
      logLevel = "NOTICE";
   }
   logLevel.toUpper();
   OsSysLogPriority priority = PRI_ERR;
   int iEntries = sizeof(lkupTable)/sizeof(struct tagPriorityLookupTable);
   for (int i=0; i<iEntries; i++)
   {
      if (logLevel == lkupTable[i].pIdentity)
      {
         priority = lkupTable[i].ePriority;
         osPrintf("%s : %s\n", CONFIG_SETTING_LOG_LEVEL, lkupTable[i].pIdentity) ;
         OsSysLog::add(LOG_FACILITY, PRI_INFO, "%s : %s", CONFIG_SETTING_LOG_LEVEL, lkupTable[i].pIdentity) ;
         break;
      }
   }
   OsSysLog::setLoggingPriority(priority);

   //
   // Get/Apply console logging
   //
   UtlBoolean bConsoleLoggingEnabled = false ;
   if ((pConfig->get(CONFIG_SETTING_LOG_CONSOLE, consoleLogging) ==
        OS_SUCCESS))
   {
      consoleLogging.toUpper();
      if (consoleLogging == "ENABLE")
      {
         OsSysLog::enableConsoleOutput(true);
         bConsoleLoggingEnabled = true ;
      }
   }

   OsSysLog::add(LOG_FACILITY, PRI_INFO, "%s : %s", CONFIG_SETTING_LOG_CONSOLE,
                 bConsoleLoggingEnabled ? "ENABLE" : "DISABLE") ;

   if (bSpecifiedDirError)
   {
      OsSysLog::add(FAC_LOG, PRI_CRIT,
                    "Cannot access directory '%s'; please check configuration.",
                    CONFIG_SETTING_LOG_DIR);
   }
}

/** The main entry point to the sipregistrar */
int
main(int argc, char* argv[] )
{
   // Configuration Database (used for OsSysLog)
   OsConfigDb configDb;

   // Register Signal handlers to close IMDB
   pt_signal(SIGINT,   sigHandler);    // Trap Ctrl-C on NT
   pt_signal(SIGILL,   sigHandler);
   pt_signal(SIGABRT,  sigHandler);    // Abort signal 6
   pt_signal(SIGFPE,   sigHandler);    // Floading Point Exception
   pt_signal(SIGSEGV,  sigHandler);    // Address access violations signal 11
   pt_signal(SIGTERM,  sigHandler);    // Trap kill -15 on UNIX
#if defined(__pingtel_on_posix__)
   pt_signal(SIGHUP,   sigHandler);    // Hangup
   pt_signal(SIGQUIT,  sigHandler);
   pt_signal(SIGPIPE,  SIG_IGN);    // Handle TCP Failure
   pt_signal(SIGBUS,   sigHandler);
   pt_signal(SIGSYS,   sigHandler);
   pt_signal(SIGXCPU,  sigHandler);
   pt_signal(SIGXFSZ,  sigHandler);
   pt_signal(SIGUSR1,  sigHandler);
   pt_signal(SIGUSR2,  sigHandler);
#endif

   UtlBoolean interactiveSet = false;
   UtlString argString;
   for (int argIndex = 1; argIndex < argc; argIndex++)
   {
      osPrintf("arg[%d]: %s\n", argIndex, argv[argIndex]);
      argString = argv[argIndex];
      NameValueTokenizer::frontBackTrim(&argString, "\t ");
      if (argString.compareTo("-v") == 0)
      {
         osPrintf("Version: %s (%s)\n", SIPXCHANGE_VERSION, SIPXCHANGE_VERSION_COMMENT);
         return(1);
      }
      else if ( argString.compareTo("-i") == 0)
      {
         interactiveSet = true;
         osPrintf("Entering Interactive Mode\n");
      }
      else
      {
         osPrintf("usage: %s [-v] [-i]\nwhere:\n -v provides the software version\n"
                  " -i start the server in an interactive mode\n",
                  argv[0]);
         return(1);
      }
   }

   // initialize log file
   OsPath workingDirectory;
   if (OsFileSystem::exists(CONFIG_ETC_DIR))
   {
      workingDirectory = CONFIG_ETC_DIR;
      OsPath path(workingDirectory);
      path.getNativePath(workingDirectory);
   }
   else
   {
      OsPath path;
      OsFileSystem::getWorkingDirectory(path);
      path.getNativePath(workingDirectory);
   }

   UtlString fileName =  workingDirectory +
      OsPathBase::separator +
      CONFIG_SETTINGS_FILE;

   bool configLoaded = ( configDb.loadFromFile(fileName) == OS_SUCCESS );
   if (!configLoaded)
   {
      configDb.set("SIP_REGISTRAR_UDP_PORT", "5070");
      configDb.set("SIP_REGISTRAR_TCP_PORT", "5070");
      configDb.set("SIP_REGISTRAR_TLS_PORT", "5071");
      configDb.set("SIP_REGISTRAR_PROXY_PORT", "5060");
      configDb.set("SIP_REGISTRAR_MAX_EXPIRES", "");
      configDb.set("SIP_REGISTRAR_MIN_EXPIRES", "");
      configDb.set("SIP_REGISTRAR_DOMAIN_NAME", "");
      //configDb.set("SIP_REGISTRAR_AUTHENTICATE_SCHEME", "");
      configDb.set("SIP_REGISTRAR_AUTHENTICATE_ALGORITHM", "");
      configDb.set("SIP_REGISTRAR_AUTHENTICATE_QOP", "");
      configDb.set("SIP_REGISTRAR_AUTHENTICATE_REALM", "");

      configDb.set("SIP_REGISTRAR_MEDIA_SERVER", "");
      configDb.set("SIP_REGISTRAR_VOICEMAIL_SERVER", "");
      configDb.set(CONFIG_SETTING_LOG_DIR, "");
      configDb.set(CONFIG_SETTING_LOG_LEVEL, "");
      configDb.set(CONFIG_SETTING_LOG_CONSOLE, "");
   }

   initSysLog(&configDb) ;
   OsSysLog::add(FAC_SIP, PRI_NOTICE,
                 "SipRegistrar >>>>>>>>>>>>>>>> STARTED"
                 );
   if (configLoaded)
   {
      OsSysLog::add(FAC_SIP, PRI_INFO, "Read config %s", fileName.data());
   }
   else
   {
      if (configDb.storeToFile(fileName) == OS_SUCCESS)
      {
         OsSysLog::add( FAC_SIP, PRI_INFO, "Default config written to: %s",
                       fileName.data()
                       );
      }
      else
      {
         OsSysLog::add( FAC_SIP, PRI_ERR, "Default config write failed to: %s",
                       fileName.data());
      }
   }

   // Fetch Pointer to the OsServer task object, note that
   // object uses the IMDB so it is important to shut this thread
   // cleanly before the signal handler exits
   SipRegistrar* registrar = SipRegistrar::getInstance(&configDb);

   registrar->start();

   pServerTask = static_cast<OsServerTask*>(registrar);

   // Do not exit, let the services run...
   while( !gShutdownFlag )
   {
      if ( interactiveSet)
      {

         int charCode = getchar();

         if (charCode != '\n' && charCode != '\r')
         {
            if ( charCode == 'e')
            {
               OsSysLog::enableConsoleOutput(TRUE);
            }
            else if ( charCode == 'd')
            {
               OsSysLog::enableConsoleOutput(FALSE);
            }
         }
      }
      else
      {
         OsTask::delay(2000);
      }
   }

   // Remove the current process's row from the IMDB
   // Persisting the database if necessary

   // This is a server task so gracefully shutdown the
   // server task using the waitForShutdown method, this
   // will implicitly request a shutdown for us if one is
   // not already in progress
   if ( pServerTask != NULL )
   {
      // Deleting a server task is the only way of
      // waiting for shutdown to complete cleanly
      pServerTask->requestShutdown();
      delete pServerTask;
      pServerTask = NULL;
   }

   // now deregister this process's database references from the IMDB
   closeIMDBConnections();

   // Flush the log file
   OsSysLog::flush();

   return 0;
}
<commit_msg>Heap-alloc the config DB, don't stack-alloc it, since we are passing it to SipRegistrar, which holds onto it for a little while.  Unlikely to cause problems in practice but must be done right.<commit_after>//
//
// Copyright (C) 2004 SIPfoundry Inc.
// Licensed by SIPfoundry under the LGPL license.
//
// Copyright (C) 2004 Pingtel Corp.
// Licensed to SIPfoundry under a Contributor Agreement.
//
// $$
//////////////////////////////////////////////////////////////////////////////

// SYSTEM INCLUDES
#include <stdio.h>
#include <signal.h>
#include <iostream>

// APPLICATION INCLUDES
#ifndef SIPX_VERSION
#  include "sipxregistry-buildstamp.h"
#  define SIPXCHANGE_VERSION SipXregistryVersion
#  define SIPXCHANGE_VERSION_COMMENT SipXregistryBuildStamp
#else
#  define SIPXCHANGE_VERSION SIPX_VERSION
#  define SIPXCHANGE_VERSION_COMMENT ""
#endif

#include "os/OsConfigDb.h"
#include "os/OsFS.h"
#include "os/OsTask.h"

#include "net/NameValueTokenizer.h"
#include "sipdb/SIPDBManager.h"
#include "sipdb/ExtensionDB.h"
#include "SipRegistrar.h"

// DEFINES
#define CONFIG_SETTINGS_FILE  "registrar-config"
#define CONFIG_LOG_FILE       "sipregistrar.log"
#define CONFIG_LOG_DIR        SIPX_LOGDIR
#define CONFIG_ETC_DIR        SIPX_CONFDIR

#define CONFIG_SETTING_LOG_LEVEL      "SIP_REGISTRAR_LOG_LEVEL"
#define CONFIG_SETTING_LOG_CONSOLE    "SIP_REGISTRAR_LOG_CONSOLE"
#define CONFIG_SETTING_LOG_DIR        "SIP_REGISTRAR_LOG_DIR"
#define LOG_FACILITY                  FAC_SIP

// MACROS
// EXTERNAL FUNCTIONS
// EXTERNAL VARIABLES
// CONSTANTS
// STRUCTS
// TYPEDEFS
typedef void (*sighandler_t)(int);

using namespace std ;

// FUNCTIONS
extern "C" {
   void  sigHandler( int sig_num );
   sighandler_t pt_signal( int sig_num, sighandler_t handler );
}

// FORWARD DECLARATIONS
// EXTERNAL VARIABLES
// CONSTANTS
// STATIC VARIABLE INITIALIZATIONS
// GLOBAL VARIABLE INITIALIZATIONS
OsServerTask* pServerTask   = NULL;
UtlBoolean     gShutdownFlag = FALSE;
UtlBoolean     gClosingIMDB  = FALSE;
OsMutex*       gpLockMutex = new OsMutex(OsMutex::Q_FIFO);

/* ============================ FUNCTIONS ================================= */

/**
 * Description:
 * closes any open connections to the IMDB safely using a mutex lock
 */
void
closeIMDBConnections ()
{
   // Critical Section here
   OsLock lock( *gpLockMutex );
   SIPDBManager* db = SIPDBManager::getInstance();
   db->releaseAllDatabase();

   delete db;
}

/**
 * Description:
 * This is a replacement for signal() which registers a signal handler but sets
 * a flag causing system calls ( namely read() or getchar() ) not to bail out
 * upon recepit of that signal. We need this behavior, so we must call
 * sigaction() manually.
 */
sighandler_t
pt_signal( int sig_num, sighandler_t handler)
{
#if defined(__pingtel_on_posix__)
   struct sigaction action[2];
   action[0].sa_handler = handler;
   sigemptyset(&action[0].sa_mask);
   action[0].sa_flags = 0;
   sigaction ( sig_num, &action[0], &action[1] );
   return action[1].sa_handler;
#else
   return signal( sig_num, handler );
#endif
}

/**
 * Description:
 * This is the signal handler, When called this sets the
 * global gShutdownFlag allowing the main processing
 * loop to exit cleanly.
 */
void
sigHandler( int sig_num )
{
   // set a global shutdown flag
   gShutdownFlag = TRUE;

   // Unregister interest in the signal to prevent recursive callbacks
   pt_signal( sig_num, SIG_DFL );

   // Minimize the chance that we loose log data
   OsSysLog::flush();
   if (SIGTERM == sig_num)
   {
      OsSysLog::add( LOG_FACILITY, PRI_INFO, "sigHandler: terminate signal received.");
   }
   else
   {
      OsSysLog::add( LOG_FACILITY, PRI_CRIT, "sigHandler: caught signal: %d", sig_num );
   }
   OsSysLog::add( LOG_FACILITY, PRI_CRIT, "sigHandler: closing IMDB connections" );
   OsSysLog::flush();

   // Finally close the IMDB connections
   closeIMDBConnections();
}

// Initialize the OsSysLog
void
initSysLog(OsConfigDb* pConfig)
{
   UtlString logLevel;               // Controls Log Verbosity
   UtlString consoleLogging;         // Enable console logging by default?
   UtlString fileTarget;             // Path to store log file.
   UtlBoolean bSpecifiedDirError ;   // Set if the specified log dir does not
   // exist
   struct tagPriorityLookupTable
   {
      const char*      pIdentity;
      OsSysLogPriority ePriority;
   };

   struct tagPriorityLookupTable lkupTable[] =
      {
         { "DEBUG",   PRI_DEBUG},
         { "INFO",    PRI_INFO},
         { "NOTICE",  PRI_NOTICE},
         { "WARNING", PRI_WARNING},
         { "ERR",     PRI_ERR},
         { "CRIT",    PRI_CRIT},
         { "ALERT",   PRI_ALERT},
         { "EMERG",   PRI_EMERG},
      };
   OsSysLog::initialize(0, "SipRegistrar");

   //
   // Get/Apply Log Filename
   //
   fileTarget.remove(0) ;
   if ((pConfig->get(CONFIG_SETTING_LOG_DIR, fileTarget) != OS_SUCCESS) ||
       fileTarget.isNull() || !OsFileSystem::exists(fileTarget))
   {
      bSpecifiedDirError = !fileTarget.isNull() ;

      // If the log file directory exists use that, otherwise place the log
      // in the current directory
      OsPath workingDirectory;
      if (OsFileSystem::exists(CONFIG_LOG_DIR))
      {
         fileTarget = CONFIG_LOG_DIR;
         OsPath path(fileTarget);
         path.getNativePath(workingDirectory);

         osPrintf("%s : %s\n", CONFIG_SETTING_LOG_DIR, workingDirectory.data()) ;
         OsSysLog::add(LOG_FACILITY, PRI_INFO, "%s : %s", CONFIG_SETTING_LOG_DIR, workingDirectory.data()) ;
      }
      else
      {
         OsPath path;
         OsFileSystem::getWorkingDirectory(path);
         path.getNativePath(workingDirectory);

         osPrintf("%s : %s\n", CONFIG_SETTING_LOG_DIR, workingDirectory.data()) ;
         OsSysLog::add(LOG_FACILITY, PRI_INFO, "%s : %s", CONFIG_SETTING_LOG_DIR, workingDirectory.data()) ;
      }

      fileTarget = workingDirectory +
         OsPathBase::separator +
         CONFIG_LOG_FILE;
   }
   else
   {
      bSpecifiedDirError = false ;
      osPrintf("%s : %s\n", CONFIG_SETTING_LOG_DIR, fileTarget.data()) ;
      OsSysLog::add(LOG_FACILITY, PRI_INFO, "%s : %s", CONFIG_SETTING_LOG_DIR, fileTarget.data()) ;

      fileTarget = fileTarget +
         OsPathBase::separator +
         CONFIG_LOG_FILE;
   }
   OsSysLog::setOutputFile(0, fileTarget) ;

   //
   // Get/Apply Log Level
   //
   if ((pConfig->get(CONFIG_SETTING_LOG_LEVEL, logLevel) != OS_SUCCESS) ||
       logLevel.isNull())
   {
      logLevel = "NOTICE";
   }
   logLevel.toUpper();
   OsSysLogPriority priority = PRI_ERR;
   int iEntries = sizeof(lkupTable)/sizeof(struct tagPriorityLookupTable);
   for (int i=0; i<iEntries; i++)
   {
      if (logLevel == lkupTable[i].pIdentity)
      {
         priority = lkupTable[i].ePriority;
         osPrintf("%s : %s\n", CONFIG_SETTING_LOG_LEVEL, lkupTable[i].pIdentity) ;
         OsSysLog::add(LOG_FACILITY, PRI_INFO, "%s : %s", CONFIG_SETTING_LOG_LEVEL, lkupTable[i].pIdentity) ;
         break;
      }
   }
   OsSysLog::setLoggingPriority(priority);

   //
   // Get/Apply console logging
   //
   UtlBoolean bConsoleLoggingEnabled = false ;
   if ((pConfig->get(CONFIG_SETTING_LOG_CONSOLE, consoleLogging) ==
        OS_SUCCESS))
   {
      consoleLogging.toUpper();
      if (consoleLogging == "ENABLE")
      {
         OsSysLog::enableConsoleOutput(true);
         bConsoleLoggingEnabled = true ;
      }
   }

   OsSysLog::add(LOG_FACILITY, PRI_INFO, "%s : %s", CONFIG_SETTING_LOG_CONSOLE,
                 bConsoleLoggingEnabled ? "ENABLE" : "DISABLE") ;

   if (bSpecifiedDirError)
   {
      OsSysLog::add(FAC_LOG, PRI_CRIT,
                    "Cannot access directory '%s'; please check configuration.",
                    CONFIG_SETTING_LOG_DIR);
   }
}

/** The main entry point to the sipregistrar */
int
main(int argc, char* argv[] )
{
   // Configuration Database (used for OsSysLog)
   OsConfigDb* configDb = new OsConfigDb();

   // Register Signal handlers to close IMDB
   pt_signal(SIGINT,   sigHandler);    // Trap Ctrl-C on NT
   pt_signal(SIGILL,   sigHandler);
   pt_signal(SIGABRT,  sigHandler);    // Abort signal 6
   pt_signal(SIGFPE,   sigHandler);    // Floading Point Exception
   pt_signal(SIGSEGV,  sigHandler);    // Address access violations signal 11
   pt_signal(SIGTERM,  sigHandler);    // Trap kill -15 on UNIX
#if defined(__pingtel_on_posix__)
   pt_signal(SIGHUP,   sigHandler);    // Hangup
   pt_signal(SIGQUIT,  sigHandler);
   pt_signal(SIGPIPE,  SIG_IGN);    // Handle TCP Failure
   pt_signal(SIGBUS,   sigHandler);
   pt_signal(SIGSYS,   sigHandler);
   pt_signal(SIGXCPU,  sigHandler);
   pt_signal(SIGXFSZ,  sigHandler);
   pt_signal(SIGUSR1,  sigHandler);
   pt_signal(SIGUSR2,  sigHandler);
#endif

   UtlBoolean interactiveSet = false;
   UtlString argString;
   for (int argIndex = 1; argIndex < argc; argIndex++)
   {
      osPrintf("arg[%d]: %s\n", argIndex, argv[argIndex]);
      argString = argv[argIndex];
      NameValueTokenizer::frontBackTrim(&argString, "\t ");
      if (argString.compareTo("-v") == 0)
      {
         osPrintf("Version: %s (%s)\n", SIPXCHANGE_VERSION, SIPXCHANGE_VERSION_COMMENT);
         return(1);
      }
      else if ( argString.compareTo("-i") == 0)
      {
         interactiveSet = true;
         osPrintf("Entering Interactive Mode\n");
      }
      else
      {
         osPrintf("usage: %s [-v] [-i]\nwhere:\n -v provides the software version\n"
                  " -i start the server in an interactive mode\n",
                  argv[0]);
         return(1);
      }
   }

   // initialize log file
   OsPath workingDirectory;
   if (OsFileSystem::exists(CONFIG_ETC_DIR))
   {
      workingDirectory = CONFIG_ETC_DIR;
      OsPath path(workingDirectory);
      path.getNativePath(workingDirectory);
   }
   else
   {
      OsPath path;
      OsFileSystem::getWorkingDirectory(path);
      path.getNativePath(workingDirectory);
   }

   UtlString fileName =  workingDirectory +
      OsPathBase::separator +
      CONFIG_SETTINGS_FILE;

   bool configLoaded = ( configDb->loadFromFile(fileName) == OS_SUCCESS );
   if (!configLoaded)
   {
      configDb->set("SIP_REGISTRAR_UDP_PORT", "5070");
      configDb->set("SIP_REGISTRAR_TCP_PORT", "5070");
      configDb->set("SIP_REGISTRAR_TLS_PORT", "5071");
      configDb->set("SIP_REGISTRAR_PROXY_PORT", "5060");
      configDb->set("SIP_REGISTRAR_MAX_EXPIRES", "");
      configDb->set("SIP_REGISTRAR_MIN_EXPIRES", "");
      configDb->set("SIP_REGISTRAR_DOMAIN_NAME", "");
      //configDb->set("SIP_REGISTRAR_AUTHENTICATE_SCHEME", "");
      configDb->set("SIP_REGISTRAR_AUTHENTICATE_ALGORITHM", "");
      configDb->set("SIP_REGISTRAR_AUTHENTICATE_QOP", "");
      configDb->set("SIP_REGISTRAR_AUTHENTICATE_REALM", "");

      configDb->set("SIP_REGISTRAR_MEDIA_SERVER", "");
      configDb->set("SIP_REGISTRAR_VOICEMAIL_SERVER", "");
      configDb->set(CONFIG_SETTING_LOG_DIR, "");
      configDb->set(CONFIG_SETTING_LOG_LEVEL, "");
      configDb->set(CONFIG_SETTING_LOG_CONSOLE, "");
   }

   initSysLog(configDb) ;
   OsSysLog::add(FAC_SIP, PRI_NOTICE,
                 "SipRegistrar >>>>>>>>>>>>>>>> STARTED"
                 );
   if (configLoaded)
   {
      OsSysLog::add(FAC_SIP, PRI_INFO, "Read config %s", fileName.data());
   }
   else
   {
      if (configDb->storeToFile(fileName) == OS_SUCCESS)
      {
         OsSysLog::add( FAC_SIP, PRI_INFO, "Default config written to: %s",
                       fileName.data()
                       );
      }
      else
      {
         OsSysLog::add( FAC_SIP, PRI_ERR, "Default config write failed to: %s",
                       fileName.data());
      }
   }

   // Fetch Pointer to the OsServer task object, note that
   // object uses the IMDB so it is important to shut this thread
   // cleanly before the signal handler exits
   SipRegistrar* registrar = SipRegistrar::getInstance(configDb);

   registrar->start();

   pServerTask = static_cast<OsServerTask*>(registrar);

   // Do not exit, let the services run...
   while( !gShutdownFlag )
   {
      if ( interactiveSet)
      {

         int charCode = getchar();

         if (charCode != '\n' && charCode != '\r')
         {
            if ( charCode == 'e')
            {
               OsSysLog::enableConsoleOutput(TRUE);
            }
            else if ( charCode == 'd')
            {
               OsSysLog::enableConsoleOutput(FALSE);
            }
         }
      }
      else
      {
         OsTask::delay(2000);
      }
   }

   // Remove the current process's row from the IMDB
   // Persisting the database if necessary

   // This is a server task so gracefully shutdown the
   // server task using the waitForShutdown method, this
   // will implicitly request a shutdown for us if one is
   // not already in progress
   if ( pServerTask != NULL )
   {
      // Deleting a server task is the only way of
      // waiting for shutdown to complete cleanly
      pServerTask->requestShutdown();
      delete pServerTask;
      pServerTask = NULL;
   }

   // now deregister this process's database references from the IMDB
   closeIMDBConnections();

   if ( configDb != NULL )
   {
      delete configDb;
   }

   // Flush the log file
   OsSysLog::flush();

   return 0;
}
<|endoftext|>