Disabled external gits

This commit is contained in:
2022-04-07 18:46:57 +02:00
parent 88cb3426ad
commit 15e7120d6d
5316 changed files with 4563444 additions and 6 deletions

View File

@@ -0,0 +1,84 @@
@echo off
REM
REM Copyright (c) 2005-2020 Intel Corporation
REM
REM Licensed under the Apache License, Version 2.0 (the "License");
REM you may not use this file except in compliance with the License.
REM You may obtain a copy of the License at
REM
REM http://www.apache.org/licenses/LICENSE-2.0
REM
REM Unless required by applicable law or agreed to in writing, software
REM distributed under the License is distributed on an "AS IS" BASIS,
REM WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
REM See the License for the specific language governing permissions and
REM limitations under the License.
REM
:: Getting parameters
if ("%1") == ("") goto error0
if ("%2") == ("") goto error0
if ("%3") == ("") goto error0
set arch=%1
if ("%2") == ("debug") set postfix=_debug
set output_dir=%3
:: Check if necessary .dll's already exist in output directory
set dlls=tbb%postfix%.dll tbbmalloc%postfix%.dll
(for %%a in (%dlls%) do (
if not exist %output_dir%\%%a (
goto copy_libs
)
))
:: Necessary .dll's already exist; no need to do anything
exit /B 0
:copy_libs
:: Optional 4th parameter to set install root
if ("%4") NEQ ("") set TBBROOT=%4
:: Actually we can set install root by ourselves
if ("%TBBROOT%") == ("") set TBBROOT=%~d0%~p0..\..\
:: Getting vs folders in case vc_mt binaries are not provided
:: ordered from oldest to newest, so we end with newest available version
if ("%VS140COMNTOOLS%") NEQ ("") set vc_dir=vc14
:: To use Microsoft* Visual Studio* 2017 IDE, make sure the variable VS150COMNTOOLS is set in your IDE instance.
:: If it is not, try running Microsoft Visual Studio 2017 from Microsoft* Developer Command Prompt* for VS 2017.
:: For details, see https://developercommunity.visualstudio.com/content/problem/730/vs154-env-var-vs150comntools-missing-from-build-sy.html
if ("%VS150COMNTOOLS%") NEQ ("") set vc_dir=vc14
:: The same comment also applies to Microsoft Visual Studio 2019 and variable VS160COMNTOOLS
if ("%VS160COMNTOOLS%") NEQ ("") set vc_dir=vc14
:: Are we standalone/oss or inside compiler?
if exist "%TBBROOT%\bin\%arch%\%vc_dir%\tbb%postfix%.dll" set interim_path=bin\%arch%
if exist "%TBBROOT%\..\redist\%arch%\tbb\%vc_dir%\tbb%postfix%.dll" set interim_path=..\redist\%arch%\tbb
if ("%interim_path%") == ("") goto error1
:: Do we provide vc_mt binaries?
if exist "%TBBROOT%\%interim_path%\vc_mt\tbb%postfix%.dll" set vc_dir=vc_mt
if ("%vc_dir%") == ("") goto error2
:: We know everything we wanted and there are no errors
:: Copying binaries
copy "%TBBROOT%\%interim_path%\%vc_dir%\tbb%postfix%.dll" "%output_dir%"
copy "%TBBROOT%\%interim_path%\%vc_dir%\tbb%postfix%.pdb" "%output_dir%"
copy "%TBBROOT%\%interim_path%\%vc_dir%\tbbmalloc%postfix%.dll" "%output_dir%"
copy "%TBBROOT%\%interim_path%\%vc_dir%\tbbmalloc%postfix%.pdb" "%output_dir%"
if exist "%TBBROOT%\%interim_path%\%vc_dir%\tbb_preview%postfix%.dll" copy "%TBBROOT%\%interim_path%\%vc_dir%\tbb_preview%postfix%.dll" "%output_dir%"
if exist "%TBBROOT%\%interim_path%\%vc_dir%\tbb_preview%postfix%.pdb" copy "%TBBROOT%\%interim_path%\%vc_dir%\tbb_preview%postfix%.pdb" "%output_dir%"
goto end
:error0
echo number of parameters not correct
exit /B 1
:error1
echo Could not determine path to TBB libraries
exit /B 1
:error2
echo Could not determine Visual Studio version
exit /B 1
:end
exit /B 0

View File

@@ -0,0 +1,34 @@
# Copyright (c) 2005-2020 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# detect if a compiler can support C++11
# If CXX0XFLAGS already set, do not change it
ifneq (,$(findstring icc, $(CXX))$(findstring icpc, $(CXX))$(findstring clang++, $(CXX)))
# every supported icc or clang is OK
CXX0XFLAGS ?= -std=c++11
else
ifneq (,$(findstring g++, $(CXX))$(findstring gcc, $(CXX)))
ifneq (, $(strip $(shell $(CXX) -v 2>&1 | grep "clang-")))
# This is clang actually,
# every supported clang is OK
CXX0XFLAGS ?= -std=c++11
else
# support of lambda started GCC 4.5
ifneq (, $(strip $(shell g++ -dumpfullversion -dumpversion | egrep "^(4\.[5-9]|[5-9]|1[0-9])")))
CXX0XFLAGS ?= -std=c++11
endif
endif
endif
endif

View File

@@ -0,0 +1,86 @@
# Copyright (c) 2005-2020 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# The C++ compiler
#CXX=g++
# detecting MS Windows (for MinGW support)
ifeq ($(OS), Windows_NT)
RM = cmd /C del /Q /F
RD = cmd /C rmdir
UI = con
EXE = $(NAME)$(SUFFIX).exe
else
RM = rm -f
RD = rmdir -r
# detecting 64-bit platform
arch ?= $(shell uname -m)
# Possible values of interest: intel64 x86_64 amd64 ia64 ppc64 sparc sparc64
x64 ?= $(findstring 64,$(subst sparc,sparc64,$(arch)))
# see https://wiki.debian.org/Multiarch/Tuples
MULTIARCH = $(arch)
ifeq ($(arch),ia32)
MULTIARCH = i386
endif
ifeq ($(arch),intel64)
MULTIARCH = x86_64
endif
ifeq ($(arch),ppc32)
MULTIARCH = powerpc
endif
ifeq ($(arch),sparc)
MULTIARCH = sparc64
endif
MULTIARCHTUPLE ?= $(MULTIARCH)-linux-gnu
# detecting UI ("mac", "x" or "con")
ifeq ($(shell uname),Darwin)
UI ?= mac
else
UI ?= $(shell sh -c "[ -f /usr/X11R6/lib$(x64)/libX11.so -o -f /usr/lib$(x64)/libX11.so -o -f /usr/lib/$(MULTIARCHTUPLE)/libX11.so ] && echo x")
endif
ifeq ($(UI),x)
EXE = $(NAME)$(SUFFIX)
UI_CXXFLAGS += -I/usr/X11R6/include
LIBS += -lpthread -L/usr/X11R6/lib$(x64) -lX11
# detect if libXext can be found
ifeq ($(shell sh -c "[ -f /usr/X11R6/lib$(x64)/libXext.so -o -f /usr/lib$(x64)/libXext.so -o -f /usr/lib/$(MULTIARCHTUPLE)/libXext.so ] && echo 0"),0)
LIBS += -lXext
else # no libXext
UI_CXXFLAGS += -DX_NOSHMEM
endif # libXext
else # ! X
ifeq ($(UI),mac)
CXX_UI?=g++
LIBS += -framework OpenGL -framework Foundation -framework Cocoa
MACUISOURCES = ../../common/gui/xcode/tbbExample/OpenGLView.m ../../common/gui/xcode/tbbExample/main.m ../../common/gui/xcode/tbbExample/tbbAppDelegate.m
MACUIOBJS = OpenGLView.o main.o tbbAppDelegate.o
APPRES = $(NAME)$(SUFFIX).app/Contents/Resources
EXE = $(NAME)$(SUFFIX).app/Contents/MacOS/$(NAME)$(SUFFIX)
else # ! macOS*
EXE = $(NAME)$(SUFFIX)
ifeq (,$(strip $(UI)))
UI = con
$(warning Note: no graphics output capability detected, building for console output.)
endif
endif # macOS
endif # X
endif # Windows vs. other

View File

@@ -0,0 +1,70 @@
# Copyright (c) 2005-2020 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Per-build Makefile rules (for recursive $(MAKE) calls from Makefile)
# Base compile/link options
MYCXXFLAGS = /nologo /EHsc /Zc:forScope /D WIN32 /D _MBCS /D _CRT_SECURE_NO_DEPRECATE /MP $(CXXFLAGS)
MYLFLAGS = /link /incremental:no /fixed:no $(LFLAGS)
CXXFLAGS_NDEBUG = /MD /O2 /Ot /Gy /D NDEBUG
CXXFLAGS_DEBUG = /MDd /Od /Zi /D _DEBUG
# Specify library directory for Direct X SDK
DDLIB_DIR=$(DXSDK_DIR)\lib\$(XARCH:AMD64=x64)
# Input and output files
#SOURCE = v
#RCNAME = specified externaly
#EXE = ^
# defaults on XARCH = x86
UISRC = ../../common/gui/$(UI)video.cpp
default:
build_echo:
-@echo Building$(DEBUG) $(EXE) with UI=$(UI) XARCH=$(XARCH)
build_one: build_echo build_$(UI)$(DEBUG)
build_con: $(SOURCE) $(UISRC) compiler_check
$(CXX) $(CXXFLAGS_NDEBUG) $(MYCXXFLAGS) $(SOURCE) $(UISRC) $(MYLFLAGS) /subsystem:console /OUT:$(EXE)
@cmd.exe /C del *.obj
build_con_debug: $(SOURCE) $(UISRC) compiler_check
$(CXX) $(CXXFLAGS_DEBUG) $(MYCXXFLAGS) $(SOURCE) $(UISRC) $(MYLFLAGS) /debug /subsystem:console /OUT:$(EXE)
@cmd.exe /C del *.obj
build_gdi: $(SOURCE) $(UISRC) msvs/$(RCNAME).res compiler_check
$(CXX) $(CXXFLAGS_NDEBUG) /D _WINDOWS $(MYCXXFLAGS) $(SOURCE) $(UISRC) $(MYLFLAGS) msvs/$(RCNAME).res /subsystem:windows /machine:$(XARCH) /OUT:$(EXE)
@cmd.exe /C del *.obj
build_gdi_debug: $(SOURCE) $(UISRC) msvs/$(RCNAME).res compiler_check
$(CXX) $(CXXFLAGS_DEBUG) /D _WINDOWS $(MYCXXFLAGS) $(SOURCE) $(UISRC) $(MYLFLAGS) msvs/$(RCNAME).res /debug /subsystem:windows /machine:$(XARCH) /OUT:$(EXE)
@cmd.exe /C del *.obj
build_d2d: $(SOURCE) $(UISRC) msvs/$(RCNAME).res compiler_check
-@echo Using DirectX SDK from "$(DDLIB_DIR)"
$(CXX) $(CXXFLAGS_NDEBUG) /D _WINDOWS $(MYCXXFLAGS) /I "$(DXSDK_DIR)\include" $(SOURCE) $(UISRC) $(MYLFLAGS) /LIBPATH:"$(DDLIB_DIR)" msvs/$(RCNAME).res /subsystem:windows /machine:$(XARCH) /OUT:$(EXE)
@cmd.exe /C del *.obj
build_d2d_debug: $(SOURCE) $(UISRC) msvs/$(RCNAME).res compiler_check
-@echo Using DirectX SDK from "$(DDLIB_DIR)"
$(CXX) $(CXXFLAGS_DEBUG) /D _WINDOWS $(MYCXXFLAGS) /I "$(DXSDK_DIR)\include" $(SOURCE) $(UISRC) $(MYLFLAGS) /LIBPATH:"$(DDLIB_DIR)" msvs/$(RCNAME).res /debug /subsystem:windows /machine:$(XARCH) /OUT:$(EXE)
@cmd.exe /C del *.obj
msvs/$(RCNAME).res:
rc /r msvs/$(RCNAME)
compiler_check:
@echo compiler_test>compiler_test && @$(CXX) /E compiler_test >nul 2>&1 || echo "$(CXX) command not found. Check if CXX=$(CXX) is set properly"
@cmd.exe /C del compiler_test

View File

@@ -0,0 +1,132 @@
/*
Copyright (c) 2005-2020 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "video.h"
#include <cassert>
#include <stdio.h>
unsigned int * g_pImg = 0;
int g_sizex, g_sizey;
static video *g_video = 0;
static int g_fps = 0;
#if _WIN32 || _WIN64
static DWORD g_msec = 0;
#ifdef _WINDOWS
HINSTANCE video::win_hInstance = 0;
int video::win_iCmdShow = 0;
void video::win_set_class(WNDCLASSEX &wcex) { }
void video::win_load_accelerators(int idc) { }
#endif //_WINDOWS
#else
#include <sched.h>
#include <sys/time.h>
struct timeval g_time;
#endif //_WIN32||_WIN64
#define CALC_FPS_ENABLED ((WINAPI_FAMILY != WINAPI_FAMILY_APP) && (!__ANDROID__))
video::video()
// OpenGL* RGBA byte order for little-endian CPU
: depth(24), red_shift(0), green_shift(8), blue_shift(16),
red_mask(0xff), green_mask(0xff00), blue_mask(0xff0000)
{
assert(g_video == 0);
g_video = this; title = "Video"; updating = calc_fps = false;
}
bool video::init_window(int x, int y)
{
g_sizex = x; g_sizey = y;
g_pImg = new unsigned int[x*y];
running = true;
return false;
}
bool video::init_console()
{
running = true;
return true;
}
void video::terminate()
{
#if CALC_FPS_ENABLED
if(calc_fps) {
double fps = g_fps;
#if _WIN32 || _WIN64
fps /= (GetTickCount()-g_msec)/1000.0;
#else
struct timezone tz; struct timeval end_time; gettimeofday(&end_time, &tz);
fps /= (end_time.tv_sec+1.0*end_time.tv_usec/1000000.0) - (g_time.tv_sec+1.0*g_time.tv_usec/1000000.0);
#endif
printf("%s: %.1f fps\n", title, fps);
}
#endif
g_video = 0; running = false;
if(g_pImg) { delete[] g_pImg; g_pImg = 0; }
}
video::~video()
{
if(g_video) terminate();
}
//! Count and display FPS count in titlebar
bool video::next_frame()
{
#if CALC_FPS_ENABLED
if(calc_fps){
if(!g_fps) {
#if _WIN32 || _WIN64
g_msec = GetTickCount();
#else
struct timezone tz; gettimeofday(&g_time, &tz);
#endif
}
g_fps++;
}
#endif
return running;
}
//! Do standard loop
void video::main_loop()
{
on_process();
}
//! Change window title
void video::show_title()
{
}
///////////////////////////////////////////// public methods of video class ///////////////////////
drawing_area::drawing_area(int x, int y, int sizex, int sizey)
: base_index(y*g_sizex + x), max_index(g_sizex*g_sizey), index_stride(g_sizex),
pixel_depth(24), ptr32(g_pImg), start_x(x), start_y(y), size_x(sizex), size_y(sizey)
{
assert(x < g_sizex); assert(y < g_sizey);
assert(x+sizex <= g_sizex); assert(y+sizey <= g_sizey);
index = base_index; // current index
}
void drawing_area::update() {}

View File

@@ -0,0 +1,197 @@
/*
Copyright (c) 2005-2020 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// common Windows parts
#include "winvideo.h"
// and another headers
#include <cassert>
#include <stdio.h>
#include <dxsdkver.h>
#if _DXSDK_PRODUCT_MAJOR < 9
#error DXSDK Version 9 and above required.
#endif
#include <d2d1.h>
#include <d2d1helper.h>
#pragma comment(lib, "d2d1.lib")
ID2D1Factory *m_pD2DFactory;
ID2D1HwndRenderTarget *m_pRenderTarget;
ID2D1Bitmap *m_pBitmap;
D2D1_SIZE_U bitmapSize;
HANDLE g_hVSync;
#include <DXErr.h>
#pragma comment(lib, "DxErr.lib")
//! Create a dialog box and tell the user what went wrong
bool DisplayError(LPSTR lpstrErr, HRESULT hres)
{
if(hres != S_OK){
static bool InError = false;
int retval = 0;
if (!InError)
{
InError = true;
const char *message = hres?DXGetErrorString(hres):0;
retval = MessageBoxA(g_hAppWnd, lpstrErr, hres?message:"Error!", MB_OK|MB_ICONERROR);
InError = false;
}
}
return false;
}
void DrawBitmap()
{
HRESULT hr = S_OK;
if (m_pRenderTarget) {
m_pRenderTarget->BeginDraw();
if (m_pBitmap)
hr = m_pBitmap->CopyFromMemory(NULL,(BYTE*)g_pImg, 4*g_sizex);
DisplayError( "DrawBitmap error", hr );
m_pRenderTarget->DrawBitmap(m_pBitmap);
m_pRenderTarget->EndDraw();
}
return;
}
inline void mouse(int k, LPARAM lParam)
{
int x = (int)LOWORD(lParam);
int y = (int)HIWORD(lParam);
RECT rc;
GetClientRect(g_hAppWnd, &rc);
g_video->on_mouse( x*g_sizex/(rc.right - rc.left), y*g_sizey/(rc.bottom - rc.top), k );
}
//! Win event processing function
LRESULT CALLBACK InternalWndProc(HWND hwnd, UINT iMsg, WPARAM wParam, LPARAM lParam)
{
switch (iMsg)
{
case WM_MOVE:
// Check to make sure our window exists before we tell it to repaint.
// This will fail the first time (while the window is being created).
if (hwnd) {
InvalidateRect(hwnd, NULL, FALSE);
UpdateWindow(hwnd);
}
return 0L;
case WM_SIZE:
case WM_PAINT:
if( g_video->running && g_video->updating ) {
DrawBitmap();
Sleep(0);
}
break;
// Process all mouse and keyboard events
case WM_LBUTTONDOWN: mouse( 1, lParam ); break;
case WM_LBUTTONUP: mouse(-1, lParam ); break;
case WM_RBUTTONDOWN: mouse( 2, lParam ); break;
case WM_RBUTTONUP: mouse(-2, lParam ); break;
case WM_MBUTTONDOWN: mouse( 3, lParam ); break;
case WM_MBUTTONUP: mouse(-3, lParam ); break;
case WM_CHAR: g_video->on_key( (int)wParam); break;
// some useless stuff
case WM_ERASEBKGND: return 1; // keeps erase-background events from happening, reduces chop
case WM_DISPLAYCHANGE: return 0;
// Now, shut down the window...
case WM_DESTROY: PostQuitMessage(0); return 0;
}
// call user defined proc, if exists
return g_pUserProc? g_pUserProc(hwnd, iMsg, wParam, lParam) : DefWindowProc(hwnd, iMsg, wParam, lParam);
}
bool video::init_window(int sizex, int sizey)
{
assert(win_hInstance != 0);
g_sizex = sizex; g_sizey = sizey;
if (!WinInit(win_hInstance, win_iCmdShow, gWndClass, title, false)) {
DisplayError("Unable to initialize the program's window.");
return false;
}
ShowWindow(g_hAppWnd, SW_SHOW);
g_pImg = new unsigned int[sizex*sizey];
HRESULT hr = S_OK;
hr = D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, &m_pD2DFactory);
// Create a Direct2D render target.
if (SUCCEEDED(hr) && !m_pRenderTarget){
RECT rc;
GetClientRect(g_hAppWnd, &rc);
bitmapSize = D2D1::SizeU(
rc.right - rc.left,
rc.bottom - rc.top
);
hr = m_pD2DFactory->CreateHwndRenderTarget(
D2D1::RenderTargetProperties(),
D2D1::HwndRenderTargetProperties(g_hAppWnd, bitmapSize),
&m_pRenderTarget
);
if (SUCCEEDED(hr) && !m_pBitmap){
D2D1_PIXEL_FORMAT pixelFormat = D2D1::PixelFormat(
DXGI_FORMAT_B8G8R8A8_UNORM,
D2D1_ALPHA_MODE_IGNORE
);
D2D1_BITMAP_PROPERTIES bitmapProperties;
bitmapProperties.pixelFormat = pixelFormat;
m_pRenderTarget->GetDpi( &bitmapProperties.dpiX, &bitmapProperties.dpiY );
m_pRenderTarget->CreateBitmap(bitmapSize,bitmapProperties,&m_pBitmap);
m_pRenderTarget->DrawBitmap(m_pBitmap);
}
}
running = true;
return true;
}
void video::terminate()
{
if (m_pBitmap) m_pBitmap->Release();
if (m_pRenderTarget) m_pRenderTarget->Release();
if (m_pD2DFactory) m_pD2DFactory->Release();
g_video = 0; running = false;
if(g_pImg) { delete[] g_pImg; g_pImg = 0; }
}
//////////// drawing area constructor & destructor /////////////
drawing_area::drawing_area(int x, int y, int sizex, int sizey)
: base_index(y*g_sizex + x), max_index(g_sizex*g_sizey), index_stride(g_sizex),
pixel_depth(24), ptr32(g_pImg), start_x(x), start_y(y), size_x(sizex), size_y(sizey)
{
assert(x < g_sizex); assert(y < g_sizey);
assert(x+sizex <= g_sizex); assert(y+sizey <= g_sizey);
index = base_index; // current index
}
void drawing_area::update()
{
if(g_video->updating) {
RECT r;
r.left = start_x; r.right = start_x + size_x;
r.top = start_y; r.bottom = start_y + size_y;
InvalidateRect(g_hAppWnd, &r, false);
}
}

View File

@@ -0,0 +1,24 @@
@echo off
REM
REM Copyright (c) 2005-2020 Intel Corporation
REM
REM Licensed under the Apache License, Version 2.0 (the "License");
REM you may not use this file except in compliance with the License.
REM You may obtain a copy of the License at
REM
REM http://www.apache.org/licenses/LICENSE-2.0
REM
REM Unless required by applicable law or agreed to in writing, software
REM distributed under the License is distributed on an "AS IS" BASIS,
REM WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
REM See the License for the specific language governing permissions and
REM limitations under the License.
REM
if "%DXSDK_DIR%"=="" goto error_no_DXSDK
goto end
:error_no_DXSDK
echo DirectX SDK Check : error : This example requires the DirectX SDK. Either (re)-install the DirectX SDK, or set the DXSDK_DIR environment variable to indicate where it is installed.
:end

View File

@@ -0,0 +1,142 @@
/*
Copyright (c) 2005-2020 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// common Windows parts
#include "winvideo.h"
// include GDI+ headers
#include <gdiplus.h>
// and another headers
#include <stdio.h>
// tag linking library
#pragma comment(lib, "gdiplus.lib")
// global specific variables
Gdiplus::Bitmap * g_pBitmap; // main drawing bitmap
ULONG_PTR gdiplusToken;
Gdiplus::GdiplusStartupInput gdiplusStartupInput;// GDI+
//! display system error
bool DisplayError(LPSTR lpstrErr, HRESULT hres)
{
static bool InError = false;
int retval = 0;
if (!InError)
{
InError = true;
LPCSTR lpMsgBuf;
if(!hres) hres = GetLastError();
FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, hres, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &lpMsgBuf, 0, NULL );
retval = MessageBox(g_hAppWnd, lpstrErr, lpMsgBuf, MB_OK|MB_ICONERROR);
LocalFree( (HLOCAL)lpMsgBuf );
InError = false;
}
return false;
}
//! Win event processing function
LRESULT CALLBACK InternalWndProc(HWND hwnd, UINT iMsg, WPARAM wParam, LPARAM lParam)
{
switch (iMsg)
{
case WM_MOVE:
// Check to make sure our window exists before we tell it to repaint.
// This will fail the first time (while the window is being created).
if (hwnd) {
InvalidateRect(hwnd, NULL, FALSE);
UpdateWindow(hwnd);
}
return 0L;
case WM_PAINT:
{
PAINTSTRUCT ps;
Gdiplus::Graphics graphics( BeginPaint(hwnd, &ps) );
// redraw just requested area. This call is as fast as simple DrawImage() call.
if(g_video->updating) graphics.DrawImage(g_pBitmap, ps.rcPaint.left, ps.rcPaint.top, ps.rcPaint.left, ps.rcPaint.top,
ps.rcPaint.right, ps.rcPaint.bottom, Gdiplus::UnitPixel);
EndPaint(hwnd, &ps);
}
return 0L;
// Process all mouse and keyboard events
case WM_LBUTTONDOWN: g_video->on_mouse( (int)LOWORD(lParam), (int)HIWORD(lParam), 1); break;
case WM_LBUTTONUP: g_video->on_mouse( (int)LOWORD(lParam), (int)HIWORD(lParam), -1); break;
case WM_RBUTTONDOWN: g_video->on_mouse( (int)LOWORD(lParam), (int)HIWORD(lParam), 2); break;
case WM_RBUTTONUP: g_video->on_mouse( (int)LOWORD(lParam), (int)HIWORD(lParam), -2); break;
case WM_MBUTTONDOWN: g_video->on_mouse( (int)LOWORD(lParam), (int)HIWORD(lParam), 3); break;
case WM_MBUTTONUP: g_video->on_mouse( (int)LOWORD(lParam), (int)HIWORD(lParam), -3); break;
case WM_CHAR: g_video->on_key( (int)wParam); break;
// some useless stuff
case WM_ERASEBKGND: return 1; // keeps erase-background events from happening, reduces chop
case WM_DISPLAYCHANGE: return 0;
// Now, shut down the window...
case WM_DESTROY: PostQuitMessage(0); return 0;
}
// call user defined proc, if exists
return g_pUserProc? g_pUserProc(hwnd, iMsg, wParam, lParam) : DefWindowProc(hwnd, iMsg, wParam, lParam);
}
///////////// video functions ////////////////
bool video::init_window(int sizex, int sizey)
{
assert(win_hInstance != 0);
g_sizex = sizex; g_sizey = sizey;
if (!WinInit(win_hInstance, win_iCmdShow, gWndClass, title, true)) {
DisplayError("Unable to initialize the program's window.");
return false;
}
ShowWindow(g_hAppWnd, SW_SHOW);
Gdiplus::GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);
g_pImg = new unsigned int[sizex*sizey];
g_pBitmap = new Gdiplus::Bitmap(g_sizex, g_sizey, 4*g_sizex, PixelFormat32bppRGB, (BYTE*)g_pImg );
running = true;
return true;
}
void video::terminate()
{
if(g_pBitmap) { delete g_pBitmap; g_pBitmap = 0; }
Gdiplus::GdiplusShutdown(gdiplusToken);
g_video = 0; running = false;
if(g_pImg) { delete[] g_pImg; g_pImg = 0; }
}
//////////// drawing area constructor & destructor /////////////
drawing_area::drawing_area(int x, int y, int sizex, int sizey)
: base_index(y*g_sizex + x), max_index(g_sizex*g_sizey), index_stride(g_sizex),
pixel_depth(24), ptr32(g_pImg), start_x(x), start_y(y), size_x(sizex), size_y(sizey)
{
assert(x < g_sizex); assert(y < g_sizey);
assert(x+sizex <= g_sizex); assert(y+sizey <= g_sizey);
index = base_index; // current index
}
void drawing_area::update()
{
if(g_video->updating) {
RECT r;
r.left = start_x; r.right = start_x + size_x;
r.top = start_y; r.bottom = start_y + size_y;
InvalidateRect(g_hAppWnd, &r, false);
}
}

View File

@@ -0,0 +1,160 @@
/*
Copyright (c) 2005-2020 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "video.h"
#include <cassert>
#include <stdio.h>
#include <iostream>
#include <pthread.h>
unsigned int* g_pImg = 0;
int g_sizex=0, g_sizey=0;
static video *g_video = 0;
static int g_fps = 0;
char *window_title=NULL;
#define WINDOW_TITLE_SIZE 256
int cocoa_update=0;
#include <sched.h>
#include <sys/time.h>
struct timeval g_time;
video::video()
#if __TBB_IOS
: depth(24), red_shift(0), green_shift(8), blue_shift(16),
red_mask(0xff), green_mask(0xff00), blue_mask(0xff0000)
#else
: depth(24), red_shift(16), green_shift(8), blue_shift(0),
red_mask(0xff0000), green_mask(0xff00), blue_mask(0xff)
#endif
{
assert(g_video == 0);
g_video = this; title = "Video"; cocoa_update=1; updating = true; calc_fps = false;
}
bool video::init_window(int x, int y)
{
g_sizex = x; g_sizey = y;
g_pImg = new unsigned int[x*y];
if( window_title==NULL )
window_title = (char*)malloc(WINDOW_TITLE_SIZE);
strncpy( window_title, title, WINDOW_TITLE_SIZE-1 );
running = true;
return true;
}
bool video::init_console()
{
running = true;
return true;
}
void video::terminate()
{
if(calc_fps) {
double fps = g_fps;
struct timezone tz; struct timeval end_time; gettimeofday(&end_time, &tz);
fps /= (end_time.tv_sec+1.0*end_time.tv_usec/1000000.0) - (g_time.tv_sec+1.0*g_time.tv_usec/1000000.0);
printf("%s: %.1f fps\n", title, fps);
}
g_video = 0; running = false;
if(g_pImg) { delete[] g_pImg; g_pImg = 0; }
}
video::~video()
{
if(g_video) terminate();
}
//! Count and display FPS count in titlebar
bool video::next_frame()
{
if(calc_fps){
if(!g_fps) {
struct timezone tz; gettimeofday(&g_time, &tz);
}
g_fps++;
}
struct timezone tz; struct timeval now_time; gettimeofday(&now_time, &tz);
double sec=((now_time.tv_sec+1.0*now_time.tv_usec/1000000.0) - (g_time.tv_sec+1.0*g_time.tv_usec/1000000.0));
if( sec>1 ){
if(calc_fps) {
memcpy(&g_time, &now_time, sizeof(g_time));
int fps;
fps = g_fps/sec;
cocoa_update = (int)updating;
snprintf(window_title,WINDOW_TITLE_SIZE, "%s%s: %d fps", title, updating?"":" (no updating)", int(fps));
g_fps=0;
}
}
return running;
}
void* thread_func(void*)
{
g_video->on_process();
exit(EXIT_SUCCESS);
}
extern "C" void on_mouse_func(int x, int y, int k)
{
g_video->on_mouse(x, y, k);
return;
}
extern "C" void on_key_func(int x)
{
g_video->on_key(x);
return;
}
extern "C" int cocoa_main( int argc, char *argv[] );
//! Do standard loop
void video::main_loop()
{
pthread_t handle;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_create(&handle,&attr,&thread_func,(void*)NULL);
pthread_detach(handle);
cocoa_main( 0, NULL );
}
//! Change window title
void video::show_title()
{
if(title)
strncpy( window_title, title, WINDOW_TITLE_SIZE );
return;
}
///////////////////////////////////////////// public methods of video class ///////////////////////
drawing_area::drawing_area(int x, int y, int sizex, int sizey)
: base_index(y*g_sizex + x), max_index(g_sizex*g_sizey), index_stride(g_sizex),
pixel_depth(24), ptr32(g_pImg), start_x(x), start_y(y), size_x(sizex), size_y(sizey)
{
assert(x < g_sizex); assert(y < g_sizey);
assert(x+sizex <= g_sizex); assert(y+sizey <= g_sizey);
index = base_index; // current index
}
void drawing_area::update()
{
//nothing to do, updating via timer in cocoa part.
}

View File

@@ -0,0 +1,237 @@
/*
Copyright (c) 2005-2020 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef __VIDEO_H__
#define __VIDEO_H__
#include <cassert>
#if _MSC_VER
#include <stddef.h> // for uintptr_t
#else
#include <stdint.h> // for uintptr_t
#endif
#if _WIN32 || _WIN64
#include <windows.h>
#else
#include <unistd.h>
#endif
typedef unsigned int color_t;
typedef unsigned char colorcomp_t;
typedef signed char depth_t;
//! Class for getting access to drawing memory
class drawing_memory
{
#ifdef __TBB_MIC_OFFLOAD
// The address is kept as uintptr_t since
// the compiler could not offload a pointer
#endif
uintptr_t my_address;
public:
depth_t pixel_depth;
int sizex, sizey;
//! Get drawing memory
inline char* get_address() const { return reinterpret_cast<char*>(my_address); }
//! Get drawing memory size
inline int get_size() const { return ((pixel_depth>16) ? 4:2) * sizex * sizey; }
//! Set drawing memory
inline void set_address(char *mem) { my_address = reinterpret_cast<uintptr_t>(mem); }
friend class drawing_area;
friend class video;
};
//! Simple proxy class for managing of different video systems
class video
{
//! colorspace information
depth_t depth, red_shift, green_shift, blue_shift;
color_t red_mask, green_mask, blue_mask;
friend class drawing_area;
public:
//! Constructor
video();
//! Destructor
~video();
//! member to set window name
const char *title;
//! true is enable to show fps
bool calc_fps;
//! if true: on windows fork processing thread for on_process(), on non-windows note that next_frame() is called concurrently.
bool threaded;
//! true while running within main_loop()
bool running;
//! if true, do gui updating
bool updating;
//! initialize graphical video system
bool init_window(int sizex, int sizey);
//! initialize console. returns true if console is available
bool init_console();
//! terminate video system
void terminate();
//! Do standard event & processing loop. Use threaded = true to separate event/updating loop from frame processing
void main_loop();
//! Process next frame
bool next_frame();
//! Change window title
void show_title();
//! translate RGB components into packed type
inline color_t get_color(colorcomp_t red, colorcomp_t green, colorcomp_t blue) const;
//! Get drawing memory descriptor
inline drawing_memory get_drawing_memory() const;
//! code of the ESCape key
static const int esc_key = 27;
//! Mouse events handler.
virtual void on_mouse(int x, int y, int key) { }
//! Mouse events handler.
virtual void on_key(int key) { }
//! Main processing loop. Redefine with your own
virtual void on_process() { while(next_frame()); }
#ifdef _WINDOWS
//! Windows specific members
//! if VIDEO_WINMAIN isn't defined then set this just before init() by arguments of WinMain
static HINSTANCE win_hInstance; static int win_iCmdShow;
//! optionally call it just before init() to set own. Use ascii strings convention
void win_set_class(WNDCLASSEX &);
//! load and set accelerator table from resources
void win_load_accelerators(int idc);
#endif
};
//! Drawing class
class drawing_area
{
const size_t base_index, max_index, index_stride;
const depth_t pixel_depth;
unsigned int * const ptr32;
size_t index;
public:
const int start_x, start_y, size_x, size_y;
//! constructors
drawing_area(int x, int y, int sizex, int sizey);
inline drawing_area(int x, int y, int sizex, int sizey, const drawing_memory &dmem);
//! destructor
inline ~drawing_area();
//! update the image
void update();
//! set current position. local_x could be bigger then size_x
inline void set_pos(int local_x, int local_y);
//! put pixel in current position with incremental address calculating to next right pixel
inline void put_pixel(color_t color);
//! draw pixel at position by packed color
void set_pixel(int localx, int localy, color_t color)
{ set_pos(localx, localy); put_pixel(color); }
};
extern int g_sizex;
extern int g_sizey;
extern unsigned int *g_pImg;
inline drawing_memory video::get_drawing_memory() const
{
drawing_memory dmem;
dmem.pixel_depth = depth;
dmem.my_address = reinterpret_cast<uintptr_t>(g_pImg);
dmem.sizex = g_sizex;
dmem.sizey = g_sizey;
return dmem;
}
inline color_t video::get_color(colorcomp_t red, colorcomp_t green, colorcomp_t blue) const
{
if(red_shift == 16) // only for depth == 24 && red_shift > blue_shift
return (red<<16) | (green<<8) | blue;
else if(depth >= 24)
return
#if __ANDROID__
// Setting Alpha to 0xFF
0xFF000000 |
#endif
(red<<red_shift) | (green<<green_shift) | (blue<<blue_shift);
else if(depth > 0) {
depth_t bs = blue_shift, rs = red_shift;
if(blue_shift < 0) blue >>= -bs, bs = 0;
else /*red_shift < 0*/ red >>= -rs, rs = 0;
return ((red<<rs)&red_mask) | ((green<<green_shift)&green_mask) | ((blue<<bs)&blue_mask);
} else { // UYVY colorspace
unsigned y, u, v;
y = red * 77 + green * 150 + blue * 29; // sum(77+150+29=256) * max(=255): limit->2^16
u = (2048 + (blue << 3) - (y >> 5)) >> 4; // (limit->2^12)>>4
v = (2048 + (red << 3) - (y >> 5)) >> 4;
y = y >> 8;
return u | (y << 8) | (v << 16) | (y << 24);
}
}
inline drawing_area::drawing_area(int x, int y, int sizex, int sizey, const drawing_memory &dmem)
: base_index(y*dmem.sizex + x), max_index(dmem.sizex*dmem.sizey), index_stride(dmem.sizex),
pixel_depth(dmem.pixel_depth), ptr32(reinterpret_cast<unsigned int*>(dmem.my_address)),
start_x(x), start_y(y), size_x(sizex), size_y(sizey)
{
assert(x < dmem.sizex); assert(y < dmem.sizey);
assert(x+sizex <= dmem.sizex); assert(y+sizey <= dmem.sizey);
index = base_index; // current index
}
inline void drawing_area::set_pos(int local_x, int local_y)
{
index = base_index + local_x + local_y*index_stride;
}
inline void drawing_area::put_pixel(color_t color)
{
assert(index < max_index);
if(pixel_depth > 16) ptr32[index++] = color;
else if(pixel_depth > 0)
((unsigned short*)ptr32)[index++] = (unsigned short)color;
else { // UYVY colorspace
if(index&1) color >>= 16;
((unsigned short*)ptr32)[index++] = (unsigned short)color;
}
}
inline drawing_area::~drawing_area()
{
#if ! __TBB_DEFINE_MIC
update();
#endif
}
#if defined(_WINDOWS) && (defined(VIDEO_WINMAIN) || defined(VIDEO_WINMAIN_ARGS) )
#include <cstdlib>
//! define WinMain for subsystem:windows.
#ifdef VIDEO_WINMAIN_ARGS
int main(int, char *[]);
#else
int main();
#endif
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE, PSTR szCmdLine, int iCmdShow)
{
video::win_hInstance = hInstance; video::win_iCmdShow = iCmdShow;
#ifdef VIDEO_WINMAIN_ARGS
return main(__argc, __argv);
#else
return main();
#endif
}
#endif
#endif// __VIDEO_H__

View File

@@ -0,0 +1,279 @@
/*
Copyright (c) 2005-2020 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/////// Common internal implementation of Windows-specific stuff //////////////
/////// Must be the first included header //////////////
#ifndef __WINVIDEO_H__
#define __WINVIDEO_H__
#ifndef _CRT_SECURE_NO_DEPRECATE
#define _CRT_SECURE_NO_DEPRECATE
#endif
// Check that the target Windows version has all API calls required.
#ifndef _WIN32_WINNT
# define _WIN32_WINNT 0x0400
#endif
#if _WIN32_WINNT<0x0400
# define YIELD_TO_THREAD() Sleep(0)
#else
# define YIELD_TO_THREAD() SwitchToThread()
#endif
#include "video.h"
#include <fcntl.h>
#include <io.h>
#include <iostream>
#include <fstream>
#pragma comment(lib, "gdi32.lib")
#pragma comment(lib, "user32.lib")
// maximum number of lines the output console should have
static const WORD MAX_CONSOLE_LINES = 500;
const COLORREF RGBKEY = RGB(8, 8, 16); // at least 8 for 16-bit palette
HWND g_hAppWnd; // The program's window handle
HANDLE g_handles[2] = {0,0};// thread and wake up event
unsigned int * g_pImg = 0; // drawing memory
int g_sizex, g_sizey;
static video * g_video = 0;
WNDPROC g_pUserProc = 0;
HINSTANCE video::win_hInstance = 0;
int video::win_iCmdShow = 0;
static WNDCLASSEX * gWndClass = 0;
static HACCEL hAccelTable = 0;
static DWORD g_msec = 0;
static int g_fps = 0, g_updates = 0, g_skips = 0;
bool DisplayError(LPSTR lpstrErr, HRESULT hres = 0); // always returns false
LRESULT CALLBACK InternalWndProc(HWND hwnd, UINT iMsg, WPARAM wParam, LPARAM lParam);
//! Create window
bool WinInit(HINSTANCE hInstance, int nCmdShow, WNDCLASSEX *uwc, const char *title, bool fixedsize)
{
WNDCLASSEX wndclass; // Our app's windows class
if(uwc) {
memcpy(&wndclass, uwc, sizeof(wndclass));
g_pUserProc = uwc->lpfnWndProc;
} else {
memset(&wndclass, 0, sizeof(wndclass));
wndclass.hCursor = LoadCursor(NULL, IDC_ARROW);
wndclass.lpszClassName = title;
}
wndclass.cbSize = sizeof(wndclass);
wndclass.hInstance = hInstance;
wndclass.lpfnWndProc = InternalWndProc;
wndclass.style |= CS_HREDRAW | CS_VREDRAW;
wndclass.hbrBackground = CreateSolidBrush(RGBKEY);
if( !RegisterClassExA(&wndclass) ) return false;
int xaddend = GetSystemMetrics(fixedsize?SM_CXFIXEDFRAME:SM_CXFRAME)*2;
int yaddend = GetSystemMetrics(fixedsize?SM_CYFIXEDFRAME:SM_CYFRAME)*2 + GetSystemMetrics(SM_CYCAPTION);
if(wndclass.lpszMenuName) yaddend += GetSystemMetrics(SM_CYMENU);
// Setup the new window's physical parameters - and tell Windows to create it
g_hAppWnd = CreateWindowA(wndclass.lpszClassName, // Window class name
title, // Window caption
!fixedsize ? WS_OVERLAPPEDWINDOW : // Window style
WS_OVERLAPPED|WS_CAPTION|WS_SYSMENU|WS_MINIMIZEBOX,
CW_USEDEFAULT, // Initial x pos: use default placement
0, // Initial y pos: not used here
g_sizex+xaddend,// Initial x size
g_sizey+yaddend,// Initial y size
NULL, // parent window handle
NULL, // window menu handle
hInstance, // program instance handle
NULL); // Creation parameters
return g_hAppWnd != NULL;
}
//! create console window with redirection
static bool RedirectIOToConsole(void)
{
int hConHandle; size_t lStdHandle;
CONSOLE_SCREEN_BUFFER_INFO coninfo;
FILE *fp;
// allocate a console for this app
AllocConsole();
// set the screen buffer to be big enough to let us scroll text
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &coninfo);
coninfo.dwSize.Y = MAX_CONSOLE_LINES;
SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE), coninfo.dwSize);
// redirect unbuffered STDOUT to the console
lStdHandle = (size_t)GetStdHandle(STD_OUTPUT_HANDLE);
hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
if(hConHandle <= 0) return false;
fp = _fdopen( hConHandle, "w" );
*stdout = *fp;
setvbuf( stdout, NULL, _IONBF, 0 );
// redirect unbuffered STDERR to the console
lStdHandle = (size_t)GetStdHandle(STD_ERROR_HANDLE);
hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
if(hConHandle > 0) {
fp = _fdopen( hConHandle, "w" );
*stderr = *fp;
setvbuf( stderr, NULL, _IONBF, 0 );
}
// redirect unbuffered STDIN to the console
lStdHandle = (size_t)GetStdHandle(STD_INPUT_HANDLE);
hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
if(hConHandle > 0) {
fp = _fdopen( hConHandle, "r" );
*stdin = *fp;
setvbuf( stdin, NULL, _IONBF, 0 );
}
// make cout, wcout, cin, wcin, wcerr, cerr, wclog and clog
// point to console as well
std::ios::sync_with_stdio();
return true;
}
video::video()
: depth(24), red_shift(16), green_shift(8), blue_shift(0),
red_mask(0xff0000), green_mask(0xff00), blue_mask(0xff)
{
assert(g_video == 0);
g_video = this; title = "Video"; running = threaded = calc_fps = false; updating = true;
}
//! optionally call it just before init() to set own
void video::win_set_class(WNDCLASSEX &wcex)
{
gWndClass = &wcex;
}
void video::win_load_accelerators(int idc)
{
hAccelTable = LoadAccelerators(win_hInstance, MAKEINTRESOURCE(idc));
}
bool video::init_console()
{
if(RedirectIOToConsole()) {
if(!g_pImg && g_sizex && g_sizey)
g_pImg = new unsigned int[g_sizex * g_sizey];
if(g_pImg) running = true;
return true;
}
return false;
}
video::~video()
{
if(g_video) terminate();
}
DWORD WINAPI thread_video(LPVOID lpParameter)
{
video *v = (video*)lpParameter;
v->on_process();
return 0;
}
static bool loop_once(video *v)
{
// screen update notify
if(int updates = g_updates) {
g_updates = 0;
if(g_video->updating) { g_skips += updates-1; g_fps++; }
else g_skips += updates;
UpdateWindow(g_hAppWnd);
}
// update fps
DWORD msec = GetTickCount();
if(v->calc_fps && msec >= g_msec+1000) {
double sec = (msec - g_msec)/1000.0;
char buffer[256], n = _snprintf(buffer, 128, "%s: %d fps", v->title, int(double(g_fps + g_skips)/sec));
if(g_skips) _snprintf(buffer+n, 128, " - %d skipped = %d updates", int(g_skips/sec), int(g_fps/sec));
SetWindowTextA(g_hAppWnd, buffer);
g_msec = msec; g_skips = g_fps = 0;
}
// event processing, including painting
MSG msg;
if(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)){
if( msg.message == WM_QUIT ) { v->running = false; return false; }
if( !hAccelTable || !TranslateAccelerator(msg.hwnd, hAccelTable, &msg) ){
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return true; // try again
}
return false;
}
//! Do standard event loop
void video::main_loop()
{
// let Windows draw and unroll the window
InvalidateRect(g_hAppWnd, 0, false);
g_msec = GetTickCount(); // let's stay for 0,5 sec
while(g_msec + 500 > GetTickCount()) { loop_once(this); Sleep(1); }
g_msec = GetTickCount();
// now, start main process
if(threaded) {
g_handles[0] = CreateThread (
NULL, // LPSECURITY_ATTRIBUTES security_attrs
0, // SIZE_T stacksize
(LPTHREAD_START_ROUTINE) thread_video,
this, // argument
0, 0);
if(!g_handles[0]) { DisplayError("Can't create thread"); return; }
else // harmless race is possible here
g_handles[1] = CreateEvent(NULL, false, false, NULL);
while(running) {
while(loop_once(this));
YIELD_TO_THREAD(); // give time for processing when running on single CPU
DWORD r = MsgWaitForMultipleObjects(2, g_handles, false, INFINITE, QS_ALLINPUT^QS_MOUSEMOVE);
if(r == WAIT_OBJECT_0) break; // thread terminated
}
running = false;
if(WaitForSingleObject(g_handles[0], 3000) == WAIT_TIMEOUT){
// there was not enough time for graceful shutdown, killing the example with code 1.
exit(1);
}
if(g_handles[0]) CloseHandle(g_handles[0]);
if(g_handles[1]) CloseHandle(g_handles[1]);
g_handles[0] = g_handles[1] = 0;
}
else on_process();
}
//! Refresh screen picture
bool video::next_frame()
{
if(!running) return false;
g_updates++; // Fast but inaccurate counter. The data race here is benign.
if(!threaded) while(loop_once(this));
else if(g_handles[1]) {
SetEvent(g_handles[1]);
YIELD_TO_THREAD();
}
return true;
}
//! Change window title
void video::show_title()
{
if(g_hAppWnd)
SetWindowTextA(g_hAppWnd, title);
}
#endif //__WINVIDEO_H__

View File

@@ -0,0 +1,56 @@
/*
Copyright (c) 2005-2020 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#import <Foundation/Foundation.h>
#if TARGET_OS_IPHONE
#import <UIKit/UIKit.h>
#import "OpenGLES/ES2/gl.h"
@interface OpenGLView : UIView {
NSTimer *timer;
CGRect imageRect;
}
@property (nonatomic, retain) NSTimer *timer;
@property (nonatomic) CGRect imageRect;
- (void) drawRect:(CGRect)rect;
- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
@end
#elif TARGET_OS_MAC
#import <Foundation/Foundation.h>
#import <Cocoa/Cocoa.h>
@interface OpenGLView : NSOpenGLView{
NSTimer *timer;
}
@property (nonatomic,retain) NSTimer *timer;
- (void) drawRect:(NSRect)start;
- (void) mouseDown:(NSEvent *)theEvent;
- (void) keyDown:(NSEvent *)theEvent;
- (BOOL) acceptsFirstResponder;
- (void) viewDidEndLiveResize;
@end
#endif

View File

@@ -0,0 +1,143 @@
/*
Copyright (c) 2005-2020 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#import <Foundation/Foundation.h>
#import "OpenGLView.h"
// defined in macvideo.cpp
extern char* window_title;
extern int cocoa_update;
extern int g_sizex, g_sizey;
extern unsigned int *g_pImg;
void on_mouse_func(int x, int y, int k);
void on_key_func(int x);
bool initialized = false;
#if TARGET_OS_IPHONE
#import "OpenGLES/ES2/gl.h"
@implementation OpenGLView
@synthesize timer;
@synthesize imageRect;
- (void)drawRect:(CGRect)start
{
if (initialized == false) {
NSLog(@"INITIALIZE");
timer = [NSTimer scheduledTimerWithTimeInterval:0.03 target:self selector:@selector(update_window) userInfo:nil repeats:YES];
imageRect = [[UIScreen mainScreen] bounds];
CGFloat full_height = imageRect.size.height;
const float ratio=(float)g_sizex/g_sizey;
imageRect.size.height=imageRect.size.width/ratio;
imageRect.origin.y=(full_height-imageRect.size.height)/2;
initialized = true;
}
CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
CGDataProviderRef dataProvider = CGDataProviderCreateWithData(NULL, g_pImg, 4*g_sizex*g_sizey, NULL);
CGImageRef inputImage = CGImageCreate(g_sizex, g_sizey, 8, 32, g_sizex * 4, colourSpace,(CGBitmapInfo)kCGImageAlphaNoneSkipLast, dataProvider, NULL, NO, kCGRenderingIntentDefault);
UIImage *image = [UIImage imageWithCGImage:inputImage];
CGDataProviderRelease(dataProvider);
CGColorSpaceRelease(colourSpace);
CGImageRelease(inputImage);
[image drawInRect:imageRect];
}
- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
CGPoint point = [[touches anyObject] locationInView:self];
const int x = point.x;
const int y = point.y;
if ( (y-imageRect.origin.y) > 0 && y < (imageRect.origin.y + imageRect.size.height ))
on_mouse_func( x*g_sizex/(imageRect.size.width), (y-imageRect.origin.y)*g_sizey/imageRect.size.height,1);
[self setNeedsDisplay];
}
-(void) update_window{
if( cocoa_update ) [self setNeedsDisplay];
}
@end
#elif TARGET_OS_MAC
#import <OpenGL/gl.h>
@implementation OpenGLView
@synthesize timer;
- (void) drawRect:(NSRect)start
{
if (initialized == false) {
NSLog(@"INITIALIZE");
timer = [NSTimer scheduledTimerWithTimeInterval:0.03 target:self selector:@selector(update_window) userInfo:nil repeats:YES];
initialized = true;
}
glWindowPos2i(0, (int)self.visibleRect.size.height);
glPixelZoom( (float)self.visibleRect.size.width /(float)g_sizex,
-(float)self.visibleRect.size.height/(float)g_sizey);
glDrawPixels(g_sizex, g_sizey, GL_BGRA_EXT, GL_UNSIGNED_INT_8_8_8_8_REV, g_pImg);
glFlush();
}
-(void) update_window{
if( cocoa_update ) [self setNeedsDisplay:YES];
if( window_title ) [self.window setTitle:[NSString stringWithFormat:@"%s", window_title]];
}
-(void) keyDown:(NSEvent *)theEvent{
on_key_func([theEvent.characters characterAtIndex:0]);
}
-(void) mouseDown:(NSEvent *)theEvent{
// mouse event for seismic and fractal
NSPoint point= theEvent.locationInWindow;
const int x = (int)point.x;
const int y = (int)point.y;
NSRect rect = self.visibleRect;
on_mouse_func(x*g_sizex/(int)rect.size.width,((int)rect.size.height-y)*g_sizey/(int)rect.size.height,1);
[self setNeedsDisplay:YES];
}
- (BOOL) acceptsFirstResponder
{
return YES;
}
- (void) rightMouseDown:(NSEvent *)theEvent
{
return;
}
-(void) viewDidEndLiveResize
{
NSRect rect = self.visibleRect;
const int x=(int)rect.size.width;
const int y=(int)rect.size.height;
[self.window setTitle:[NSString stringWithFormat:@"X=%d Y=%d", x,y]];
}
@end
#endif

View File

@@ -0,0 +1 @@
APPL????

View File

@@ -0,0 +1,2 @@
/* Localized versions of Info.plist keys */

View File

@@ -0,0 +1,48 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="9060" systemVersion="15B42" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none">
<dependencies>
<deployment identifier="macosx"/>
<plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="9060"/>
</dependencies>
<objects>
<customObject id="-2" userLabel="File's Owner" customClass="NSApplication">
<connections>
<outlet property="delegate" destination="494" id="495"/>
</connections>
</customObject>
<customObject id="-1" userLabel="First Responder" customClass="FirstResponder"/>
<customObject id="-3" userLabel="Application"/>
<menu title="AMainMenu" systemMenu="main" id="29">
<items>
<menuItem title="tbbExample" id="56">
<menu key="submenu" title="tbbExample" systemMenu="apple" id="57">
<items>
<menuItem title="Quit tbbExample" keyEquivalent="q" id="136">
<connections>
<action selector="terminate:" target="-3" id="449"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
</items>
</menu>
<window title="tbbExample" allowsToolTipsWhenApplicationIsInactive="NO" deferred="NO" oneShot="NO" releasedWhenClosed="NO" showsToolbarButton="NO" animationBehavior="default" id="371">
<windowStyleMask key="styleMask" titled="YES" closable="YES" miniaturizable="YES" resizable="YES"/>
<windowPositionMask key="initialPositionMask" leftStrut="YES" rightStrut="YES" topStrut="YES" bottomStrut="YES"/>
<rect key="contentRect" x="100" y="100" width="480" height="360"/>
<rect key="screenRect" x="0.0" y="0.0" width="1280" height="1002"/>
<view key="contentView" focusRingType="none" horizontalHuggingPriority="1" verticalHuggingPriority="9" horizontalCompressionResistancePriority="1" verticalCompressionResistancePriority="1" id="372" customClass="OpenGLView">
<rect key="frame" x="0.0" y="0.0" width="480" height="360"/>
<autoresizingMask key="autoresizingMask"/>
<animations/>
</view>
</window>
<customObject id="494" customClass="tbbAppDelegate">
<connections>
<outlet property="window" destination="371" id="532"/>
</connections>
</customObject>
<customObject id="420" customClass="NSFontManager"/>
</objects>
</document>

View File

@@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="9060" systemVersion="15B42" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" initialViewController="AKo-RD-jUr">
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="9051"/>
</dependencies>
<scenes>
<!--View Controller-->
<scene sceneID="aF8-QV-POo">
<objects>
<viewController id="AKo-RD-jUr" sceneMemberID="viewController">
<layoutGuides>
<viewControllerLayoutGuide type="top" id="SEe-ff-xUc"/>
<viewControllerLayoutGuide type="bottom" id="Cp9-IV-SKb"/>
</layoutGuides>
<view key="view" contentMode="scaleToFill" id="1aY-my-944" customClass="OpenGLView">
<rect key="frame" x="0.0" y="0.0" width="320" height="568"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
<animations/>
<color key="backgroundColor" white="0.0" alpha="1" colorSpace="custom" customColorSpace="calibratedWhite"/>
</view>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="wcZ-9q-FxX" userLabel="First Responder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="90" y="88"/>
</scene>
</scenes>
</document>

View File

@@ -0,0 +1,47 @@
/*
Copyright (c) 2005-2020 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#import <Availability.h>
#import <Foundation/Foundation.h>
#if TARGET_OS_IPHONE
#import <UIKit/UIKit.h>
#import "tbbAppDelegate.h"
void get_screen_resolution(int *x, int *y) {
// Getting landscape screen resolution in any case
CGRect imageRect = [[UIScreen mainScreen] bounds];
*x=imageRect.size.width>imageRect.size.height?imageRect.size.width:imageRect.size.height;
*y=imageRect.size.width<imageRect.size.height?imageRect.size.width:imageRect.size.height;
return;
}
int cocoa_main(int argc, char * argv[]) {
@autoreleasepool {
return UIApplicationMain(argc, argv, nil, NSStringFromClass([tbbAppDelegate class]));
}
}
#elif TARGET_OS_MAC
#import <Cocoa/Cocoa.h>
int cocoa_main(int argc, char *argv[])
{
return NSApplicationMain(argc, (const char **)argv);
}
#endif

View File

@@ -0,0 +1,47 @@
/*
Copyright (c) 2005-2020 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
//
// Created by Xcode* 4.3.2
//
#import <Foundation/Foundation.h>
#if TARGET_OS_IPHONE
#import <UIKit/UIKit.h>
@interface tbbAppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end
#elif TARGET_OS_MAC
#import <Cocoa/Cocoa.h>
@interface tbbAppDelegate : NSObject <NSApplicationDelegate>{
__unsafe_unretained NSWindow *_window;
}
@property (assign) IBOutlet NSWindow *window;
- (BOOL) applicationShouldTerminateAfterLastWindowClosed:(NSApplication *) sender;
@end
#endif

View File

@@ -0,0 +1,62 @@
/*
Copyright (c) 2005-2020 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#import "tbbAppDelegate.h"
#if TARGET_OS_IPHONE
@implementation tbbAppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
return YES;
}
- (void)applicationDidEnterBackground:(UIApplication *)application
{
exit(EXIT_SUCCESS);
}
@end
#elif TARGET_OS_MAC
@implementation tbbAppDelegate
@synthesize window = _window;
//declared in macvideo.cpp file
extern int g_sizex, g_sizey;
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
// Insert code here to initialize your application
NSRect windowSize;
windowSize.size.height = g_sizey;
windowSize.size.width = g_sizex;
windowSize.origin=_window.frame.origin;
[_window setFrame:windowSize display:YES];
}
- (BOOL) applicationShouldTerminateAfterLastWindowClosed:(NSApplication *) sender
{
return YES;
}
@end
#endif

View File

@@ -0,0 +1,44 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>UILaunchStoryboardName</key>
<string>iOS</string>
<key>UIMainStoryboardFile</key>
<string>iOS</string>
<key>UIRequiredDeviceCapabilities</key>
<array>
<string>armv7</string>
</array>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
</dict>
</plist>

View File

@@ -0,0 +1,45 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleDisplayName</key>
<string></string>
<key>CFBundleExecutable</key>
<string>${EXECUTABLE_NAME}</string>
<key>CFBundleIconFile</key>
<string></string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>${PRODUCT_NAME}</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>LSApplicationCategoryType</key>
<string>public.app-category.business</string>
<key>LSEnvironment</key>
<dict>
<key>DYLD_LIBRARY_PATH</key>
<string>Contents/Resources:.:../Resources:/tmp:$DYLD_LIBRARY_PATH</string>
<key>LIBRARY_PATH</key>
<string>Contents/Resources:.:../:/tmp:$DYLD_LIBRARY_PATH</string>
</dict>
<key>LSMinimumSystemVersion</key>
<string>${MACOSX_DEPLOYMENT_TARGET}</string>
<key>NSHumanReadableCopyright</key>
<string>Copyright 2005-2020 Intel Corporation. All Rights Reserved.</string>
<key>NSMainNibFile</key>
<string>MainMenu</string>
<key>NSPrincipalClass</key>
<string>NSApplication</string>
</dict>
</plist>

View File

@@ -0,0 +1,32 @@
/*
Copyright (c) 2005-2020 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
//
// Prefix header for all source files of the 'tbbExample' target in the 'tbbExample' project
//
#import <Availability.h>
#if TARGET_OS_IPHONE
#ifdef __OBJC__
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#endif
#elif TARGET_OS_MAC
#ifdef __OBJC__
#import <Cocoa/Cocoa.h>
#endif
#endif

View File

@@ -0,0 +1,382 @@
/*
Copyright (c) 2005-2020 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Uncomment next line to disable shared memory features if you do not have libXext
// (http://www.xfree86.org/current/mit-shm.html)
//#define X_NOSHMEM
// Note that it may happen that the build environment supports the shared-memory extension
// (so there's no build-time reason to disable the relevant code by defining X_NOSHMEM),
// but that using shared memory still fails at run time.
// This situation will (ultimately) cause the error handler set by XSetErrorHandler()
// to be invoked with XErrorEvent::minor_code==X_ShmAttach. The code below tries to make
// such a determination at XShmAttach() time, which seems plausible, but unfortunately
// it has also been observed in a specific environment that the error may be reported
// at a later time instead, even after video::init_window() has returned.
// It is not clear whether this may happen in that way in any environment where it might
// depend on the kind of display, e.g., local vs. over "ssh -X", so #define'ing X_NOSHMEM
// may not always be the appropriate solution, therefore an environment variable
// has been introduced to disable shared memory at run time.
// A diagnostic has been added to advise the user about possible workarounds.
// X_ShmAttach macro was changed to 1 due to recent changes to X11/extensions/XShm.h header.
#include "video.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/keysym.h>
#include <sys/time.h>
#include <signal.h>
#include <pthread.h>
#ifndef X_NOSHMEM
#include <errno.h>
#include <X11/extensions/XShm.h>
#include <sys/ipc.h>
#include <sys/shm.h>
static XShmSegmentInfo shmseginfo;
static Pixmap pixmap = 0;
static bool already_called_X_ShmAttach = false;
static bool already_advised_about_NOSHMEM_workarounds = false;
static const char* NOSHMEM_env_var_name = "TBB_EXAMPLES_X_NOSHMEM";
#endif
static char *display_name = NULL;
static Display *dpy = NULL;
static Screen *scrn;
static Visual *vis;
static Colormap cmap;
static GC gc;
static Window win, rootW;
static int dispdepth = 0;
static XGCValues xgcv;
static XImage *ximage;
static int x_error = 0;
static int vidtype = 3;
int g_sizex, g_sizey;
static video *g_video = 0;
unsigned int *g_pImg = 0;
static int g_fps = 0;
struct timeval g_time;
static pthread_mutex_t g_mutex = PTHREAD_MUTEX_INITIALIZER;
Atom _XA_WM_DELETE_WINDOW = 0;// like in Xatom.h
///////////////////////////////////////////// public methods of video class ///////////////////////
video::video()
{
assert(g_video == 0);
g_video = this; title = "Video"; calc_fps = running = false; updating = true;
}
inline void mask2bits(unsigned int mask, unsigned int &save, depth_t &shift)
{
save = mask; if(!mask) { shift = dispdepth/3; return; }
shift = 0; while(!(mask&1)) ++shift, mask >>= 1;
int bits = 0; while(mask&1) ++bits, mask >>= 1;
shift += bits - 8;
}
int xerr_handler(Display* dpy_, XErrorEvent *error)
{
x_error = error->error_code;
if(g_video) g_video->running = false;
#ifndef X_NOSHMEM
if (error->minor_code==1/*X_ShmAttach*/ && already_called_X_ShmAttach && !already_advised_about_NOSHMEM_workarounds)
{
char err[256]; XGetErrorText(dpy_, x_error, err, 255);
fprintf(stderr, "Warning: Can't attach shared memory to display: %s (%d)\n", err, x_error);
fprintf(stderr, "If you are seeing a black output window, try setting %s environment variable to 1"
" to disable shared memory extensions (0 to re-enable, other values undefined),"
" or rebuilding with X_NOSHMEM defined in " __FILE__ "\n", NOSHMEM_env_var_name);
already_advised_about_NOSHMEM_workarounds = true;
}
#else
(void) dpy_; // warning prevention
#endif
return 0;
}
bool video::init_window(int xsize, int ysize)
{
{ //enclose local variables before fail label
g_sizex = xsize; g_sizey = ysize;
// Open the display
if (!dpy) {
dpy = XOpenDisplay(display_name);
if (!dpy) {
fprintf(stderr, "Can't open X11 display %s\n", XDisplayName(display_name));
goto fail;
}
}
int theScreen = DefaultScreen(dpy);
scrn = ScreenOfDisplay(dpy, theScreen);
dispdepth = DefaultDepth(dpy, theScreen);
XVisualInfo vinfo;
if (!( (dispdepth >= 15 && dispdepth <= 32 && XMatchVisualInfo(dpy, theScreen, dispdepth, TrueColor, &vinfo) )
|| XMatchVisualInfo(dpy, theScreen, 24, TrueColor, &vinfo)
|| XMatchVisualInfo(dpy, theScreen, 32, TrueColor, &vinfo)
|| XMatchVisualInfo(dpy, theScreen, 16, TrueColor, &vinfo)
|| XMatchVisualInfo(dpy, theScreen, 15, TrueColor, &vinfo)
)) {
fprintf(stderr, "Display has no appropriate True Color visual\n");
goto fail;
}
vis = vinfo.visual;
depth = dispdepth = vinfo.depth;
mask2bits(vinfo.red_mask, red_mask, red_shift);
mask2bits(vinfo.green_mask, green_mask, green_shift);
mask2bits(vinfo.blue_mask, blue_mask, blue_shift);
rootW = RootWindow(dpy, theScreen);
cmap = XCreateColormap(dpy, rootW, vis, AllocNone);
XSetWindowAttributes attrs;
attrs.backing_store = Always;
attrs.colormap = cmap;
attrs.event_mask = StructureNotifyMask|KeyPressMask|ButtonPressMask|ButtonReleaseMask;
attrs.background_pixel = BlackPixelOfScreen(scrn);
attrs.border_pixel = WhitePixelOfScreen(scrn);
win = XCreateWindow(dpy, rootW,
0, 0, xsize, ysize, 2,
dispdepth, InputOutput, vis,
CWBackingStore | CWColormap | CWEventMask |
CWBackPixel | CWBorderPixel,
&attrs);
if(!win) {
fprintf(stderr, "Can't create the window\n");
goto fail;
}
XSizeHints sh;
sh.flags = PSize | PMinSize | PMaxSize;
sh.width = sh.min_width = sh.max_width = xsize;
sh.height = sh.min_height = sh.max_height = ysize;
XSetStandardProperties( dpy, win, g_video->title, g_video->title, None, NULL, 0, &sh );
_XA_WM_DELETE_WINDOW = XInternAtom(dpy, "WM_DELETE_WINDOW", false);
XSetWMProtocols(dpy, win, &_XA_WM_DELETE_WINDOW, 1);
gc = XCreateGC(dpy, win, 0L, &xgcv);
XMapRaised(dpy, win);
XFlush(dpy);
#ifdef X_FULLSYNC
XSynchronize(dpy, true);
#endif
XSetErrorHandler(xerr_handler);
int imgbytes = xsize*ysize*(dispdepth<=16?2:4);
const char *vidstr;
#ifndef X_NOSHMEM
int major, minor, pixmaps;
if(XShmQueryExtension(dpy) &&
XShmQueryVersion(dpy, &major, &minor, &pixmaps))
{ // Shared memory
if(NULL!=getenv(NOSHMEM_env_var_name) && 0!=strcmp("0",getenv(NOSHMEM_env_var_name))) {
goto generic;
}
shmseginfo.shmid = shmget(IPC_PRIVATE, imgbytes, IPC_CREAT|0777);
if(shmseginfo.shmid < 0) {
fprintf(stderr, "Warning: Can't get shared memory: %s\n", strerror(errno));
goto generic;
}
g_pImg = (unsigned int*)(shmseginfo.shmaddr = (char*)shmat(shmseginfo.shmid, 0, 0));
if(g_pImg == (unsigned int*)-1) {
fprintf(stderr, "Warning: Can't attach to shared memory: %s\n", strerror(errno));
shmctl(shmseginfo.shmid, IPC_RMID, NULL);
goto generic;
}
shmseginfo.readOnly = false;
if(!XShmAttach(dpy, &shmseginfo) || x_error) {
char err[256]; XGetErrorText(dpy, x_error, err, 255);
fprintf(stderr, "Warning: Can't attach shared memory to display: %s (%d)\n", err, x_error);
shmdt(shmseginfo.shmaddr); shmctl(shmseginfo.shmid, IPC_RMID, NULL);
goto generic;
}
already_called_X_ShmAttach = true;
#ifndef X_NOSHMPIX
if(pixmaps && XShmPixmapFormat(dpy) == ZPixmap)
{ // Pixmaps
vidtype = 2; vidstr = "X11 shared memory pixmap";
pixmap = XShmCreatePixmap(dpy, win, (char*)g_pImg, &shmseginfo, xsize, ysize, dispdepth);
XSetWindowBackgroundPixmap(dpy, win, pixmap);
} else
#endif//!X_NOSHMPIX
{ // Standard
vidtype = 1; vidstr = "X11 shared memory";
ximage = XShmCreateImage(dpy, vis, dispdepth,
ZPixmap, 0, &shmseginfo, xsize, ysize);
if(!ximage) {
fprintf(stderr, "Can't create the shared image\n");
goto fail;
}
assert(ximage->bytes_per_line == xsize*(dispdepth<=16?2:4));
ximage->data = shmseginfo.shmaddr;
}
} else
#endif
{
#ifndef X_NOSHMEM
generic:
#endif
vidtype = 0; vidstr = "generic X11";
g_pImg = new unsigned int[imgbytes/sizeof(int)];
ximage = XCreateImage(dpy, vis, dispdepth, ZPixmap, 0, (char*)g_pImg, xsize, ysize, 32, imgbytes/ysize);
if(!ximage) {
fprintf(stderr, "Can't create the image\n");
goto fail;
}
}
if( ximage ) {
// Note: It may be more efficient to adopt the server's byte order
// and swap once per get_color() call instead of once per pixel.
const uint32_t probe = 0x03020100;
const bool big_endian = (((const char*)(&probe))[0]==0x03);
ximage->byte_order = big_endian ? MSBFirst : LSBFirst;
}
printf("Note: using %s with %s visual for %d-bit color depth\n", vidstr, vis==DefaultVisual(dpy, theScreen)?"default":"non-default", dispdepth);
running = true;
return true;
} // end of enclosing local variables
fail:
terminate(); init_console();
return false;
}
bool video::init_console()
{
if(!g_pImg && g_sizex && g_sizey) {
dispdepth = 24; red_shift = 16; vidtype = 3; // fake video
g_pImg = new unsigned int[g_sizex*g_sizey];
running = true;
}
return true;
}
void video::terminate()
{
running = false;
if(dpy) {
vidtype = 3; // stop video
if(threaded) { pthread_mutex_lock(&g_mutex); pthread_mutex_unlock(&g_mutex); }
if(ximage) { XDestroyImage(ximage); ximage = 0; g_pImg = 0; } // it frees g_pImg for vidtype == 0
#ifndef X_NOSHMEM
if(pixmap) XFreePixmap(dpy, pixmap);
if(shmseginfo.shmaddr) { XShmDetach(dpy, &shmseginfo); shmdt(shmseginfo.shmaddr); g_pImg = 0; }
if(shmseginfo.shmid >= 0) shmctl(shmseginfo.shmid, IPC_RMID, NULL);
#endif
if(gc) XFreeGC(dpy, gc);
if(win) XDestroyWindow(dpy, win);
XCloseDisplay(dpy); dpy = 0;
}
if(g_pImg) { delete[] g_pImg; g_pImg = 0; } // if was allocated for console mode
}
video::~video()
{
if(g_video) terminate();
g_video = 0;
}
//! Do standard event loop
void video::main_loop()
{
struct timezone tz; gettimeofday(&g_time, &tz);
on_process();
}
//! Check for pending events once
bool video::next_frame()
{
if(!running) return false;
//! try acquire mutex if threaded code, returns on failure
if(vidtype == 3 || threaded && pthread_mutex_trylock(&g_mutex))
return running;
//! Refresh screen picture
g_fps++;
#ifndef X_NOSHMPIX
if(vidtype == 2 && updating) XClearWindow(dpy, win);
#endif
while( XPending(dpy) ) {
XEvent report; XNextEvent(dpy, &report);
switch( report.type ) {
case ClientMessage:
if(report.xclient.format != 32 || report.xclient.data.l[0] != _XA_WM_DELETE_WINDOW) break;
case DestroyNotify:
running = false;
case KeyPress:
on_key( XLookupKeysym(&report.xkey, 0) ); break;
case ButtonPress:
on_mouse( report.xbutton.x, report.xbutton.y, report.xbutton.button ); break;
case ButtonRelease:
on_mouse( report.xbutton.x, report.xbutton.y, -report.xbutton.button ); break;
}
}
struct timezone tz; struct timeval now_time; gettimeofday(&now_time, &tz);
double sec = (now_time.tv_sec+1.0*now_time.tv_usec/1000000.0) - (g_time.tv_sec+1.0*g_time.tv_usec/1000000.0);
if(sec > 1) {
memcpy(&g_time, &now_time, sizeof(g_time));
if(calc_fps) {
double fps = g_fps; g_fps = 0;
char buffer[256]; snprintf(buffer, 256, "%s%s: %d fps", title, updating?"":" (no updating)", int(fps/sec));
XStoreName(dpy, win, buffer);
}
#ifndef X_FULLSYNC
XSync(dpy, false); // It is often better then using XSynchronize(dpy, true)
#endif//X_FULLSYNC
}
if(threaded) pthread_mutex_unlock(&g_mutex);
return true;
}
//! Change window title
void video::show_title()
{
if(vidtype < 3)
XStoreName(dpy, win, title);
}
drawing_area::drawing_area(int x, int y, int sizex, int sizey)
: base_index(y*g_sizex + x), max_index(g_sizex*g_sizey), index_stride(g_sizex),
pixel_depth(dispdepth), ptr32(g_pImg), start_x(x), start_y(y), size_x(sizex), size_y(sizey)
{
assert(x < g_sizex); assert(y < g_sizey);
assert(x+sizex <= g_sizex); assert(y+sizey <= g_sizey);
index = base_index; // current index
}
void drawing_area::update()
{
if(!g_video->updating) return;
#ifndef X_NOSHMEM
switch(vidtype) {
case 0:
#endif
pthread_mutex_lock(&g_mutex);
if(vidtype == 0) XPutImage(dpy, win, gc, ximage, start_x, start_y, start_x, start_y, size_x, size_y);
pthread_mutex_unlock(&g_mutex);
#ifndef X_NOSHMEM
break;
case 1:
pthread_mutex_lock(&g_mutex);
if(vidtype == 1) XShmPutImage(dpy, win, gc, ximage, start_x, start_y, start_x, start_y, size_x, size_y, false);
pthread_mutex_unlock(&g_mutex);
break;
/*case 2: make it in next_frame(); break;*/
}
#endif
}

View File

@@ -0,0 +1,399 @@
<!DOCTYPE html>
<html xmlns:mso="urn:schemas-microsoft-com:office:office" xmlns:msdt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882">
<head>
<meta charset="UTF-8">
<style>
::selection {
background: #b7ffb7;
}
::-moz-selection {
background: #b7ffb7;
}
body {
font-family: Arial, Helvetica, sans-serif;
font-size: 16px;
width: 800px;
margin: 0 auto;
}
#banner {
/* Div for banner */
float:left;
margin: 0px;
margin-bottom: 10px;
width: 100%;
background-color: #0071C5;
z-index: 0;
}
#banner .logo {
/* Apply to logo in banner. Add as class to image tag. */
float: left;
margin-right: 20px;
margin-left: 20px;
margin-top: 15px;
padding-bottom: 5px;
}
h1 {
text-align: center;
font-size: 36px;
}
h1.title {
/* Add as class to H1 in banner */
font-family: "Intel Clear", Verdana, Arial, sans-serif;
font-weight:normal;
color: #FFFFFF;
font-size: 170%;
margin-right: 40px;
margin-left: 40px;
padding-right: 20px;
text-indent: 20px;
}
.h3-alike {
display:inline;
font-size: 1.17em;
font-weight: bold;
color: #0071C5;
}
h3 {
font-size: 1.17em;
font-weight: bold;
color: #0071C5;
}
.h4-alike {
display:inline;
font-size: 1.05em;
font-weight: bold;
}
pre {
font-family: "Consolas", Monaco, monospace;
font-size:small;
background: #fafafa;
margin: 0;
padding-left:20px;
}
#footer {
font-size: small;
}
code {
font-family: "Consolas", Monaco, monospace;
}
.code-block
{
padding-left:20px;
}
.changes {
margin: 1em 0;
}
.changes input:active {
position: relative;
top: 1px;
}
.changes input:hover:after {
padding-left: 16px;
font-size: 10px;
content: 'More';
}
.changes input:checked:hover:after {
content: 'Less';
}
.changes input + .show-hide {
display: none;
}
.changes input:checked + .show-hide {
display: block;
}
ul {
margin: 0;
padding: 0.5em 0 0.5em 2.5em;
}
ul li {
margin-bottom: 3px;
}
ul li:last-child {
margin-bottom: 0;
}
.disc {
list-style-type:disc
}
.circ {
list-style-type:circle
}
.single {
padding: 0 0.5em;
}
/* ------------------------------------------------- */
/* Table styles */
table{
margin-bottom:5pt;
border-collapse:collapse;
margin-left:0px;
margin-top:0.3em;
font-size:10pt;
}
tr{
vertical-align:top;
}
th,
th h3{
padding:4px;
text-align:left;
background-color:#0071C5;
font-weight:bold;
margin-top:1px;
margin-bottom:0;
color:#FFFFFF;
font-size:10pt;
vertical-align:middle;
}
th{
border:1px #dddddd solid;
padding-top:2px;
padding-bottom:0px;
padding-right:3px;
padding-left:3px;
}
td{
border:1px #dddddd solid;
vertical-align:top;
font-size:100%;
text-align:left;
margin-bottom:0;
}
td,
td p{
margin-top:0;
margin-left:0;
text-align:left;
font-size:inherit;
line-height:120%;
}
td p{
margin-bottom:0;
padding-top:5px;
padding-bottom:5px;
padding-right:5px;
padding-left:1px;
}
.noborder{
border:0px none;
}
.noborder1stcol{
border:0px none;
padding-left:0pt;
}
td ol{
font-size:inherit;
margin-left:28px;
}
td ul{
font-size:inherit;
margin-left:24px;
}
.DefListTbl{
width:90%;
margin-left:-3pt;
}
.syntaxdiagramtbl{
margin-left:-3pt;
}
.sdtbl{
}
.sdrow{
}
.sdtblp{
border:0px none;
font-size:inherit;
line-height:120%;
margin-bottom:0;
padding-bottom:0px;
padding-top:5px;
padding-left:0px;
padding-right:5px;
vertical-align:top;
}
.idepara, .ide_para{
border:0px none;
font-size:inherit;
line-height:120%;
margin-bottom:0;
padding-bottom:0px;
padding-top:5px;
padding-left:0px;
padding-right:5px;
vertical-align:top;
}
.specs {
border-collapse:collapse;
}
.specs td, .specs th {
font-size: 14px;
}
.specs td {
border: 1px solid black;
}
.specs td td, .specs td th {
border: none;
}
.specs td, .specs td td, .specs td th {
padding: 0 0.2em 0.2em;
text-align: center;
}
.specs td tr:last-child td,
.specs td tr:last-child th {
padding: 0 0.2em;
}
.serial-time {
}
.modified-time {
width: 6.5em;
}
.compiler {
}
.comp-opt {
}
.sys-specs {
width: 18em;
}
.note {
font-size:small;
font-style: italic;
}
</style>
<title>Intel&reg; Threading Building Blocks. Common source code for samples</title>
</head>
<body>
<div id="banner">
<img class="logo" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEMAAAAsCAYAAAA+aAX8AAAAAXNSR0IArs4c6QAAAARnQU1BAACx
jwv8YQUAAAAJcEhZcwAALiIAAC4iAari3ZIAAAAZdEVYdFNvZnR3YXJlAEFkb2JlIEltYWdlUmVh
ZHlxyWU8AAAIN0lEQVRoQ+WaCaxdUxSGW2ouatZWaVS15nkqkZhSVERQglLEPCam1BCixhqqCKUS
NIiYpxhqHmouIeaY5ylFzA/v1fev8+/j3N5737v3vtf3buNP/uy9/7X2Ovuse4a997m9mgltbW2L
wRHwcHgFfAx+AH+GCb/BT2fNmvUk5ZXwYOrrOsTcCU5CJ74pPBJeA5+Bn8LfOLmagf/f8Af4NrwD
ngg3wdTHh2pOMMB1Gejx8AE4M85mNqD/A7+D78GXkXQFTIMPwUfhdPg6/AxWTRw29b8QruPD9zwY
zPrwHPi2xxmg3QrfgDfD05BGU24EB1HvC3s7REXgtwDsDzeEY+Ak+AJsUfwE2sJdcBN37V4whiU4
+KGUM2JEBtpzUInZEa5g9y4FcYfAo+GLPmwOND2HFrXrnAUHWgnq0vzDB2+Bt0H9coPs1m3gmNvD
ZyITBu234Jp26XoQfCC80sfTAXVv7wOXskuPgnHoSvnTw9P49MDdyOauAQEXhWdC4Vd4ARxmc1OB
cW0Gv3U+lJDvKFa0ufMg4GXwR3gs7J57sRNoaWnR2+znLB2RkKds6jwItvbckIQiGO+eTkSby71t
qh100qtsUCJxmmpSw5i2gWebR1jWm2047T1gf0vyfViJEKi/TtHua7wMdNJs8U/zDzjUpqYA47k4
O704wY+kUZ2P+glQc5ldac9j323sF1cH2EB6h8BxYZdbRDeDOJ16UBJiHDFuMMdYbhjEGA8DxJ4h
jXIemmMpz6ccqbZ1JUlT/3SrHC+9XeB0MjzV9RHqKFAXVg2nBkH/lxxO8aZYbhjEKEuGQH1BuCKc
z1IAN61jAtiut1wZ+ByIkwa6r9t6ZmhSFZw9eL0gxiMw4SLLDYMYFZNRDbhpcpgwzXI5MOqSEvKM
Ue8D+xU4r/Xe+C8HB1ThkhFgNqAXk6FVqyZuA1LcItBXQd+WUvf6YMslwFZvMs7KvMP/SculwKa3
hfYPPsZpfsvS9QD9PRHbcOmUC9J+H2qfoRJ/0MHgFhHIQC8mQ8twxZ0Ji099vSGegn/TP0BdD/Db
Ycn0nna9yZiceQcetFwKDE/4oNtZCtDeXHoC7dWlU1Uyvs7U6sBHJ7FaBAPU82TYJUAzFnCU+1mq
COyfwGLi6k3G05l34BrL/wFxjA/0mKUcaNqBKiJODHclQ3sLCVqZprfEvVCLtThhiskRDFAvXhnv
QPlfi5uW7ytTL14Nr0Bd1pfDXy1Lv93h6koGLstCLR/SuPJ5SQBBD8hPZATbWs6BrdZk7B4dDNpT
Mjkw3bL0YjLOsxygPUWDyExtD1GNV6JAeyTUBlDCKtbrScYxhfjyj1s+B9o+dnifIj94AnpNyaC9
f3QwkNJCTnjOsvRiMi6xrHiaA3ycyYFNbcqBpisl/aoHWaspGdg03uIc43mb/gOilt3CREslQG80
GedmlkC1KyNPBnU9wOPWMp6Aut0S74HfwIQJ7ldTMjBPdBIiGWC0TRkQlseWNmR2tlwC9DmZjEmW
pQ/zOAKqtwdcrnW/DpOBPtp9Ii6F9lhL1yWIo2zUvVhxzYHeLVcG/QfT/iuTA3qwan+zGndVP8p2
k4G8E/wLW4D6PxTlnxgwaDEjaMe6n+USYOvqZKTbUrjQcor3ZSYHRtjULvCrmgwkfY5oRc9B+3Cb
S4FhIhS+gAtZLgH9Y6GWuQU6mwx9IEqYajlA+47CsZ6lGovFBDTNkA9xM4CmpXsAWySDUrPjqZQl
QBsfnSoB41UKAvS9ouJmDfpaDpTQ2WRcXYinCZm+pdyEtDClPgLloP0unABPp3lrpoZ+KkWskSgP
sVZMhlat2t7LQftE2aoCh0sVBOheXclyCYjTp7W19bUsZAQtJuPLTA39gOhg0D7PJtny1xj1tWA+
sUpAG2j7mZaqAh9tzPSVP+XStL+w/qY1XRlfWdOSYXvp7QKnU6Ayqk4jLZcB2zD4gv1iu52qkvG5
NKPsyrCuPs9aDtDeDr4EtS7RRyXNCgfYLPtYfoC33D0Hul6tE6jOfvsMhVqaT8PWG85PXR+WxlOP
pHUIHPNXDsif7NWAT773STdlX6vK4ebi4WRgWybZqFe86tBXUAw4BL+S7UTautTXo9yFcjdKPbsq
PuQTsKdbZ16YLzZrAgdRRvXLCF/Big/R/wXInn5dffdMt8opNs214Bz6cyqNbUDRcZwTIWjDt3m+
XtcBxq3pvL6p6mFftlFUE+i8JPxRCRGoawVbcVepGcF4V4eTGPNPHv+7NjUGAhzmQOl20fyhphlg
T4CxLcQw9WC9Gxb3P4Q37NY4CHJXCuhSW3JnwEXs0qNgSHqVbw210ZP2XwK0A65/6C6NgziaAU5X
wCIUHB4H86227gKH1+JtL3gd1N5sCdACbgZo5rtgnQKx+hLs/ixsdjBXBd2TtyKNhUOp1/dprgMQ
rx9x16fcn1KbttrIyf9OkICWw1KApvY2YyXbpSBobKf7OGXApFtI+5d3Qq1BDoL6V87GcDVc9Ivq
E4D+bjTQbc1i9demreDu8Ch0ffG6hdnmDMrvFbsSsAXczIGk3fwb4VYe+pwBB9Angkd83ADtqgkq
AjetdTTV1icDlfl+Qi3AP4elHEjaDXscHgFjPdNt4ID6S9B9sNLiKoelmuFuJbCpDJi+hvqz2qFw
iIfWc2AQusxPgvq484vH2eUgtpYHH0Hteeqb75ZwMQ+j+cDg9PlwFDwd6o9sr0KtbWI/tSPgp32M
76H+s6mNX3030df5neGq1OtbZDUbOIlFoFaha0L9j0qfCHeAerDqVtODU8+hNThZfR1fHHbpG6kx
9Or1LzUmVVz+HJXDAAAAAElFTkSuQmCC">
<h1 class="title">Intel&reg; Threading Building Blocks.<br>Common source code for samples</h1>
</div>
<p>
This directory contains common code that is used in the Intel&reg; Threading Building Blocks (Intel&reg; TBB) samples.
<br>
This code is not intended to be used directly. It is incorporated automatically by the examples that need it.
</p>
<div class="changes">
<div class="h3-alike">Directories</div>
<input type="checkbox" checked="checked">
<div class="show-hide">
<dl>
<dt><a href="gui/">gui</a>
<dd>
GUI code for examples that have graphical user interfaces. Currently supports:
<ul>
<li>GDI+*, DirectDraw*, Direct2D* (Windows* systems)
<li>OpenGL* (macOS* systems)
<li>X window (Linux* or macOS* systems)
</ul>
See the examples that use the GUI
(<a href="../graph/stereo/readme.html">stereo</a>,
<a href="../parallel_for/tachyon/readme.html">tachyon</a>,
<a href="../parallel_for/seismic/readme.html">seismic</a>,
<a href="../task_arena/fractal/readme.html">fractal</a>)
for more details.
</dl>
<dl>
<dt><a href="utility/">utility</a>
<dd>Common driver and utility code for examples. Currently provides:
<ul>
<li>class FastRandom - a random number generator that uses linear congruential method
(<a href="utility/fast_random.h">fast_random.h</a>)
<li>class thread_number_range - a class to specify the numbers of threads an example should use
(<a href="utility/utility.h">utility.h</a>)
<li>support for command line interface - class cli_argument_pack and function parse_cli_arguments
(<a href="utility/utility.h">utility.h</a>)
</ul>
</dl>
</div>
</div>
<div class="changes">
<div class="h3-alike">Common information</div>
<input type="checkbox" checked="checked">
<div class="show-hide">
<br>
<div class="h4-alike">Number of threads</div>
<p>
Most Intel TBB examples allow to specify <i>n-of-threads</i>, the set of thread numbers that should be used to run an example.
<br>Usually, it is a range of the form <i>low[:high[:(+|*|#)S]]</i>, where <i>low</i> and optional <i>high</i>
are non-negative integers or 'auto' for the default choice, and optional step expression <i>(+|*|#)S</i>
specifies how thread numbers are chosen within the range:
<ul>
<li>With <i>+/*</i>, the previous number is incremented/multiplied by <i>S</i>.
E.g., expression '12:16:+1' means 12,13,14,15,16 threads, and '1:16:*2' means 1,2,4,8,16 threads.
<li>With <i>#</i>, <i>S</i> is the desired number of steps between any subsequent powers of 2;
it must be a power of 2 on its own, with most meaningful values being 2, 4, and 8.
For a given number of threads, the actual step value is computed as the quotient
of the nearest smaller power of 2 divided by the number of steps, but is at least 1.
E.g., '1:32:#4' means 1,2,3,4,5,6,7,8,10,12,14,16,20,24,28,32 threads;
note the step doubling at 8 and 16 to keep 4 steps between powers of 2.
</ul>
A default value for the number of threads can be customized in an example. If not customized, it is '1:auto:#4'.
The 'auto' parameter is substituted with a value returned by a specified function
(this function is typically <code>utility::get_default_num_threads()</code>, which returns a copy of
constant that was initialized with <code>tbb::global_control::active_value(tbb::global_control::max_allowed_parallelism)</code>
at the start of the program).
</p>
</div>
</div>
<br>
<a href="../index.html">Up to parent directory</a>
<hr>
<div class="changes">
<div class="h3-alike">Legal Information:</div>
<input type="checkbox">
<div class="show-hide">
<p>
Intel and the Intel logo are trademarks of Intel Corporation in the U.S. and/or other countries.
<br>* Other names and brands may be claimed as the property of others.
<br>&copy; 2020, Intel Corporation
</p>
</div>
</div>
</body>
</html>

View File

@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<PlatformToolset Condition="Exists('$(VCTargetsPath)\Platforms\$(Platform)\PlatformToolsets\Intel C++ Compiler 15.0 [Intel(R) System Studio]')">Intel C++ Compiler 15.0 [Intel(R) System Studio]</PlatformToolset>
<PlatformToolset Condition="Exists('$(VCTargetsPath)\Platforms\$(Platform)\PlatformToolsets\Intel C++ Compiler XE 15.0')">Intel C++ Compiler XE 15.0</PlatformToolset>
<PlatformToolset Condition="Exists('$(VCTargetsPath)\Platforms\$(Platform)\PlatformToolsets\Intel C++ Compiler 16.0')">Intel C++ Compiler 16.0</PlatformToolset>
<UseIntelTBB Condition="'$(UseIntelTBB)' == ''">true</UseIntelTBB>
</PropertyGroup>
</Project>

View File

@@ -0,0 +1,78 @@
/*
Copyright (c) 2005-2020 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef FAST_RANDOM_H_
#define FAST_RANDOM_H_
namespace utility{
//------------------------------------------------------------------------
// FastRandom
//------------------------------------------------------------------------
namespace internal{
size_t GetPrime ( size_t seed );
}
//! A fast random number generator.
/** Uses linear congruential method. */
class FastRandom {
size_t x, a;
public:
//! Get a random number.
unsigned short get() {
return get(x);
}
//! Get a random number for the given seed; update the seed for next use.
unsigned short get( size_t& seed ) {
unsigned short r = (unsigned short)(seed>>16);
seed = seed*a+1;
return r;
}
//! Construct a random number generator.
FastRandom( size_t seed ) {
x = seed*internal::GetPrime(seed);
a = internal::GetPrime(x);
}
};
}
namespace utility {
namespace internal{
//! Table of primes used by fast random-number generator (FastRandom).
static const unsigned Primes[] = {
0x9e3779b1, 0xffe6cc59, 0x2109f6dd, 0x43977ab5,
0xba5703f5, 0xb495a877, 0xe1626741, 0x79695e6b,
0xbc98c09f, 0xd5bee2b3, 0x287488f9, 0x3af18231,
0x9677cd4d, 0xbe3a6929, 0xadc6a877, 0xdcf0674b,
0xbe4d6fe9, 0x5f15e201, 0x99afc3fd, 0xf3f16801,
0xe222cfff, 0x24ba5fdb, 0x0620452d, 0x79f149e3,
0xc8b93f49, 0x972702cd, 0xb07dd827, 0x6c97d5ed,
0x085a3d61, 0x46eb5ea7, 0x3d9910ed, 0x2e687b5b,
0x29609227, 0x6eb081f1, 0x0954c4e1, 0x9d114db9,
0x542acfa9, 0xb3e6bd7b, 0x0742d917, 0xe9f3ffa7,
0x54581edb, 0xf2480f45, 0x0bb9288f, 0xef1affc7,
0x85fa0ca7, 0x3ccc14db, 0xe6baf34b, 0x343377f7,
0x5ca19031, 0xe6d9293b, 0xf0a9f391, 0x5d2e980b,
0xfc411073, 0xc3749363, 0xb892d829, 0x3549366b,
0x629750ad, 0xb98294e5, 0x892d9483, 0xc235baf3,
0x3d2402a3, 0x6bdef3c9, 0xbec333cd, 0x40c9520f
};
size_t GetPrime ( size_t seed ) {
return Primes[seed%(sizeof(Primes)/sizeof(Primes[0]))];
}
}
}
#endif /* FAST_RANDOM_H_ */

View File

@@ -0,0 +1,32 @@
/*
Copyright (c) 2005-2020 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef GET_DEFAULT_NUM_THREADS_H_
#define GET_DEFAULT_NUM_THREADS_H_
#include "tbb/global_control.h"
namespace utility {
inline int get_default_num_threads() {
#if __TBB_MIC_OFFLOAD
#pragma offload target(mic) out(default_num_threads)
#endif // __TBB_MIC_OFFLOAD
static size_t default_num_threads = tbb::global_control::active_value(tbb::global_control::max_allowed_parallelism);
return static_cast<int>(default_num_threads);
}
}
#endif /* GET_DEFAULT_NUM_THREADS_H_ */

View File

@@ -0,0 +1,523 @@
/*
Copyright (c) 2005-2020 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef UTILITY_H_
#define UTILITY_H_
#if __TBB_MIC_OFFLOAD
#pragma offload_attribute (push,target(mic))
#include <exception>
#include <cstdio>
#pragma offload_attribute (pop)
#endif // __TBB_MIC_OFFLOAD
#include <utility>
#include <string>
#include <cstring>
#include <vector>
#include <map>
#include <set>
#include <algorithm>
#include <sstream>
#include <numeric>
#include <stdexcept>
#include <memory>
#include <cassert>
#include <iostream>
#include <cstdlib>
// TBB headers should not be used, as some examples may need to be built without TBB.
namespace utility{
namespace internal{
#if (_MSC_VER >= 1600 || __cplusplus >= 201103L || __GXX_EXPERIMENTAL_CXX0X__) \
&& (_CPPLIB_VER || _LIBCPP_VERSION || __GLIBCXX__ && _UNIQUE_PTR_H ) \
&& (!__INTEL_COMPILER || __INTEL_COMPILER >= 1200 )
// std::unique_ptr is available, and compiler can use it
#define smart_ptr std::unique_ptr
using std::swap;
#else
#if __INTEL_COMPILER && __GXX_EXPERIMENTAL_CXX0X__
// std::unique_ptr is unavailable, so suppress std::auto_prt<> deprecation warning
#pragma warning(disable: 1478)
#endif
#define smart_ptr std::auto_ptr
// in some C++ libraries, std::swap does not work with std::auto_ptr
template<typename T>
void swap( std::auto_ptr<T>& ptr1, std::auto_ptr<T>& ptr2 ) {
std::auto_ptr<T> tmp; tmp = ptr2; ptr2 = ptr1; ptr1 = tmp;
}
#endif
//TODO: add tcs
template<class dest_type>
dest_type& string_to(std::string const& s, dest_type& result){
std::stringstream stream(s);
stream>>result;
if ((!stream)||(stream.fail())){
throw std::invalid_argument("error converting string '"+std::string(s)+"'");
}
return result;
}
template<class dest_type>
dest_type string_to(std::string const& s){
dest_type result;
return string_to(s,result);
}
template<typename>
struct is_bool { static bool value(){return false;}};
template<>
struct is_bool<bool> { static bool value(){return true;}};
class type_base {
type_base& operator=(const type_base&);
public:
const std::string name;
const std::string description;
type_base (std::string a_name, std::string a_description) : name(a_name), description(a_description) {}
virtual void parse_and_store(const std::string & s) = 0;
virtual std::string value() const = 0;
virtual smart_ptr<type_base> clone() const = 0;
virtual ~type_base(){}
};
template <typename type>
class type_impl : public type_base {
private:
type_impl(const type_impl& src) : type_base(src.name, src.description), target(src.target),
validating_function(src.validating_function) {}
type_impl& operator=(const type_impl&);
typedef bool(*validating_function_type)(const type&);
type & target;
validating_function_type validating_function;
public:
type_impl(std::string a_name, std::string a_description, type & a_target, validating_function_type a_validating_function = NULL)
: type_base (a_name,a_description), target(a_target),validating_function(a_validating_function)
{};
void parse_and_store (const std::string & s) /*override*/ {
try{
const bool is_bool = internal::is_bool<type>::value();
if (is_bool && s.empty()){
//to avoid directly assigning true
//(as it will impose additional layer of indirection)
//so, simply pass it as string
internal::string_to("1",target);
}else {
internal::string_to(s,target);
}
}catch(std::invalid_argument& e){
std::stringstream str;
str <<"'"<<s<<"' is incorrect input for argument '"<<name<<"'"
<<" ("<<e.what()<<")";
throw std::invalid_argument(str.str());
}
if (validating_function){
if (!((validating_function)(target))){
std::stringstream str;
str <<"'"<<target<<"' is invalid value for argument '"<<name<<"'";
throw std::invalid_argument(str.str());
}
}
}
template <typename t>
static bool is_null_c_str(t&){return false;}
static bool is_null_c_str(char* s){return s==NULL;}
std::string value() const /*override*/ {
std::stringstream str;
if (!is_null_c_str(target))
str<<target;
return str.str();
}
smart_ptr<type_base> clone() const /*override*/ {
return smart_ptr<type_base>(new type_impl(*this));
}
};
class argument{
private:
smart_ptr<type_base> p_type;
bool matched_;
public:
argument(argument const& other)
: p_type(other.p_type.get() ? (other.p_type->clone()).release() : NULL)
,matched_(other.matched_)
{}
argument& operator=(argument a){
this->swap(a);
return *this;
}
void swap(argument& other){
internal::swap(p_type, other.p_type);
std::swap(matched_,other.matched_);
}
template<class type>
argument(std::string a_name, std::string a_description, type& dest, bool(*a_validating_function)(const type&)= NULL)
:p_type(new type_impl<type>(a_name,a_description,dest,a_validating_function))
,matched_(false)
{}
std::string value()const{
return p_type->value();
}
std::string name()const{
return p_type->name;
}
std::string description() const{
return p_type->description;
}
void parse_and_store(const std::string & s){
p_type->parse_and_store(s);
matched_=true;
}
bool is_matched() const{return matched_;}
};
} // namespace internal
class cli_argument_pack{
typedef std::map<std::string,internal::argument> args_map_type;
typedef std::vector<std::string> args_display_order_type;
typedef std::vector<std::string> positional_arg_names_type;
private:
args_map_type args_map;
args_display_order_type args_display_order;
positional_arg_names_type positional_arg_names;
std::set<std::string> bool_args_names;
private:
void add_arg(internal::argument const& a){
std::pair<args_map_type::iterator, bool> result = args_map.insert(std::make_pair(a.name(),a));
if (!result.second){
throw std::invalid_argument("argument with name: '"+a.name()+"' already registered");
}
args_display_order.push_back(a.name());
}
public:
template<typename type>
cli_argument_pack& arg(type& dest,std::string const& name, std::string const& description, bool(*validate)(const type &)= NULL){
internal::argument a(name,description,dest,validate);
add_arg(a);
if (internal::is_bool<type>::value()){
bool_args_names.insert(name);
}
return *this;
}
//Positional means that argument name can be omitted in actual CL
//only key to match values for parameters with
template<typename type>
cli_argument_pack& positional_arg(type& dest,std::string const& name, std::string const& description, bool(*validate)(const type &)= NULL){
internal::argument a(name,description,dest,validate);
add_arg(a);
if (internal::is_bool<type>::value()){
bool_args_names.insert(name);
}
positional_arg_names.push_back(name);
return *this;
}
void parse(std::size_t argc, char const* argv[]){
{
std::size_t current_positional_index=0;
for (std::size_t j=1;j<argc;j++){
internal::argument* pa = NULL;
std::string argument_value;
const char * const begin=argv[j];
const char * const end=begin+std::strlen(argv[j]);
const char * const assign_sign = std::find(begin,end,'=');
struct throw_unknown_parameter{ static void _(std::string const& location){
throw std::invalid_argument(std::string("unknown parameter starting at:'")+location+"'");
}};
//first try to interpret it like parameter=value string
if (assign_sign!=end){
std::string name_found = std::string(begin,assign_sign);
args_map_type::iterator it = args_map.find(name_found );
if(it!=args_map.end()){
pa= &((*it).second);
argument_value = std::string(assign_sign+1,end);
}else {
throw_unknown_parameter::_(argv[j]);
}
}
//then see is it a named flag
else{
args_map_type::iterator it = args_map.find(argv[j] );
if(it!=args_map.end()){
pa= &((*it).second);
argument_value = "";
}
//then try it as positional argument without name specified
else if (current_positional_index < positional_arg_names.size()){
std::stringstream str(argv[j]);
args_map_type::iterator found_positional_arg = args_map.find(positional_arg_names.at(current_positional_index));
//TODO: probably use of smarter assert would help here
assert(found_positional_arg!=args_map.end()/*&&"positional_arg_names and args_map are out of sync"*/);
if (found_positional_arg==args_map.end()){
throw std::logic_error("positional_arg_names and args_map are out of sync");
}
pa= &((*found_positional_arg).second);
argument_value = argv[j];
current_positional_index++;
}else {
//TODO: add tc to check
throw_unknown_parameter::_(argv[j]);
}
}
assert(pa);
if (pa->is_matched()){
throw std::invalid_argument(std::string("several values specified for: '")+pa->name()+"' argument");
}
pa->parse_and_store(argument_value);
}
}
}
std::string usage_string(const std::string& binary_name)const{
std::string command_line_params;
std::string summary_description;
for (args_display_order_type::const_iterator it = args_display_order.begin();it!=args_display_order.end();++it){
const bool is_bool = (0!=bool_args_names.count((*it)));
args_map_type::const_iterator argument_it = args_map.find(*it);
//TODO: probably use of smarter assert would help here
assert(argument_it!=args_map.end()/*&&"args_display_order and args_map are out of sync"*/);
if (argument_it==args_map.end()){
throw std::logic_error("args_display_order and args_map are out of sync");
}
const internal::argument & a = (*argument_it).second;
command_line_params +=" [" + a.name() + (is_bool ?"":"=value")+ "]";
summary_description +=" " + a.name() + " - " + a.description() +" ("+a.value() +")" + "\n";
}
std::string positional_arg_cl;
for (positional_arg_names_type::const_iterator it = positional_arg_names.begin();it!=positional_arg_names.end();++it){
positional_arg_cl +=" ["+(*it);
}
for (std::size_t i=0;i<positional_arg_names.size();++i){
positional_arg_cl+="]";
}
command_line_params+=positional_arg_cl;
std::stringstream str;
using std::endl;
str << " Program usage is:" << endl
<< " " << binary_name << command_line_params
<< endl << endl
<< " where:" << endl
<< summary_description
;
return str.str();
}
}; // class cli_argument_pack
namespace internal {
template<typename T>
bool is_power_of_2( T val ) {
size_t intval = size_t(val);
return (intval&(intval-1)) == size_t(0);
}
int step_function_plus(int previous, double step){
return static_cast<int>(previous+step);
}
int step_function_multiply(int previous, double multiply){
return static_cast<int>(previous*multiply);
}
// "Power-of-2 ladder": nsteps is the desired number of steps between any subsequent powers of 2.
// The actual step is the quotient of the nearest smaller power of 2 divided by that number (but at least 1).
// E.g., '1:32:#4' means 1,2,3,4,5,6,7,8,10,12,14,16,20,24,28,32
int step_function_power2_ladder(int previous, double nsteps){
int steps = int(nsteps);
assert( is_power_of_2(steps) ); // must be a power of 2
// The actual step is 1 until the value is twice as big as nsteps
if( previous < 2*steps )
return previous+1;
// calculate the previous power of 2
int prev_power2 = previous/2; // start with half the given value
int rshift = 1; // and with the shift of 1;
while( int shifted = prev_power2>>rshift ) { // shift the value right; while the result is non-zero,
prev_power2 |= shifted; // add the bits set in 'shifted';
rshift <<= 1; // double the shift, as twice as many top bits are set;
} // repeat.
++prev_power2; // all low bits set; now it's just one less than the desired power of 2
assert( is_power_of_2(prev_power2) );
assert( (prev_power2<=previous)&&(2*prev_power2>previous) );
// The actual step value is the previous power of 2 divided by steps
return previous + (prev_power2/steps);
}
typedef int (* step_function_ptr_type)(int,double);
struct step_function_descriptor {
char mnemonic;
step_function_ptr_type function;
public:
step_function_descriptor(char a_mnemonic, step_function_ptr_type a_function) : mnemonic(a_mnemonic), function(a_function) {}
private:
void operator=(step_function_descriptor const&);
};
step_function_descriptor step_function_descriptors[] = {
step_function_descriptor('*',step_function_multiply),
step_function_descriptor('+',step_function_plus),
step_function_descriptor('#',step_function_power2_ladder)
};
template<typename T, size_t N>
inline size_t array_length(const T(&)[N])
{
return N;
}
struct thread_range_step {
step_function_ptr_type step_function;
double step_function_argument;
thread_range_step ( step_function_ptr_type step_function_, double step_function_argument_)
:step_function(step_function_),step_function_argument(step_function_argument_)
{
if (!step_function_)
throw std::invalid_argument("step_function for thread range step should not be NULL");
}
int operator()(int previous)const {
assert(0<=previous); // test 0<=first and loop discipline
const int ret = step_function(previous,step_function_argument);
assert(previous<ret);
return ret;
}
friend std::istream& operator>>(std::istream& input_stream, thread_range_step& step){
char function_char;
double function_argument;
input_stream >> function_char >> function_argument;
size_t i = 0;
while ((i<array_length(step_function_descriptors)) && (step_function_descriptors[i].mnemonic!=function_char)) ++i;
if (i >= array_length(step_function_descriptors)){
throw std::invalid_argument("unknown step function mnemonic: "+std::string(1,function_char));
} else if ((function_char=='#') && !is_power_of_2(function_argument)) {
throw std::invalid_argument("the argument of # should be a power of 2");
}
step.step_function = step_function_descriptors[i].function;
step.step_function_argument = function_argument;
return input_stream;
}
};
} // namespace internal
struct thread_number_range{
int (*auto_number_of_threads)();
int first; // 0<=first (0 can be used as a special value)
int last; // first<=last
::utility::internal::thread_range_step step;
thread_number_range( int (*auto_number_of_threads_)(),int low_=1, int high_=-1
, ::utility::internal::thread_range_step step_ = ::utility::internal::thread_range_step(::utility::internal::step_function_power2_ladder,4)
)
: auto_number_of_threads(auto_number_of_threads_), first(low_), last((high_>-1) ? high_ : auto_number_of_threads_())
,step(step_)
{
if (first<0) {
throw std::invalid_argument("negative value not allowed");
}
if (first>last) {
throw std::invalid_argument("decreasing sequence not allowed");
}
}
friend std::istream& operator>>(std::istream& i, thread_number_range& range){
try{
std::string s;
i>>s;
struct string_to_number_of_threads{
int auto_value;
string_to_number_of_threads(int auto_value_):auto_value(auto_value_){}
int operator()(const std::string & value)const{
return (value=="auto")? auto_value : internal::string_to<int>(value);
}
};
string_to_number_of_threads string_to_number_of_threads(range.auto_number_of_threads());
int low, high;
std::size_t colon = s.find(':');
if ( colon == std::string::npos ){
low = high = string_to_number_of_threads(s);
} else {
//it is a range
std::size_t second_colon = s.find(':',colon+1);
low = string_to_number_of_threads(std::string(s, 0, colon)); //not copying the colon
high = string_to_number_of_threads(std::string(s, colon+1, second_colon - (colon+1))); //not copying the colons
if (second_colon != std::string::npos){
internal::string_to(std::string(s,second_colon + 1),range.step);
}
}
range = thread_number_range(range.auto_number_of_threads,low,high,range.step);
}catch(std::invalid_argument&){
i.setstate(std::ios::failbit);
throw;
}
return i;
}
friend std::ostream& operator<<(std::ostream& o, thread_number_range const& range){
using namespace internal;
size_t i = 0;
for (; i < array_length(step_function_descriptors) && step_function_descriptors[i].function != range.step.step_function; ++i ) {}
if (i >= array_length(step_function_descriptors)){
throw std::invalid_argument("unknown step function for thread range");
}
o<<range.first<<":"<<range.last<<":"<<step_function_descriptors[i].mnemonic<<range.step.step_function_argument;
return o;
}
}; // struct thread_number_range
//TODO: fix unused warning here
//TODO: update the thread range description in the .html files
static const char* thread_number_range_desc="number of threads to use; a range of the form low[:high[:(+|*|#)step]],"
"\n\twhere low and optional high are non-negative integers or 'auto' for the default choice,"
"\n\tand optional step expression specifies how thread numbers are chosen within the range."
"\n\tSee examples/common/index.html for detailed description."
;
inline void report_elapsed_time(double seconds){
std::cout<<"elapsed time : "<<seconds<<" seconds"<<std::endl;
}
inline void report_skipped(){
std::cout<<"skip"<<std::endl;
}
inline void parse_cli_arguments(int argc, const char* argv[], utility::cli_argument_pack cli_pack){
bool show_help = false;
cli_pack.arg(show_help,"-h","show this message");
bool invalid_input=false;
try {
cli_pack.parse(argc,argv);
}catch(std::exception& e){
std::cerr
<<"error occurred while parsing command line."<<std::endl
<<"error text: "<<e.what()<<std::endl
<<std::flush;
invalid_input =true;
}
if (show_help || invalid_input){
std::cout<<cli_pack.usage_string(argv[0])<<std::flush;
std::exit(0);
}
}
inline void parse_cli_arguments(int argc, char* argv[], utility::cli_argument_pack cli_pack){
parse_cli_arguments(argc, const_cast<const char**>(argv), cli_pack);
}
}
#endif /* UTILITY_H_ */