Merged changes in the trunk up to revision 38543.

Conflicts resolved:
doc/python_api/sphinx_doc_gen.py
source/blender/blenkernel/CMakeLists.txt
source/blender/makesdna/DNA_material_types.h
source/blender/render/intern/source/pipeline.c
source/creator/CMakeLists.txt
This commit is contained in:
2011-07-20 23:33:10 +00:00
395 changed files with 34491 additions and 33122 deletions

View File

@@ -53,10 +53,12 @@ if(NOT EXECUTABLE_OUTPUT_PATH)
set(FIRST_RUN "TRUE")
endif()
# this starts out unset
list(APPEND CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/build_files/cmake/Modules")
# avoid having empty buildtype
set(CMAKE_BUILD_TYPE_INIT "Release")
# quiet output for Makefiles, 'make -s' helps too
# set_property(GLOBAL PROPERTY RULE_MESSAGES OFF)
@@ -88,6 +90,9 @@ set(LIBRARY_OUTPUT_PATH ${CMAKE_BINARY_DIR}/lib CACHE INTERNAL "" FORCE )
get_blender_version()
# Blender internal features
option(WITH_BLENDER "Build blender (disable to build only the blender player)" ON)
mark_as_advanced(WITH_BLENDER)
option(WITH_INTERNATIONAL "Enable I18N (International fonts and text)" ON)
option(WITH_PYTHON "Enable Embedded Python API (only disable for development)" ON)
@@ -104,12 +109,21 @@ option(WITH_BULLET "Enable Bullet (Physics Engine)" ON)
option(WITH_GAMEENGINE "Enable Game Engine" ON)
option(WITH_PLAYER "Build Player" OFF)
option(WITH_AUDASPACE "Build with blenders audio library" ON)
mark_as_advanced(WITH_AUDASPACE)
# GHOST Windowing Library Options
option(WITH_GHOST_DEBUG "Enable debugging output for the GHOST library" OFF)
mark_as_advanced(WITH_GHOST_DEBUG)
option(WITH_GHOST_SDL "Enable building blender against SDL for windowing rather then the native APIs" OFF)
mark_as_advanced(WITH_GHOST_SDL)
# Misc...
option(WITH_HEADLESS "Build without graphical support (renderfarm, server mode only)" OFF)
mark_as_advanced(WITH_HEADLESS)
option(WITH_AUDASPACE "Build with blenders audio library (only disable if you know what you're doing!)" ON)
mark_as_advanced(WITH_AUDASPACE)
# (unix defaults to OpenMP On)
if(UNIX AND NOT APPLE)
option(WITH_OPENMP "Enable OpenMP (has to be supported by the compiler)" ON)
@@ -127,6 +141,7 @@ endif()
# Modifiers
option(WITH_MOD_FLUID "Enable Elbeem Modifier (Fluid Simulation)" ON)
option(WITH_MOD_SMOKE "Enable Smoke Modifier (Smoke Simulation)" ON)
option(WITH_MOD_DECIMATE "Enable Decimate Modifier" ON)
option(WITH_MOD_BOOLEAN "Enable Boolean Modifier" ON)
option(WITH_MOD_CLOTH_ELTOPO "Enable Experemental cloth solver" OFF)
@@ -142,7 +157,7 @@ option(WITH_IMAGE_HDR "Enable HDR Image Support" ON)
option(WITH_IMAGE_REDCODE "Enable RedCode Image Support" OFF)
# Audio/Video format support
option(WITH_CODEC_FFMPEG "Enable FFMPeg Support (http://ffmpeg.mplayerhq.hu)" OFF)
option(WITH_CODEC_FFMPEG "Enable FFMPeg Support (http://ffmpeg.org)" OFF)
option(WITH_CODEC_SNDFILE "Enable libsndfile Support (http://www.mega-nerd.com/libsndfile)" OFF)
if(APPLE OR (WIN32 AND NOT UNIX))
option(WITH_CODEC_QUICKTIME "Enable Quicktime Support" OFF)
@@ -199,6 +214,10 @@ endif()
#-----------------------------------------------------------------------------
# Check for conflicting/unsupported configurations
if(NOT WITH_BLENDER AND NOT WITH_PLAYER)
message(FATAL_ERROR "At least one of WITH_BLENDER or WITH_PLAYER must be enabled, nothing to do!")
endif()
if(NOT WITH_GAMEENGINE AND WITH_PLAYER)
message(FATAL_ERROR "WITH_PLAYER requires WITH_GAMEENGINE")
endif()
@@ -207,6 +226,10 @@ if(NOT WITH_AUDASPACE AND (WITH_OPENAL OR WITH_SDL OR WITH_JACK))
message(FATAL_ERROR "WITH_OPENAL/WITH_SDL/WITH_JACK/WITH_CODEC_FFMPEG require WITH_AUDASPACE")
endif()
if(NOT WITH_SDL AND WITH_GHOST_SDL)
message(FATAL_ERROR "WITH_GHOST_SDL requires WITH_SDL to be ON")
endif()
if(NOT WITH_IMAGE_OPENJPEG AND WITH_IMAGE_REDCODE)
message(FATAL_ERROR "WITH_IMAGE_REDCODE requires WITH_IMAGE_OPENJPEG")
endif()
@@ -240,11 +263,24 @@ TEST_SSE_SUPPORT()
set(WITH_BINRELOC OFF)
# MAXOSX only, set to avoid uninitialized
set(EXETYPE "")
set(EXETYPE)
# C/C++ flags
set(PLATFORM_CFLAGS)
# these are added to later on.
set(C_WARNINGS "")
set(CXX_WARNINGS "")
set(C_WARNINGS)
set(CXX_WARNINGS)
# libraries to link the binary with passed to target_link_libraries()
# known as LLIBS to scons
set(PLATFORM_LINKLIBS)
# Added to linker flags in setup_liblinks
# - CMAKE_EXE_LINKER_FLAGS
# - CMAKE_EXE_LINKER_FLAGS_DEBUG
set(PLATFORM_LINKFLAGS)
set(PLATFORM_LINKFLAGS_DEBUG)
# disabled for now, not supported
@@ -347,7 +383,7 @@ if(UNIX AND NOT APPLE)
endif()
if(WITH_CODEC_FFMPEG)
set(FFMPEG /usr CACHE FILEPATH "FFMPEG Directory")
set(FFMPEG /usr CACHE PATH "FFMPEG Directory")
mark_as_advanced(FFMPEG)
set(FFMPEG_INCLUDE_DIRS ${FFMPEG}/include)
set(FFMPEG_LIBRARIES avformat avcodec avutil avdevice swscale CACHE STRING "FFMPEG Libraries")
@@ -391,18 +427,18 @@ if(UNIX AND NOT APPLE)
endif()
if(WITH_OPENCOLLADA)
set(OPENCOLLADA /usr/local/opencollada CACHE FILEPATH "OpenCollada Directory")
set(OPENCOLLADA /usr/local/opencollada CACHE PATH "OpenCollada Directory")
mark_as_advanced(OPENCOLLADA)
set(OPENCOLLADA_LIBPATH ${OPENCOLLADA}/lib)
set(OPENCOLLADA_LIBRARIES OpenCOLLADAStreamWriter OpenCOLLADASaxFrameworkLoader OpenCOLLADAFramework OpenCOLLADABaseUtils GeneratedSaxParser UTF MathMLSolver pcre ftoa buffer xml2)
set(OPENCOLLADA_INCLUDE_DIR ${OPENCOLLADA})
set(PCRE /usr CACHE FILEPATH "PCRE Directory")
set(PCRE /usr CACHE PATH "PCRE Directory")
mark_as_advanced(PCRE)
set(PCRE_LIBPATH ${PCRE}/lib)
set(PCRE_LIB pcre)
set(EXPAT /usr CACHE FILEPATH "Expat Directory")
set(EXPAT /usr CACHE PATH "Expat Directory")
mark_as_advanced(EXPAT)
set(EXPAT_LIBPATH ${EXPAT}/lib)
set(EXPAT_LIB expat)
@@ -416,24 +452,24 @@ if(UNIX AND NOT APPLE)
endif()
# OpenSuse needs lutil, ArchLinux not, for now keep, can avoid by using --as-needed
set(LLIBS "-lutil -lc -lm -lpthread -lstdc++")
set(PLATFORM_LINKLIBS "-lutil -lc -lm -lpthread -lstdc++")
if(NOT WITH_HEADLESS)
if((NOT WITH_HEADLESS) AND (NOT WITH_GHOST_SDL))
find_package(X11 REQUIRED)
find_path(X11_XF86keysym_INCLUDE_PATH X11/XF86keysym.h ${X11_INC_SEARCH_PATH})
mark_as_advanced(X11_XF86keysym_INCLUDE_PATH)
list(APPEND LLIBS ${X11_X11_LIB})
list(APPEND PLATFORM_LINKLIBS ${X11_X11_LIB})
if(WITH_X11_XINPUT)
list(APPEND LLIBS ${X11_Xinput_LIB})
list(APPEND PLATFORM_LINKLIBS ${X11_Xinput_LIB})
endif()
endif()
if(CMAKE_SYSTEM_NAME MATCHES "Linux")
if(NOT WITH_PYTHON_MODULE)
# BSD's dont use libdl.so
list(APPEND LLIBS -ldl)
list(APPEND PLATFORM_LINKLIBS -ldl)
# binreloc is linux only
set(BINRELOC_INCLUDE_DIRS ${CMAKE_SOURCE_DIR}/extern/binreloc/include)
set(WITH_BINRELOC ON)
@@ -544,13 +580,15 @@ elseif(WIN32)
if(MSVC)
if(CMAKE_CL_64)
set(LLIBS ws2_32 vfw32 winmm kernel32 user32 gdi32 comdlg32 advapi32 shfolder shell32 ole32 oleaut32 uuid )
set(PLATFORM_LINKLIBS ws2_32 vfw32 winmm kernel32 user32 gdi32 comdlg32 advapi32 shfolder shell32 ole32 oleaut32 uuid)
else()
set(LLIBS kernel32 user32 gdi32 comdlg32 advapi32 shell32 ole32 oleaut32 uuid ws2_32 vfw32 winmm)
set(PLATFORM_LINKLIBS ws2_32 vfw32 winmm kernel32 user32 gdi32 comdlg32 advapi32 shfolder shell32 ole32 oleaut32 uuid)
endif()
set(CMAKE_CXX_FLAGS "/D_CRT_NONSTDC_NO_DEPRECATE /D_CRT_SECURE_NO_DEPRECATE /D_SCL_SECURE_NO_DEPRECATE /we4013 /wd4018 /wd4800 /wd4244 /wd4305 /wd4065 /wd4267" CACHE STRING "MSVC MT C++ flags " FORCE)
set(CMAKE_C_FLAGS "/D_CRT_NONSTDC_NO_DEPRECATE /D_CRT_SECURE_NO_DEPRECATE /D_SCL_SECURE_NO_DEPRECATE /we4013 /wd4018 /wd4800 /wd4244 /wd4305 /wd4065 /wd4267" CACHE STRING "MSVC MT C++ flags " FORCE)
add_definitions(/D_CRT_NONSTDC_NO_DEPRECATE /D_CRT_SECURE_NO_DEPRECATE /D_SCL_SECURE_NO_DEPRECATE /D_CONSOLE /D_LIB)
set(CMAKE_CXX_FLAGS "/nologo /J /W0 /Gd /wd4018 /wd4244 /wd4305 /wd4800 /wd4065 /wd4267 /we4013" CACHE STRING "MSVC MT C++ flags " FORCE)
set(CMAKE_C_FLAGS "/nologo /J /W0 /Gd /wd4018 /wd4244 /wd4305 /wd4800 /wd4065 /wd4267 /we4013 /EHsc" CACHE STRING "MSVC MT C++ flags " FORCE)
if(CMAKE_CL_64)
set(CMAKE_CXX_FLAGS_DEBUG "/D_DEBUG /Od /Gm /EHsc /RTC1 /MTd /W3 /nologo /Zi /J" CACHE STRING "MSVC MT flags " FORCE)
@@ -587,24 +625,22 @@ elseif(WIN32)
endif()
set(JPEG_LIBRARIES libjpeg)
set(ZLIB ${LIBDIR}/zlib)
set(ZLIB_INCLUDE_DIRS ${ZLIB}/include)
set(ZLIB_LIBPATH ${ZLIB}/lib)
set(ZLIB_INCLUDE_DIRS ${LIBDIR}/zlib/include)
if(CMAKE_CL_64)
set(ZLIB_LIBRARIES libz)
set(ZLIB_LIBRARIES ${LIBDIR}/zlib/lib/libz.lib)
else()
set(ZLIB_LIBRARIES zlib)
set(ZLIB_LIBRARIES ${LIBDIR}/zlib/lib/zlib.lib)
endif()
set(PTHREADS ${LIBDIR}/pthreads)
set(PTHREADS_INCLUDE_DIRS ${PTHREADS}/include)
set(PTHREADS_LIBPATH ${PTHREADS}/lib)
set(PTHREADS_LIBRARIES pthreadVC2)
set(PTHREADS_INCLUDE_DIRS ${LIBDIR}/pthreads/include)
set(PTHREADS_LIBRARIES ${LIBDIR}/pthreads/lib/pthreadVC2.lib)
set(FREETYPE ${LIBDIR}/freetype)
set(FREETYPE_INCLUDE_DIRS ${FREETYPE}/include ${FREETYPE}/include/freetype2)
set(FREETYPE_LIBPATH ${FREETYPE}/lib)
set(FREETYPE_LIBRARY freetype2ST)
set(FREETYPE_INCLUDE_DIRS
${LIBDIR}/freetype/include
${LIBDIR}/freetype/include/freetype2
)
set(FREETYPE_LIBRARY ${LIBDIR}/freetype/lib/freetype2ST.lib)
if(WITH_FFTW3)
set(FFTW3 ${LIBDIR}/fftw3)
@@ -635,10 +671,17 @@ elseif(WIN32)
endif()
if(WITH_CODEC_FFMPEG)
set(FFMPEG ${LIBDIR}/ffmpeg)
set(FFMPEG_INCLUDE_DIRS ${FFMPEG}/include ${FFMPEG}/include/msvc)
set(FFMPEG_LIBRARIES avcodec-52 avformat-52 avdevice-52 avutil-50 swscale-0)
set(FFMPEG_LIBPATH ${FFMPEG}/lib)
set(FFMPEG_INCLUDE_DIRS
${LIBDIR}/ffmpeg/include
${LIBDIR}/ffmpeg/include/msvc
)
set(FFMPEG_LIBRARIES
${LIBDIR}/ffmpeg/lib/avcodec-52.lib
${LIBDIR}/ffmpeg/lib/avformat-52.lib
${LIBDIR}/ffmpeg/lib/avdevice-52.lib
${LIBDIR}/ffmpeg/lib/avutil-50.lib
${LIBDIR}/ffmpeg/lib/swscale-0.lib
)
endif()
if(WITH_IMAGE_OPENEXR)
@@ -673,43 +716,47 @@ elseif(WIN32)
endif()
if(WITH_IMAGE_TIFF)
set(TIFF ${LIBDIR}/tiff)
set(TIFF_LIBRARY libtiff)
set(TIFF_INCLUDE_DIR ${TIFF}/include)
set(TIFF_LIBPATH ${TIFF}/lib)
set(TIFF_LIBRARY ${LIBDIR}/tiff/lib/libtiff.lib)
set(TIFF_INCLUDE_DIR ${LIBDIR}/tiff/include)
endif()
if(WITH_JACK)
set(JACK ${LIBDIR}/jack)
set(JACK_INCLUDE_DIRS ${JACK}/include/jack ${JACK}/include)
set(JACK_LIBRARIES libjack)
set(JACK_LIBPATH ${JACK}/lib)
set(JACK_INCLUDE_DIRS
${LIBDIR}/jack/include/jack
${LIBDIR}/jack/include
)
set(JACK_LIBRARIES ${LIBDIR}/jack/lib/libjack.lib)
endif()
if(WITH_PYTHON)
set(PYTHON_VERSION 3.2)
set(PYTHON_INCLUDE_DIRS "${LIBDIR}/python/include/python${PYTHON_VERSION}")
# set(PYTHON_BINARY python) # not used yet
set(PYTHON_LIBRARIES ${LIBDIR}/python/lib/python32.lib)
# normally cached but not since we include them with blender
set(PYTHON_VERSION 3.2) # CACHE STRING)
set(PYTHON_INCLUDE_DIR "${LIBDIR}/python/include/python${PYTHON_VERSION}") # CACHE PATH)
set(PYTHON_LIBRARY "${LIBDIR}/python/lib/python32.lib") #CACHE FILEPATH)
# uncached vars
set(PYTHON_INCLUDE_DIRS "${PYTHON_INCLUDE_DIR}")
set(PYTHON_LIBRARIES "${PYTHON_LIBRARY}")
endif()
set(PLATFORM_LINKFLAGS "/SUBSYSTEM:CONSOLE /STACK:2097152 /INCREMENTAL:NO /NODEFAULTLIB:msvcrt.lib /NODEFAULTLIB:msvcmrt.lib /NODEFAULTLIB:msvcurt.lib /NODEFAULTLIB:msvcrtd.lib")
# MSVC only, Mingw doesnt need
if(CMAKE_CL_64)
set(PLATFORM_LINKFLAGS "/MACHINE:X64 /NODEFAULTLIB:libc.lib /STACK:2097152 ")
set(PLATFORM_LINKFLAGS "/MACHINE:X64 /OPT:NOREF ${PLATFORM_LINKFLAGS}")
else()
set(PLATFORM_LINKFLAGS "/NODEFAULTLIB:libc.lib /STACK:2097152 ")
set(PLATFORM_LINKFLAGS "/MACHINE:IX86 /LARGEADDRESSAWARE ${PLATFORM_LINKFLAGS}")
endif()
set(CMAKE_EXE_LINKER_FLAGS_DEBUG "${CMAKE_EXE_LINKER_FLAGS_DEBUG} /NODEFAULTLIB:libcmt.lib;libc.lib ")
set(PLATFORM_LINKFLAGS_DEBUG "/NODEFAULTLIB:libcmt.lib /NODEFAULTLIB:libc.lib")
else()
# keep GCC spesific stuff here
if(CMAKE_COMPILER_IS_GNUCC)
set(LLIBS "-lshell32 -lshfolder -lgdi32 -lmsvcrt -lwinmm -lmingw32 -lm -lws2_32 -lz -lstdc++ -lole32 -luuid")
set(PLATFORM_LINKLIBS "-lshell32 -lshfolder -lgdi32 -lmsvcrt -lwinmm -lmingw32 -lm -lws2_32 -lz -lstdc++ -lole32 -luuid")
set(PLATFORM_CFLAGS "-pipe -funsigned-char -fno-strict-aliasing")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -D_LARGEFILE64_SOURCE")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -D_LARGEFILE64_SOURCE")
add_definitions(-D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -D_LARGEFILE64_SOURCE)
endif()
add_definitions(-DFREE_WINDOWS)
@@ -767,11 +814,8 @@ elseif(WIN32)
if(WITH_IMAGE_OPENEXR)
set(OPENEXR ${LIBDIR}/gcc/openexr)
set(OPENEXR_INCLUDE_DIRS ${OPENEXR}/include/OpenEXR)
set(OPENEXR_LIBRARIES Half IlmImf Imath IlmThread)
set(OPENEXR_LIBRARIES Half IlmImf Imath IlmThread Iex)
set(OPENEXR_LIBPATH ${OPENEXR}/lib)
# TODO, gives linking errors, force off
set(WITH_IMAGE_OPENEXR OFF)
endif()
if(WITH_IMAGE_TIFF)
@@ -792,12 +836,14 @@ elseif(WIN32)
endif()
if(WITH_PYTHON)
set(PYTHON ${LIBDIR}/python)
set(PYTHON_VERSION 3.2)
set(PYTHON_INCLUDE_DIRS "${PYTHON}/include/python${PYTHON_VERSION}")
# set(PYTHON_BINARY python) # not used yet
set(PYTHON_LIBRARIES ${PYTHON}/lib/python32mw.lib)
set(PYTHON_LIBPATH ${PYTHON}/lib)
# normally cached but not since we include them with blender
set(PYTHON_VERSION 3.2) # CACHE STRING)
set(PYTHON_INCLUDE_DIR "${LIBDIR}/python/include/python${PYTHON_VERSION}") # CACHE PATH)
set(PYTHON_LIBRARY "${LIBDIR}/python/lib/python32mw.lib") # CACHE FILEPATH)
# uncached vars
set(PYTHON_INCLUDE_DIRS "${PYTHON_INCLUDE_DIR}")
set(PYTHON_LIBRARIES "${PYTHON_LIBRARY}")
endif()
set(PLATFORM_LINKFLAGS "--stack,2097152")
@@ -848,27 +894,33 @@ elseif(APPLE)
set(SNDFILE_LIBPATH ${SNDFILE}/lib ${FFMPEG}/lib) # TODO, deprecate
endif()
set(PYTHON_VERSION 3.2)
if(PYTHON_VERSION MATCHES 3.2)
# we use precompiled libraries for py 3.2 and up by default
set(PYTHON ${LIBDIR}/python)
set(PYTHON_INCLUDE_DIRS "${PYTHON}/include/python${PYTHON_VERSION}")
# set(PYTHON_BINARY "${PYTHON}/bin/python${PYTHON_VERSION}") # not used yet
set(PYTHON_LIBRARIES python${PYTHON_VERSION})
set(PYTHON_LIBPATH "${PYTHON}/lib/python${PYTHON_VERSION}")
# set(PYTHON_LINKFLAGS "-u _PyMac_Error") # won't build with this enabled
else()
# otherwise, use custom system framework
set(PYTHON /System/Library/Frameworks/Python.framework/Versions/)
if(WITH_PYTHON)
set(PYTHON_VERSION 3.2)
set(PYTHON_INCLUDE_DIRS "${PYTHON}${PYTHON_VERSION}/include/python${PYTHON_VERSION}")
# set(PYTHON_BINARY ${PYTHON}${PYTHON_VERSION}/bin/python${PYTHON_VERSION}) # not used yet
set(PYTHON_LIBRARIES "")
set(PYTHON_LIBPATH ${PYTHON}${PYTHON_VERSION}/lib/python${PYTHON_VERSION}/config)
set(PYTHON_LINKFLAGS "-u _PyMac_Error -framework System -framework Python")
if(PYTHON_VERSION MATCHES 3.2)
# we use precompiled libraries for py 3.2 and up by default
# normally cached but not since we include them with blender
set(PYTHON_INCLUDE_DIR "${LIBDIR}/python/include/python${PYTHON_VERSION}")
# set(PYTHON_BINARY "${LIBDIR}/python/bin/python${PYTHON_VERSION}") # not used yet
set(PYTHON_LIBRARY python${PYTHON_VERSION})
set(PYTHON_LIBPATH "${LIBDIR}/python/lib/python${PYTHON_VERSION}")
# set(PYTHON_LINKFLAGS "-u _PyMac_Error") # won't build with this enabled
else()
# otherwise, use custom system framework
# *not used but maintained incase some dev wants to*
set(PYTHON "/System/Library/Frameworks/Python.framework/Versions/" CACHE PATH)
set(PYTHON_INCLUDE_DIR "${PYTHON}${PYTHON_VERSION}/include/python${PYTHON_VERSION}" CACHE PATH)
# set(PYTHON_BINARY ${PYTHON}${PYTHON_VERSION}/bin/python${PYTHON_VERSION}) # not used yet
set(PYTHON_LIBRARY "" CACHE FILEPATH)
set(PYTHON_LIBPATH "${PYTHON}${PYTHON_VERSION}/lib/python${PYTHON_VERSION}/config" CACHE PATH)
set(PYTHON_LINKFLAGS "-u _PyMac_Error -framework System -framework Python" CACHE STRING)
unset(PYTHON)
endif()
# uncached vars
set(PYTHON_INCLUDE_DIRS "${PYTHON_INCLUDE_DIR}")
set(PYTHON_LIBRARIES "${PYTHON_LIBRARY}")
endif()
if(WITH_INTERNATIONAL)
@@ -919,7 +971,7 @@ elseif(APPLE)
set(SAMPLERATE_LIBPATH ${SAMPLERATE}/lib)
endif()
set(LLIBS stdc++ SystemStubs)
set(PLATFORM_LINKLIBS stdc++ SystemStubs)
if(WITH_COCOA)
set(PLATFORM_CFLAGS "-pipe -funsigned-char -DGHOST_COCOA")
@@ -996,7 +1048,7 @@ endif()
# Common.
if(APPLE OR WIN32)
if(NOT IS_DIRECTORY "${LIBDIR}")
if(NOT EXISTS "${LIBDIR}/")
message(FATAL_ERROR "Apple and Windows require pre-compiled libs at: '${LIBDIR}'")
endif()
endif()
@@ -1143,6 +1195,18 @@ elseif(CMAKE_C_COMPILER_ID MATCHES "Intel")
endif()
# MSVC2010 fails to links C++ libs right
if(MSVC10)
if(WITH_IMAGE_OPENEXR)
message(WARNING "MSVC 2010 does not support OpenEXR, disabling WITH_IMAGE_OPENEXR. To enable support use Use MSVC 2008")
set(WITH_IMAGE_OPENEXR OFF)
endif()
if(WITH_OPENCOLLADA)
message(WARNING "MSVC 2010 does not support OpenCollada, disabling WITH_OPENCOLLADA. To enable support use Use MSVC 2008")
set(WITH_OPENCOLLADA OFF)
endif()
endif()
if(CMAKE_CXX_COMPILER_ID MATCHES "Clang")
if(WITH_IK_ITASC OR WITH_MOD_FLUID)
message(WARNING "Using Clang as CXX compiler: disabling WITH_IK_ITASC and WITH_MOD_FLUID, these features will be missing.")
@@ -1151,6 +1215,20 @@ if(CMAKE_CXX_COMPILER_ID MATCHES "Clang")
endif()
endif()
# ensure python header is found since detection can fail, this could happen
# with _any_ library but since we used a fixed python version this tends to
# be most problematic.
if(WITH_PYTHON)
if(NOT EXISTS "${PYTHON_INCLUDE_DIR}/Python.h")
message(FATAL_ERROR "Missing: \"${PYTHON_INCLUDE_DIR}/Python.h\",\n"
"Set the cache entry 'PYTHON_INCLUDE_DIR' to point "
"to a valid python include path. Containing "
"Python.h for python version \"${PYTHON_VERSION}\"")
endif()
endif()
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${PLATFORM_CFLAGS} ${C_WARNINGS}")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${PLATFORM_CFLAGS} ${CXX_WARNINGS}")
@@ -1179,7 +1257,9 @@ add_subdirectory(extern)
#-----------------------------------------------------------------------------
# Blender Application
add_subdirectory(source/creator)
if(WITH_BLENDER)
add_subdirectory(source/creator)
endif()
#-----------------------------------------------------------------------------

View File

@@ -73,9 +73,10 @@ all:
@echo
@echo Building Blender ...
make -C $(BUILD_DIR) -s -j $(NPROCS) install
$(MAKE) -C $(BUILD_DIR) -s -j $(NPROCS) install
@echo
@echo run blender from "$(BUILD_DIR)/bin/blender"
@echo edit build configuration with: "$(BUILD_DIR)/CMakeCache.txt" run make again to rebuild.
@echo blender installed, run from: "$(BUILD_DIR)/bin/blender"
@echo
debug: all
@@ -98,15 +99,19 @@ test:
# run pep8 check check on scripts we distribute.
test_pep8:
python source/tests/pep8.py > test_pep8.log 2>&1
python3 source/tests/pep8.py > test_pep8.log 2>&1
@echo "written: test_pep8.log"
# run some checks on our cmakefiles.
test_cmake:
python build_files/cmake/cmake_consistency_check.py > test_cmake_consistency.log 2>&1
python3 build_files/cmake/cmake_consistency_check.py > test_cmake_consistency.log 2>&1
@echo "written: test_cmake_consistency.log"
# run deprecation tests, see if we have anything to remove.
test_deprecated:
python3 source/tests/check_deprecated.py
clean:
make -C $(BUILD_DIR) clean
$(MAKE) -C $(BUILD_DIR) clean
.PHONY: all

View File

@@ -361,6 +361,23 @@ if not quickie and do_clean:
print B.bc.HEADER+'Already Clean, nothing to do.'+B.bc.ENDC
Exit()
# ensure python header is found since detection can fail, this could happen
# with _any_ library but since we used a fixed python version this tends to
# be most problematic.
if env['WITH_BF_PYTHON']:
py_h = os.path.join(Dir(env.subst('${BF_PYTHON_INC}')).abspath, "Python.h")
if not os.path.exists(py_h):
print("\nMissing: \"" + env.subst('${BF_PYTHON_INC}') + os.sep + "Python.h\",\n"
" Set 'BF_PYTHON_INC' to point "
"to a valid python include path.\n Containing "
"Python.h for python version \"" + env.subst('${BF_PYTHON_VERSION}') + "\"")
Exit()
del py_h
if not os.path.isdir ( B.root_build_dir):
os.makedirs ( B.root_build_dir )
os.makedirs ( B.root_build_dir + 'source' )

View File

@@ -26,7 +26,7 @@
from cmake_consistency_check_config import IGNORE, UTF8_CHECK, SOURCE_DIR
import os
from os.path import join, dirname, normpath, abspath, splitext
from os.path import join, dirname, normpath, splitext
print("Scanning:", SOURCE_DIR)
@@ -35,6 +35,21 @@ global_c = set()
global_refs = {}
def replace_line(f, i, text, keep_indent=True):
file_handle = open(f, 'r')
data = file_handle.readlines()
file_handle.close()
l = data[i]
ws = l[:len(l) - len(l.lstrip())]
data[i] = "%s%s\n" % (ws, text)
file_handle = open(f, 'w')
file_handle.writelines(data)
file_handle.close()
def source_list(path, filename_check=None):
for dirpath, dirnames, filenames in os.walk(path):
@@ -77,7 +92,20 @@ def cmake_get_src(f):
found = False
i = 0
# print(f)
def is_definition(l, f, i, name):
if ('set(%s' % name) in l or ('set(' in l and l.endswith(name)):
if len(l.split()) > 1:
raise Exception("strict formatting not kept 'set(%s*' %s:%d" % (name, f, i))
return True
if ("list(APPEND %s" % name) in l or ('list(APPEND ' in l and l.endswith(name)):
if l.endswith(")"):
raise Exception("strict formatting not kept 'list(APPEND %s...)' on 1 line %s:%d" % (name, f, i))
return True
while it is not None:
context_name = ""
while it is not None:
i += 1
try:
@@ -87,16 +115,13 @@ def cmake_get_src(f):
break
l = l.strip()
if not l.startswith("#"):
if 'set(SRC' in l or ('set(' in l and l.endswith("SRC")):
if len(l.split()) > 1:
raise Exception("strict formatting not kept 'set(SRC*' %s:%d" % (f, i))
found = True
found = is_definition(l, f, i, "SRC")
if found:
context_name = "SRC"
break
if "list(APPEND SRC" in l or ('list(APPEND ' in l and l.endswith("SRC")):
if l.endswith(")"):
raise Exception("strict formatting not kept 'list(APPEND SRC...)' on 1 line %s:%d" % (f, i))
found = True
found = is_definition(l, f, i, "INC")
if found:
context_name = "INC"
break
if found:
@@ -125,30 +150,45 @@ def cmake_get_src(f):
if not l:
pass
elif l.startswith("$"):
# assume if it ends with SRC we know about it
if not l.split("}")[0].endswith("SRC"):
print("Can't use var '%s' %s:%d" % (l, f, i))
if context_name == "SRC":
# assume if it ends with context_name we know about it
if not l.split("}")[0].endswith(context_name):
print("Can't use var '%s' %s:%d" % (l, f, i))
elif len(l.split()) > 1:
raise Exception("Multi-line define '%s' %s:%d" % (l, f, i))
else:
new_file = normpath(join(cmake_base, l))
if is_c_header(new_file):
sources_h.append(new_file)
global_refs.setdefault(new_file, []).append((f, i))
elif is_c(new_file):
sources_c.append(new_file)
global_refs.setdefault(new_file, []).append((f, i))
elif l in ("PARENT_SCOPE", ):
# cmake var, ignore
pass
elif new_file.endswith(".list"):
pass
elif new_file.endswith(".def"):
pass
else:
raise Exception("unknown file type - not c or h %s -> %s" % (f, new_file))
if context_name == "SRC":
if is_c_header(new_file):
sources_h.append(new_file)
global_refs.setdefault(new_file, []).append((f, i))
elif is_c(new_file):
sources_c.append(new_file)
global_refs.setdefault(new_file, []).append((f, i))
elif l in ("PARENT_SCOPE", ):
# cmake var, ignore
pass
elif new_file.endswith(".list"):
pass
elif new_file.endswith(".def"):
pass
else:
raise Exception("unknown file type - not c or h %s -> %s" % (f, new_file))
elif context_name == "INC":
if os.path.isdir(new_file):
new_path_rel = os.path.relpath(new_file, cmake_base)
if new_path_rel != l:
print("overly relative path:\n %s:%d\n %s\n %s" % (f, i, l, new_path_rel))
## Save time. just replace the line
# replace_line(f, i - 1, new_path_rel)
else:
raise Exception("non existant include %s:%d -> %s" % (f, i, new_file))
# print(new_file)
global_h.update(set(sources_h))
@@ -166,6 +206,10 @@ def cmake_get_src(f):
if ff not in sources_c:
print(" missing: " + ff)
'''
# reset
sources_h[:] = []
sources_c[:] = []
filen.close()
@@ -183,7 +227,6 @@ def is_ignore(f):
# First do stupid check, do these files exist?
print("\nChecking for missing references:")
import sys
is_err = False
errs = []
for f in (global_h | global_c):

View File

@@ -39,6 +39,21 @@ macro(file_list_suffix
endmacro()
macro(target_link_libraries_optimized TARGET LIBS)
foreach(_LIB ${LIBS})
target_link_libraries(${TARGET} optimized "${_LIB}")
endforeach()
unset(_LIB)
endmacro()
macro(target_link_libraries_debug TARGET LIBS)
foreach(_LIB ${LIBS})
target_link_libraries(${TARGET} debug "${_LIB}")
endforeach()
unset(_LIB)
endmacro()
# Nicer makefiles with -I/1/foo/ instead of -I/1/2/3/../../foo/
# use it instead of include_directories()
macro(blender_include_dirs
@@ -186,7 +201,9 @@ endmacro()
macro(setup_liblinks
target)
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${PLATFORM_LINKFLAGS} ")
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${PLATFORM_LINKFLAGS}")
set(CMAKE_EXE_LINKER_FLAGS_DEBUG "${CMAKE_EXE_LINKER_FLAGS_DEBUG} ${PLATFORM_LINKFLAGS_DEBUG}")
target_link_libraries(${target}
${OPENGL_gl_LIBRARY}
@@ -194,7 +211,7 @@ macro(setup_liblinks
${JPEG_LIBRARIES}
${PNG_LIBRARIES}
${ZLIB_LIBRARIES}
${LLIBS})
${PLATFORM_LINKLIBS})
# since we are using the local libs for python when compiling msvc projects, we need to add _d when compiling debug versions
if(WITH_PYTHON) # AND NOT WITH_PYTHON_MODULE # WIN32 needs
@@ -202,9 +219,8 @@ macro(setup_liblinks
if(WIN32 AND NOT UNIX)
file_list_suffix(PYTHON_LIBRARIES_DEBUG "${PYTHON_LIBRARIES}" "_d")
target_link_libraries(${target}
debug ${PYTHON_LIBRARIES_DEBUG}
optimized ${PYTHON_LIBRARIES})
target_link_libraries_debug(${target} "${PYTHON_LIBRARIES_DEBUG}")
target_link_libraries_optimized(${target} "${PYTHON_LIBRARIES}")
unset(PYTHON_LIBRARIES_DEBUG)
else()
target_link_libraries(${target} ${PYTHON_LIBRARIES})
@@ -257,9 +273,8 @@ macro(setup_liblinks
if(WITH_IMAGE_OPENEXR)
if(WIN32 AND NOT UNIX)
file_list_suffix(OPENEXR_LIBRARIES_DEBUG "${OPENEXR_LIBRARIES}" "_d")
target_link_libraries(${target}
debug ${OPENEXR_LIBRARIES_DEBUG}
optimized ${OPENEXR_LIBRARIES})
target_link_libraries_debug(${target} "${OPENEXR_LIBRARIES_DEBUG}")
target_link_libraries_optimized(${target} "${OPENEXR_LIBRARIES}")
unset(OPENEXR_LIBRARIES_DEBUG)
else()
target_link_libraries(${target} ${OPENEXR_LIBRARIES})
@@ -274,22 +289,19 @@ macro(setup_liblinks
if(WITH_OPENCOLLADA)
if(WIN32 AND NOT UNIX)
file_list_suffix(OPENCOLLADA_LIBRARIES_DEBUG "${OPENCOLLADA_LIBRARIES}" "_d")
target_link_libraries(${target}
debug ${OPENCOLLADA_LIBRARIES_DEBUG}
optimized ${OPENCOLLADA_LIBRARIES})
target_link_libraries_debug(${target} "${OPENCOLLADA_LIBRARIES_DEBUG}")
target_link_libraries_optimized(${target} "${OPENCOLLADA_LIBRARIES}")
unset(OPENCOLLADA_LIBRARIES_DEBUG)
file_list_suffix(PCRE_LIB_DEBUG "${PCRE_LIB}" "_d")
target_link_libraries(${target}
debug ${PCRE_LIB_DEBUG}
optimized ${PCRE_LIB})
target_link_libraries_debug(${target} "${PCRE_LIB_DEBUG}")
target_link_libraries_optimized(${target} "${PCRE_LIB}")
unset(PCRE_LIB_DEBUG)
if(EXPAT_LIB)
file_list_suffix(EXPAT_LIB_DEBUG "${EXPAT_LIB}" "_d")
target_link_libraries(${target}
debug ${EXPAT_LIB_DEBUG}
optimized ${EXPAT_LIB})
target_link_libraries_debug(${target} "${EXPAT_LIB_DEBUG}")
target_link_libraries_optimized(${target} "${EXPAT_LIB}")
unset(EXPAT_LIB_DEBUG)
endif()
else()

View File

@@ -76,11 +76,6 @@ BF_GETTEXT_INC = '${BF_GETTEXT}/include'
BF_GETTEXT_LIB = 'gettextpo intl'
BF_GETTEXT_LIBPATH = '${BF_GETTEXT}/lib'
WITH_BF_FTGL = 'false'
BF_FTGL = '#extern/bFTGL'
BF_FTGL_INC = '${BF_FTGL}/include'
BF_FTGL_LIB = 'extern_ftgl'
WITH_BF_GAMEENGINE='false'
WITH_BF_BULLET = 'true'

View File

@@ -170,7 +170,7 @@ BGE_CXXFLAGS = ['/O2', '/EHsc', '/GR', '/fp:fast', '/arch:SSE']
BF_DEBUG_CCFLAGS = ['/Zi', '/FR${TARGET}.sbr']
CPPFLAGS = ['-DWIN32','-D_CONSOLE', '-D_LIB', '-DFTGL_LIBRARY_STATIC', '-D_CRT_SECURE_NO_DEPRECATE']
CPPFLAGS = ['-DWIN32','-D_CONSOLE', '-D_LIB', '-D_CRT_SECURE_NO_DEPRECATE']
REL_CFLAGS = ['-O2', '-DNDEBUG']
REL_CCFLAGS = ['-O2', '-DNDEBUG']
REL_CXXFLAGS = ['-O2', '-DNDEBUG']
@@ -181,7 +181,7 @@ CXX_WARN = []
LLIBS = ['ws2_32', 'vfw32', 'winmm', 'kernel32', 'user32', 'gdi32', 'comdlg32', 'advapi32', 'shfolder', 'shell32', 'ole32', 'oleaut32', 'uuid']
PLATFORM_LINKFLAGS = ['/SUBSYSTEM:CONSOLE','/MACHINE:IX86','/STACK:2097152','/INCREMENTAL:NO', '/LARGEADDRESSAWARE', '/NODEFAULTLIB:"msvcrt.lib"', '/NODEFAULTLIB:"msvcmrt.lib"', '/NODEFAULTLIB:"msvcurt.lib"', '/NODEFAULTLIB:"msvcrtd.lib"']
PLATFORM_LINKFLAGS = ['/SUBSYSTEM:CONSOLE','/MACHINE:IX86','/STACK:2097152','/INCREMENTAL:NO', '/LARGEADDRESSAWARE', '/NODEFAULTLIB:msvcrt.lib', '/NODEFAULTLIB:msvcmrt.lib', '/NODEFAULTLIB:msvcurt.lib', '/NODEFAULTLIB:msvcrtd.lib']
# # Todo
# BF_PROFILE_CCFLAGS = ['-pg', '-g ']

View File

@@ -50,6 +50,8 @@ BF_SDL_INC = '${BF_SDL}/include'
BF_SDL_LIB = 'SDL.lib'
BF_SDL_LIBPATH = '${BF_SDL}/lib'
WITH_BF_JACK = False
BF_PTHREADS = LIBDIR + '/pthreads'
BF_PTHREADS_INC = '${BF_PTHREADS}/include'
BF_PTHREADS_LIB = 'pthreadVC2'
@@ -172,7 +174,7 @@ BGE_CXXFLAGS = ['/O2', '/EHsc', '/GR', '/fp:fast']
BF_DEBUG_CCFLAGS = ['/Zi', '/FR${TARGET}.sbr', '/Od']
CPPFLAGS = ['-DWIN32', '-D_CONSOLE', '-D_LIB', '-DFTGL_LIBRARY_STATIC', '-D_CRT_SECURE_NO_DEPRECATE']
CPPFLAGS = ['-DWIN32', '-D_CONSOLE', '-D_LIB', '-D_CRT_SECURE_NO_DEPRECATE']
REL_CFLAGS = ['-O2', '-DNDEBUG']
REL_CCFLAGS = ['-O2', '-DNDEBUG']
REL_CXXFLAGS = ['-O2', '-DNDEBUG']
@@ -188,7 +190,7 @@ if BF_DEBUG:
else:
BF_NUMJOBS=6
PLATFORM_LINKFLAGS = ['/SUBSYSTEM:CONSOLE','/MACHINE:X64','/STACK:2097152','/OPT:NOREF','/INCREMENTAL:NO', '/NODEFAULTLIB:"msvcrt.lib"', '/NODEFAULTLIB:"msvcmrt.lib"', '/NODEFAULTLIB:"msvcurt.lib"', '/NODEFAULTLIB:"msvcrtd.lib"']
PLATFORM_LINKFLAGS = ['/SUBSYSTEM:CONSOLE','/MACHINE:X64','/STACK:2097152','/OPT:NOREF','/INCREMENTAL:NO', '/NODEFAULTLIB:msvcrt.lib', '/NODEFAULTLIB:msvcmrt.lib', '/NODEFAULTLIB:msvcurt.lib', '/NODEFAULTLIB:msvcrtd.lib']
BF_BUILDDIR = '..\\build\\blender25-win64-vc'
BF_INSTALLDIR='..\\install\\blender25-win64-vc'

View File

@@ -320,11 +320,7 @@ def creator(env):
defs.append('WITH_PYTHON')
if env['BF_DEBUG']:
defs.append('_DEBUG')
if env['BF_BUILDINFO']:
defs.append('BUILD_DATE')
defs.append('NAN_BUILDINFO')
if env['OURPLATFORM'] in ('win32-vc', 'win32-mingw', 'linuxcross', 'win64-vc'):
incs.append(env['BF_PTHREADS_INC'])
@@ -565,13 +561,16 @@ def AppIt(target=None, source=None, env=None):
cmd = 'mkdir %s/%s.app/Contents/MacOS/%s/python/'%(installdir,binary, VERSION)
commands.getoutput(cmd)
cmd = 'unzip -q %s/release/%s -d %s/%s.app/Contents/MacOS/%s/python/'%(libdir,python_zip,installdir,binary,VERSION)
commands.getoutput(cmd)
cmd = 'cp -R %s/release/scripts %s/%s.app/Contents/MacOS/%s/'%(bldroot,installdir,binary,VERSION)
commands.getoutput(cmd)
cmd = 'cp -R %s/release/ui %s/%s.app/Contents/MacOS/%s/'%(bldroot,installdir,binary,VERSION)
commands.getoutput(cmd)
cmd = 'cp -R %s/release/io %s/%s.app/Contents/MacOS/%s/'%(bldroot,installdir,binary,VERSION)
commands.getoutput(cmd)
if binary == 'blender':#not copy everything for blenderplayer
cmd = 'cp -R %s/release/scripts %s/%s.app/Contents/MacOS/%s/'%(bldroot,installdir,binary,VERSION)
commands.getoutput(cmd)
cmd = 'cp -R %s/release/ui %s/%s.app/Contents/MacOS/%s/'%(bldroot,installdir,binary,VERSION)
commands.getoutput(cmd)
cmd = 'cp -R %s/release/io %s/%s.app/Contents/MacOS/%s/'%(bldroot,installdir,binary,VERSION)
commands.getoutput(cmd)
cmd = 'chmod +x %s/%s.app/Contents/MacOS/%s'%(installdir,binary, binary)
commands.getoutput(cmd)
cmd = 'find %s/%s.app -name .svn -prune -exec rm -rf {} \;'%(installdir, binary)

View File

@@ -121,6 +121,7 @@ def validate_arguments(args, bc):
'BF_OPENMP_INC',
'BF_OPENMP_LIBPATH',
'WITH_GHOST_COCOA',
'WITH_GHOST_SDL',
'USE_QTKIT',
'BF_FANCY', 'BF_QUIET', 'BF_LINE_OVERWRITE',
'BF_X264_CONFIG',
@@ -385,6 +386,7 @@ def read_opts(env, cfg, args):
('BF_OPENMP_INC', 'Path to OpenMP includes (used when cross-compiling with older versions of WinGW)', ''),
('BF_OPENMP_LIBPATH', 'Path to OpenMP libraries (used when cross-compiling with older versions of WinGW)', ''),
(BoolVariable('WITH_GHOST_COCOA', 'Use Cocoa-framework if true', False)),
(BoolVariable('WITH_GHOST_SDL', 'Enable building blender against SDL for windowing rather then the native APIs', False)),
(BoolVariable('USE_QTKIT', 'Use QTKIT if true', False)),
(BoolVariable('WITH_BF_QUICKTIME', 'Use QuickTime if true', False)),

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,21 @@
"""
Basic Sound Playback
++++++++++++++++++++
This script shows how to use the classes: :class:`Device`, :class:`Factory` and
:class:`Handle`.
"""
import aud
device = aud.device()
# load sound file (it can be a video file with audio)
factory = aud.Factory('music.ogg')
# play the audio, this return a handle to control play/pause
handle = device.play(sound)
# if the audio is not too big and will be used often you can buffer it
factory_buffered = aud.Factory.buffer(sound)
handle_buffered = device.play(buffered)
# stop the sounds (otherwise they play until their ends)
handle.stop()
handle_buffered.stop()

View File

@@ -0,0 +1,37 @@
"""
Basic Physics Constraint
++++++++++++++++++++++
Example of how to create a hinge Physics Constraint between two objects.
"""
from bge import logic
from bge import constraints
# get object list
objects = logic.getCurrentScene().objects
# get object named Object1 and Object 2
object_1 = objects["Object1"]
object_2 = objects["Object2"]
# want to use Edge constraint type
constraint_type = 2
# get Object1 and Object2 physics IDs
physics_id_1 = object_1.getPhysicsId()
physics_id_2 = object_2.getPhysicsId()
# Use bottom right edge of Object1 for hinge position
edge_position_x = 1.0
edge_position_y = 0.0
edge_position_z = -1.0
# use Object1 y axis for angle to point hinge
edge_angle_x = 0.0
edge_angle_y = 1.0
edge_angle_z = 0.0
# create an edge constraint
constraints.createConstraint( physics_id_1, physics_id_2,
constraint_type,
edge_position_x, edge_position_y, edge_position_z,
edge_angle_x, edge_angle_y, edge_angle_z )

View File

@@ -0,0 +1,37 @@
"""
Texture replacement
++++++++++++++++++++++
Example of how to replace a texture in game with an external image.
createTexture() and removeTexture() are to be called from a module Python
Controller.
"""
from bge import logic
from bge import texture
def createTexture(cont):
"""Create a new Dynamic Texture"""
object = cont.owner
# get the reference pointer (ID) of the internal texture
ID = texture.materialID(obj, 'IMoriginal.png')
# create a texture object
object_texture = texture.Texture(object, ID)
# create a new source with an external image
url = logic.expandPath("//newtexture.jpg")
new_source = texture.ImageFFmpeg(url)
# the texture has to be stored in a permanent Python object
logic.texture = object_texture
# update/replace the texture
logic.texture.source = new_source
logic.texture.refresh(False)
def removeTexture(cont):
"""Delete the Dynamic Texture, reversing back the final to its original state."""
try:
del logic.texture
except:
pass

View File

@@ -0,0 +1,32 @@
"""
Basic Video Playback
++++++++++++++++++++++
Example of how to replace a texture in game with a video. It needs to run everyframe
"""
import bge
from bge import texture
from bge import logic
cont = logic.getCurrentController()
obj = cont.owner
# the creation of the texture must be done once: save the
# texture object in an attribute of bge.logic module makes it persistent
if not hasattr(logic, 'video'):
# identify a static texture by name
matID = texture.materialID(obj, 'IMvideo.png')
# create a dynamic texture that will replace the static texture
logic.video = texture.Texture(obj, matID)
# define a source of image for the texture, here a movie
movie = logic.expandPath('//trailer_400p.ogg')
logic.video.source = texture.VideoFFmpeg(movie)
logic.video.source.scale = True
# quick off the movie, but it wont play in the background
logic.video.source.play()
# you need to call this function every frame to ensure update of the texture.
logic.video.refresh(True)

View File

@@ -0,0 +1,41 @@
"""
Hello World Text Example
++++++++++++++++++++++++
Blender Game Engine example of using the blf module. For this module to work we
need to use the OpenGL wrapper :class:`~bgl` as well.
"""
# import game engine modules
from bge import render
from bge import logic
# import stand alone modules
import bgl
import blf
def init():
"""init function - runs once"""
# create a new font object, use external ttf file
font_path = logic.expandPath('//Zeyada.ttf')
# store the font indice - to use later
logic.font_id = blf.load(font_path)
# set the font drawing routine to run every frame
scene = logic.getCurrentScene()
scene.post_draw=[write]
def write():
"""write on screen"""
width = render.getWindowWidth()
height = render.getWindowHeight()
# OpenGL setup
bgl.glMatrixMode(bgl.GL_PROJECTION)
bgl.glLoadIdentity()
bgl.gluOrtho2D(0, width, 0, height)
bgl.glMatrixMode(bgl.GL_MODELVIEW)
bgl.glLoadIdentity()
# BLF drawing routine
font_id = logic.font_id
blf.position(font_id, (width*0.2), (height*0.3), 0)
blf.size(font_id, 50, 72)
blf.draw(font_id, "Hello World")

View File

@@ -61,10 +61,10 @@ bpy.utils.register_class(CustomRenderEngine)
# Otherwise most of the UI will be empty when the engine is selected.
# In this example, we need to see the main render image button and
# the material preview panel.
import properties_render
from bl_ui import properties_render
properties_render.RENDER_PT_render.COMPAT_ENGINES.add('custom_renderer')
del properties_render
import properties_material
from bl_ui import properties_material
properties_material.MATERIAL_PT_preview.COMPAT_ENGINES.add('custom_renderer')
del properties_material

View File

@@ -0,0 +1,199 @@
Game Engine bge.constraints Module
==================================
.. note::
This documentation is still very weak, and needs some help!
.. function:: createConstraint([obj1, [obj2, [restLength, [restitution, [damping]]]]])
Creates a constraint.
:arg obj1: first object on Constraint
:type obj1: :class:'bge.types.KX_GameObject' #I think, there is no error when I use one
:arg obj2: second object on Constraint
:type obj2: :class:'bge.types.KX_GameObject' #too
:arg restLength: #to be filled
:type restLength: float
:arg restitution: #to be filled
:type restitution: float
:arg damping: #to be filled
:type damping: float
.. attribute:: error
Simbolic constant string that indicates error.
.. function:: exportBulletFile(filename)
export a .bullet file
:arg filename: File name
:type filename: string
.. function:: getAppliedImpulse(constraintId)
:arg constraintId: The id of the constraint.
:type constraintId: int
:return: the most recent applied impulse.
:rtype: float
.. function:: getVehicleConstraint(constraintId)
:arg constraintId: The id of the vehicle constraint.
:type constraintId: int
:return: a vehicle constraint object.
:rtype: :class:'KX_VehicleWrapper'
.. function:: removeConstraint(constraintId)
Removes a constraint.
:arg constraintId: The id of the constraint to be removed.
:type constraintId: int
.. function:: setCcdMode(ccdMode)
..note::
Very experimental, not recommended
Sets the CCD mode in the Physics Environment.
:arg ccdMode: The new CCD mode.
:type ccdMode: int
.. function:: setContactBreakingTreshold(breakingTreshold)
.. note::
Reasonable default is 0.02 (if units are meters)
Sets the contact breaking treshold in the Physics Environment.
:arg breakingTreshold: The new contact breaking treshold.
:type breakingTreshold: float
.. function:: setDeactivationAngularTreshold(angularTreshold)
Sets the deactivation angular treshold.
:arg angularTreshold: New deactivation angular treshold.
:type angularTreshold: float
.. function:: setDeactivationLinearTreshold(linearTreshold)
Sets the deactivation linear treshold.
:arg linearTreshold: New deactivation linear treshold.
:type linearTreshold: float
.. function:: setDeactivationTime(time)
Sets the time after which a resting rigidbody gets deactived.
:arg time: The deactivation time.
:type time: float
.. function:: setDebugMode(mode)
Sets the debug mode.
Debug modes:
- No debug: 0
- Draw wireframe: 1
- Draw Aabb: 2 #What's Aabb?
- Draw freatures text: 4
- Draw contact points: 8
- No deactivation: 16
- No help text: 32
- Draw text: 64
- Profile timings: 128
- Enable sat comparision: 256
- Disable Bullet LCP: 512
- Enable CCD: 1024
- Draw Constraints: #(1 << 11) = ?
- Draw Constraint Limits: #(1 << 12) = ?
- Fast Wireframe: #(1 << 13) = ?
:arg mode: The new debug mode.
:type mode: int
.. function:: setGravity(x, y, z)
Sets the gravity force.
:arg x: Gravity X force.
:type x: float
:arg y: Gravity Y force.
:type y: float
:arg z: Gravity Z force.
:type z: float
.. function:: setLinearAirDamping(damping)
Not implemented.
.. function:: setNumIterations(numiter)
Sets the number of iterations for an iterative constraint solver.
:arg numiter: New number of iterations.
:type numiter: int
.. function:: setNumTimeSubSteps(numsubstep)
Sets the number of substeps for each physics proceed. Tradeoff quality for performance.
:arg numsubstep: New number of substeps.
:type numsubstep: int
.. function:: setSolverDamping(damping)
..note::
Very experimental, not recommended
Sets the solver damping.
:arg damping: New damping for the solver.
:type damping: float
.. function:: setSolverTau(tau)
.. note::
Very experimental, not recommended
Sets the solver tau.
:arg tau: New tau for the solver.
:type tau: float
.. function:: setSolverType(solverType)
.. note::
Very experimental, not recommended
Sets the solver type.
:arg solverType: The new type of the solver.
:type solverType: int
.. function:: setSorConstant(sor)
.. note::
Very experimental, not recommended
Sets the sor constant.
:arg sor: New sor value.
:type sor: float
.. function:: setUseEpa(epa)
Not implemented.

View File

@@ -1,5 +1,5 @@
Game Engine bge.events module
Game Engine bge.events Module
=============================
*****

View File

@@ -17,7 +17,7 @@ Module to access logic functions, imported automatically into the python control
# To get the game object this controller is on:
obj = cont.owner
:class:`~bge.types.KX_GameObject` and :class:`~bge.types.KX_Camera` or :class:`bge.types.~KX_LightObject` methods are available depending on the type of object
:class:`~bge.types.KX_GameObject` and :class:`~bge.types.KX_Camera` or :class:`~bge.types.KX_LightObject` methods are available depending on the type of object
.. code-block:: python

View File

@@ -0,0 +1,549 @@
Game Engine bge.texture Module
==============================
.. note::
This documentation is still very weak, and needs some help! Right now they are mostly a collection
of the docstrings found in the bge.texture source code + some random places filled with text.
*****
Intro
*****
The bge.texture module allows you to manipulate textures during the game.
Several sources for texture are possible: video files, image files, video capture, memory buffer, camera render or a mix of that.
The video and image files can be loaded from the internet using an URL instead of a file name.
In addition, you can apply filters on the images before sending them to the GPU, allowing video effect: blue screen, color band, gray, normal map.
bge.texture uses FFmpeg to load images and videos. All the formats and codecs that FFmpeg supports are supported by this module, including but not limited to::
* AVI
* Ogg
* Xvid
* Theora
* dv1394 camera
* video4linux capture card (this includes many webcams)
* videoForWindows capture card (this includes many webcams)
* JPG
The principle is simple: first you identify a texture on an existing object using
the :materialID: function, then you create a new texture with dynamic content
and swap the two textures in the GPU.
The GE is not aware of the substitution and continues to display the object as always,
except that you are now in control of the texture.
When the texture object is deleted, the new texture is deleted and the old texture restored.
.. module:: bge.texture
.. class:: VideoFFmpeg(file [, capture=-1, rate=25.0, width=0, height=0])
FFmpeg video source
.. attribute:: status
video status
.. attribute:: range
replay range
.. attribute:: repeat
repeat count, -1 for infinite repeat
:type: int
.. attribute:: framerate
frame rate
:type: float
.. attribute:: valid
Tells if an image is available
:type: bool
.. attribute:: image
image data
.. attribute:: size
image size
.. attribute:: scale
fast scale of image (near neighbour)
.. attribute:: flip
flip image vertically
.. attribute:: filter
pixel filter
.. attribute:: preseek
number of frames of preseek
:type: int
.. attribute:: deinterlace
deinterlace image
:type: bool
.. method:: play()
Play (restart) video
.. method:: pause()
pause video
.. method:: stop()
stop video (play will replay it from start)
.. method:: refresh()
Refresh video - get its status
.. class:: ImageFFmpeg(file)
FFmpeg image source
.. attribute:: status
video status
.. attribute:: valid
Tells if an image is available
:type: bool
.. attribute:: image
image data
.. attribute:: size
image size
.. attribute:: scale
fast scale of image (near neighbour)
.. attribute:: flip
flip image vertically
.. attribute:: filter
pixel filter
.. method:: refresh()
Refresh image, i.e. load it
.. method:: reload([newname])
Reload image, i.e. reopen it
.. class:: ImageBuff()
Image source from image buffer
.. attribute:: filter
pixel filter
.. attribute:: flip
flip image vertically
.. attribute:: image
image data
.. method:: load(imageBuffer, width, height)
Load image from buffer
.. method:: plot(imageBuffer, width, height, positionX, positionY)
update image buffer
.. attribute:: scale
fast scale of image (near neighbour)
.. attribute:: size
image size
.. attribute:: valid
bool to tell if an image is available
.. class:: ImageMirror(scene)
Image source from mirror
.. attribute:: alpha
use alpha in texture
.. attribute:: background
background color
.. attribute:: capsize
size of render area
.. attribute:: clip
clipping distance
.. attribute:: filter
pixel filter
.. attribute:: flip
flip image vertically
.. attribute:: image
image data
.. method:: refresh(imageMirror)
Refresh image - invalidate its current content
.. attribute:: scale
fast scale of image (near neighbour)
.. attribute:: size
image size
.. attribute:: valid
bool to tell if an image is available
.. attribute:: whole
use whole viewport to render
.. class:: ImageMix()
Image mixer
.. attribute:: filter
pixel filter
.. attribute:: flip
flip image vertically
.. method:: getSource(imageMix)
get image source
.. method:: getWeight(imageMix)
get image source weight
.. attribute:: image
image data
.. method:: refresh(imageMix)
Refresh image - invalidate its current content
.. attribute:: scale
fast scale of image (near neighbour)
.. method:: setSource(imageMix)
set image source
.. method:: setWeight(imageMix)
set image source weight
.. attribute:: valid
bool to tell if an image is available
.. class:: ImageRender(scene, camera)
Image source from render
.. attribute:: alpha
use alpha in texture
.. attribute:: background
background color
.. attribute:: capsize
size of render area
.. attribute:: filter
pixel filter
.. attribute:: flip
flip image vertically
.. attribute:: image
image data
.. method:: refresh(imageRender)
Refresh image - invalidate its current content
.. attribute:: scale
fast scale of image (near neighbour)
.. attribute:: size
image size
.. attribute:: valid
bool to tell if an image is available
.. attribute:: whole
use whole viewport to render
.. class:: ImageViewport()
Image source from viewport
.. attribute:: alpha
use alpha in texture
.. attribute:: capsize
size of viewport area being captured
.. attribute:: filter
pixel filter
.. attribute:: flip
flip image vertically
.. attribute:: image
image data
.. attribute:: position
upper left corner of captured area
.. method:: refresh(imageViewport)
Refresh image - invalidate its current content
.. attribute:: scale
fast scale of image (near neighbour)
.. attribute:: size
image size
.. attribute:: valid
bool to tell if an image is available
.. attribute:: whole
use whole viewport to capture
.. class:: Texture(gameObj)
Texture objects
.. attribute:: bindId
OpenGL Bind Name
.. method:: close(texture)
Close dynamic texture and restore original
.. attribute:: mipmap
mipmap texture
.. method:: refresh(texture)
Refresh texture from source
.. attribute:: source
source of texture
.. class:: FilterBGR24()
Source filter BGR24 objects
.. class:: FilterBlueScreen()
Filter for Blue Screen objects
.. attribute:: color
blue screen color
.. attribute:: limits
blue screen color limits
.. attribute:: previous
previous pixel filter
.. class:: FilterColor()
Filter for color calculations
.. attribute:: matrix
matrix [4][5] for color calculation
.. attribute:: previous
previous pixel filter
.. class:: FilterGray()
Filter for gray scale effect
.. attribute:: previous
previous pixel filter
.. class:: FilterLevel()
Filter for levels calculations
.. attribute:: levels
levels matrix [4] (min, max)
.. attribute:: previous
previous pixel filter
.. class:: FilterNormal()
Filter for Blue Screen objects
.. attribute:: colorIdx
index of color used to calculate normal (0 - red, 1 - green, 2 - blue)
.. attribute:: depth
depth of relief
.. attribute:: previous
previous pixel filter
.. class:: FilterRGB24()
Returns a new input filter object to be used with :class:`ImageBuff` object when the image passed
to the ImageBuff.load() function has the 3-bytes pixel format BGR.
.. class:: FilterRGBA32()
Source filter RGBA32 objects
.. function:: getLastError()
Last error that occurred in a bge.texture function.
:return: the description of the last error occurred in a bge.texture function.
:rtype: string
.. function:: imageToArray(image,mode)
Returns a :class:`~bgl.buffer` corresponding to the current image stored in a texture source object.
:arg image: Image source object.
:type image: object of type :class:`VideoFFmpeg`, :class:`ImageFFmpeg`, :class:`ImageBuff`, :class:`ImageMix`, :class:`ImageRender`, :class:`ImageMirror` or :class:`ImageViewport`
:arg mode: optional argument representing the pixel format.
You can use the characters R, G, B for the 3 color channels, A for the alpha channel,
0 to force a fixed 0 color channel and 1 to force a fixed 255 color channel.
Example: "BGR" will return 3 bytes per pixel with the Blue, Green and Red channels in that order.
"RGB1" will return 4 bytes per pixel with the Red, Green, Blue channels in that order and the alpha channel forced to 255.
The default mode is "RGBA".
:type mode: string
:rtype: :class:`~bgl.buffer`
:return: A object representing the image as one dimensional array of bytes of size (pixel_size*width*height),
line by line starting from the bottom of the image. The pixel size and format is determined by the mode
parameter.
.. function materialID(object,name)
Returns a numeric value that can be used in :class:`Texture` to create a dynamic texture.
The value corresponds to an internal material number that uses the texture identified
by name. name is a string representing a texture name with IM prefix if you want to
identify the texture directly. This method works for basic tex face and for material,
provided the material has a texture channel using that particular texture in first
position of the texture stack. name can also have MA prefix if you want to identify
the texture by material. In that case the material must have a texture channel in first
position.
If the object has no material that matches name, it generates a runtime error. Use try/except to catch the exception.
Ex: bge.texture.materialID(obj, 'IMvideo.png')
:arg object: the game object that uses the texture you want to make dynamic
:type object: game object
:arg name: name of the texture/material you want to make dynamic.
:type name: string
:rtype: integer
.. function setLogFile(filename)
Sets the name of a text file in which runtime error messages will be written, in addition to the printing
of the messages on the Python console. Only the runtime errors specific to the VideoTexture module
are written in that file, ordinary runtime time errors are not written.
:arg filename: name of error log file
:type filename: string
:rtype: integer

1889
doc/python_api/rst/bgl.rst Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -700,6 +700,23 @@ Renamed
2.57 to 2.58
============
bpy_extras
----------
Added
^^^^^
* :mod:`bpy_extras`
* :mod:`bpy_extras.view3d_utils`
Moved
^^^^^
* io_utils -> :mod:`bpy_extras.io_utils`
* image_utils -> :mod:`bpy_extras.image_utils`
* mesh_utils -> :mod:`bpy_extras.mesh_utils`
* object_utils -> :mod:`bpy_extras.object_utils`
bpy.types.RenderSettings
------------------------

View File

@@ -29,15 +29,15 @@ For HTML generation
./blender.bin --background --python doc/python_api/sphinx_doc_gen.py
This will generate python files in doc/python_api/sphinx-in/,
assuming that ./blender.bin is or links to the blender executable
This will generate python files in doc/python_api/sphinx-in/
providing ./blender.bin is or links to the blender executable
- Generate html docs by running...
cd doc/python_api
sphinx-build sphinx-in sphinx-out
assuming that you have sphinx 1.0.7 installed
This requires sphinx 1.0.7 to be installed.
For PDF generation
------------------
@@ -48,6 +48,15 @@ For PDF generation
make
'''
# Check we're running in blender
if __import__("sys").modules.get("bpy") is None:
print("\nError, this script must run from inside blender2.5")
print(script_help_msg)
import sys
sys.exit()
# Switch for quick testing
if 1:
# full build
@@ -58,7 +67,7 @@ if 1:
else:
# for testing so doc-builds dont take so long.
EXCLUDE_MODULES = (
# "bpy.context",
"bpy.context",
"bpy.app",
"bpy.path",
"bpy.data",
@@ -67,8 +76,8 @@ else:
"bpy.context",
"bpy.types", # supports filtering
"bpy.ops", # supports filtering
#"bpy_extras",
"bge",
"bpy_extras",
# "bge",
"aud",
"bgl",
"blf",
@@ -988,6 +997,7 @@ def rna2sphinx(BASEPATH):
fw("\n")
fw("* `Quickstart Intro <http://wiki.blender.org/index.php/Dev:2.5/Py/API/Intro>`_ if you are new to scripting in blender and want to get you're feet wet!\n")
fw("* `Blender/Python Overview <http://wiki.blender.org/index.php/Dev:2.5/Py/API/Overview>`_ for a more complete explanation of python integration in blender\n")
fw("\n")
fw("===================\n")
fw("Application Modules\n")
@@ -1029,8 +1039,8 @@ def rna2sphinx(BASEPATH):
fw(" mathutils.geometry.rst\n\n")
if "Freestyle" not in EXCLUDE_MODULES:
fw(" Freestyle.rst\n\n")
# XXX TODO
#fw(" bgl.rst\n\n")
if "bgl" not in EXCLUDE_MODULES:
fw(" bgl.rst\n\n")
if "blf" not in EXCLUDE_MODULES:
fw(" blf.rst\n\n")
if "aud" not in EXCLUDE_MODULES:
@@ -1049,7 +1059,9 @@ def rna2sphinx(BASEPATH):
fw(" bge.types.rst\n\n")
fw(" bge.logic.rst\n\n")
fw(" bge.render.rst\n\n")
fw(" bge.texture.rst\n\n")
fw(" bge.events.rst\n\n")
fw(" bge.constraints.rst\n\n")
# rna generated change log
fw("========\n")
@@ -1160,14 +1172,16 @@ def rna2sphinx(BASEPATH):
import mathutils.geometry as module
pymodule2sphinx(BASEPATH, "mathutils.geometry", module, "Geometry Utilities")
if "mathutils.geometry" not in EXCLUDE_MODULES:
if "blf" not in EXCLUDE_MODULES:
import blf as module
pymodule2sphinx(BASEPATH, "blf", module, "Font Drawing")
# XXX TODO
#import bgl as module
#pymodule2sphinx(BASEPATH, "bgl", module, "Blender OpenGl wrapper")
#del module
if "bgl" not in EXCLUDE_MODULES:
#import bgl as module
#pymodule2sphinx(BASEPATH, "bgl", module, "Blender OpenGl wrapper")
#del module
import shutil
shutil.copy2(os.path.join(BASEPATH, "..", "rst", "bgl.rst"), BASEPATH)
if "aud" not in EXCLUDE_MODULES:
import aud as module
@@ -1181,7 +1195,9 @@ def rna2sphinx(BASEPATH):
shutil.copy2(os.path.join(BASEPATH, "..", "rst", "bge.types.rst"), BASEPATH)
shutil.copy2(os.path.join(BASEPATH, "..", "rst", "bge.logic.rst"), BASEPATH)
shutil.copy2(os.path.join(BASEPATH, "..", "rst", "bge.render.rst"), BASEPATH)
shutil.copy2(os.path.join(BASEPATH, "..", "rst", "bge.texture.rst"), BASEPATH)
shutil.copy2(os.path.join(BASEPATH, "..", "rst", "bge.events.rst"), BASEPATH)
shutil.copy2(os.path.join(BASEPATH, "..", "rst", "bge.constraints.rst"), BASEPATH)
shutil.copy2(os.path.join(BASEPATH, "..", "rst", "change_log.rst"), BASEPATH)
@@ -1206,72 +1222,67 @@ def rna2sphinx(BASEPATH):
def main():
import bpy
if 'bpy' not in dir():
print("\nError, this script must run from inside blender2.5")
print(script_help_msg)
import shutil
script_dir = os.path.dirname(__file__)
path_in = os.path.join(script_dir, "sphinx-in")
path_out = os.path.join(script_dir, "sphinx-out")
path_examples = os.path.join(script_dir, "examples")
# only for partial updates
path_in_tmp = path_in + "-tmp"
if not os.path.exists(path_in):
os.mkdir(path_in)
for f in os.listdir(path_examples):
if f.endswith(".py"):
EXAMPLE_SET.add(os.path.splitext(f)[0])
# only for full updates
if _BPY_FULL_REBUILD:
shutil.rmtree(path_in, True)
shutil.rmtree(path_out, True)
else:
import shutil
# write here, then move
shutil.rmtree(path_in_tmp, True)
script_dir = os.path.dirname(__file__)
path_in = os.path.join(script_dir, "sphinx-in")
path_out = os.path.join(script_dir, "sphinx-out")
path_examples = os.path.join(script_dir, "examples")
# only for partial updates
path_in_tmp = path_in + "-tmp"
rna2sphinx(path_in_tmp)
if not os.path.exists(path_in):
os.mkdir(path_in)
if not _BPY_FULL_REBUILD:
import filecmp
for f in os.listdir(path_examples):
if f.endswith(".py"):
EXAMPLE_SET.add(os.path.splitext(f)[0])
# now move changed files from 'path_in_tmp' --> 'path_in'
file_list_path_in = set(os.listdir(path_in))
file_list_path_in_tmp = set(os.listdir(path_in_tmp))
# only for full updates
if _BPY_FULL_REBUILD:
shutil.rmtree(path_in, True)
shutil.rmtree(path_out, True)
else:
# write here, then move
shutil.rmtree(path_in_tmp, True)
# remove deprecated files that have been removed.
for f in sorted(file_list_path_in):
if f not in file_list_path_in_tmp:
print("\tdeprecated: %s" % f)
os.remove(os.path.join(path_in, f))
rna2sphinx(path_in_tmp)
# freshen with new files.
for f in sorted(file_list_path_in_tmp):
f_from = os.path.join(path_in_tmp, f)
f_to = os.path.join(path_in, f)
if not _BPY_FULL_REBUILD:
import filecmp
do_copy = True
if f in file_list_path_in:
if filecmp.cmp(f_from, f_to):
do_copy = False
# now move changed files from 'path_in_tmp' --> 'path_in'
file_list_path_in = set(os.listdir(path_in))
file_list_path_in_tmp = set(os.listdir(path_in_tmp))
if do_copy:
print("\tupdating: %s" % f)
shutil.copy(f_from, f_to)
'''else:
print("\tkeeping: %s" % f) # eh, not that useful'''
# remove deprecated files that have been removed.
for f in sorted(file_list_path_in):
if f not in file_list_path_in_tmp:
print("\tdeprecated: %s" % f)
os.remove(os.path.join(path_in, f))
# freshen with new files.
for f in sorted(file_list_path_in_tmp):
f_from = os.path.join(path_in_tmp, f)
f_to = os.path.join(path_in, f)
do_copy = True
if f in file_list_path_in:
if filecmp.cmp(f_from, f_to):
do_copy = False
if do_copy:
print("\tupdating: %s" % f)
shutil.copy(f_from, f_to)
'''else:
print("\tkeeping: %s" % f) # eh, not that useful'''
EXAMPLE_SET_UNUSED = EXAMPLE_SET - EXAMPLE_SET_USED
if EXAMPLE_SET_UNUSED:
print("\nUnused examples found in '%s'..." % path_examples)
for f in EXAMPLE_SET_UNUSED:
print(" %s.py" % f)
print(" %d total\n" % len(EXAMPLE_SET_UNUSED))
EXAMPLE_SET_UNUSED = EXAMPLE_SET - EXAMPLE_SET_USED
if EXAMPLE_SET_UNUSED:
print("\nUnused examples found in '%s'..." % path_examples)
for f in EXAMPLE_SET_UNUSED:
print(" %s.py" % f)
print(" %d total\n" % len(EXAMPLE_SET_UNUSED))
import sys
sys.exit()

View File

@@ -19,7 +19,7 @@
#
set(INC
./include
include
)
set(INC_SYS

View File

@@ -25,7 +25,7 @@
# ***** END GPL LICENSE BLOCK *****
set(INC
./include
include
)
set(INC_SYS
@@ -33,7 +33,9 @@ set(INC_SYS
)
if(UNIX)
list(APPEND INC_SYS ${X11_X11_INCLUDE_PATH})
list(APPEND INC_SYS
${X11_X11_INCLUDE_PATH}
)
endif()
set(SRC

View File

@@ -25,7 +25,7 @@
# ***** END GPL LICENSE BLOCK *****
set(INC
include
)
set(INC_SYS

View File

@@ -31,7 +31,6 @@ add_subdirectory(moto)
add_subdirectory(memutil)
add_subdirectory(iksolver)
add_subdirectory(opennl)
add_subdirectory(smoke)
add_subdirectory(mikktspace)
if(WITH_AUDASPACE)
@@ -42,6 +41,10 @@ if(WITH_MOD_FLUID)
add_subdirectory(elbeem)
endif()
if(WITH_MOD_SMOKE)
add_subdirectory(smoke)
endif()
if(WITH_MOD_DECIMATE)
add_subdirectory(container)
add_subdirectory(decimation)

View File

@@ -22,9 +22,9 @@
set(INC
.
intern
FX
SRC
intern
../ffmpeg
)
@@ -159,8 +159,12 @@ set(SRC
if(WITH_CODEC_FFMPEG)
add_definitions(-DWITH_FFMPEG)
list(APPEND INC ffmpeg)
list(APPEND INC_SYS ${FFMPEG_INCLUDE_DIRS})
list(APPEND INC
ffmpeg
)
list(APPEND INC_SYS
${FFMPEG_INCLUDE_DIRS}
)
list(APPEND SRC
ffmpeg/AUD_FFMPEGFactory.cpp
ffmpeg/AUD_FFMPEGReader.cpp
@@ -172,8 +176,12 @@ endif()
if(WITH_SDL)
add_definitions(-DWITH_SDL)
list(APPEND INC SDL)
list(APPEND INC_SYS ${SDL_INCLUDE_DIR})
list(APPEND INC
SDL
)
list(APPEND INC_SYS
${SDL_INCLUDE_DIR}
)
list(APPEND SRC
SDL/AUD_SDLDevice.cpp
@@ -183,8 +191,12 @@ endif()
if(WITH_OPENAL)
add_definitions(-DWITH_OPENAL)
list(APPEND INC OpenAL)
list(APPEND INC_SYS ${OPENAL_INCLUDE_DIR})
list(APPEND INC
OpenAL
)
list(APPEND INC_SYS
${OPENAL_INCLUDE_DIR}
)
list(APPEND SRC
OpenAL/AUD_OpenALDevice.cpp
@@ -194,8 +206,12 @@ endif()
if(WITH_JACK)
add_definitions(-DWITH_JACK)
list(APPEND INC jack)
list(APPEND INC_SYS ${JACK_INCLUDE_DIRS})
list(APPEND INC
jack
)
list(APPEND INC_SYS
${JACK_INCLUDE_DIRS}
)
list(APPEND SRC
jack/AUD_JackDevice.cpp
@@ -205,8 +221,12 @@ endif()
if(WITH_CODEC_SNDFILE)
add_definitions(-DWITH_SNDFILE)
list(APPEND INC sndfile)
list(APPEND INC_SYS ${SNDFILE_INCLUDE_DIRS})
list(APPEND INC
sndfile
)
list(APPEND INC_SYS
${SNDFILE_INCLUDE_DIRS}
)
list(APPEND SRC
sndfile/AUD_SndFileFactory.cpp
sndfile/AUD_SndFileReader.cpp
@@ -218,7 +238,9 @@ endif()
if(WITH_SAMPLERATE)
add_definitions(-DWITH_SAMPLERATE)
list(APPEND INC_SYS ${SAMPLERATE_INCLUDE_DIRS})
list(APPEND INC_SYS
${SAMPLERATE_INCLUDE_DIRS}
)
list(APPEND SRC
SRC/AUD_SRCResampleFactory.cpp
SRC/AUD_SRCResampleReader.cpp
@@ -230,8 +252,12 @@ endif()
if(WITH_FFTW3 AND FALSE)
add_definitions(-DWITH_FFTW3)
list(APPEND INC fftw)
list(APPEND INC_SYS ${FFTW3_INCLUDE_DIRS})
list(APPEND INC
fftw
)
list(APPEND INC_SYS
${FFTW3_INCLUDE_DIRS}
)
list(APPEND SRC
fftw/AUD_BandPassFactory.cpp
fftw/AUD_BandPassReader.cpp
@@ -242,8 +268,12 @@ if(WITH_FFTW3 AND FALSE)
endif()
if(WITH_PYTHON)
list(APPEND INC Python)
list(APPEND INC_SYS ${PYTHON_INCLUDE_DIRS})
list(APPEND INC
Python
)
list(APPEND INC_SYS
${PYTHON_INCLUDE_DIRS}
)
list(APPEND SRC
Python/AUD_PyAPI.cpp

View File

@@ -26,11 +26,11 @@
set(INC
.
./intern
./extern
../memutil
extern
intern
../container
../guardedalloc
../memutil
../moto/include
../../source/blender/blenlib
../../source/blender/makesdna

View File

@@ -25,11 +25,11 @@
# ***** END GPL LICENSE BLOCK *****
set(INC
./intern
intern
../container
../guardedalloc
../moto/include
../memutil
../moto/include
)
set(INC_SYS

View File

@@ -40,7 +40,7 @@
#define FFMPEG_HAVE_AVIO 1
#endif
#if (LIBAVCODEC_VERSION_MAJOR > 53) || ((LIBAVCODEC_VERSION_MAJOR == 53) && (LIBAVCODEC_VERSION_MINOR > 1)) || ((LIBAVCODEC_VERSION_MAJOR == 53) && (LIBAVCODEC_VERSION_MINOR == 1) && (LIBAVCODEC_VERSION_MICRO >= 1)) || ((LIBAVCODEC_VERSION_MAJOR == 52) && (LIBAVCODEC_VERSION_MINOR >= 122))
#if (LIBAVCODEC_VERSION_MAJOR > 53) || ((LIBAVCODEC_VERSION_MAJOR == 53) && (LIBAVCODEC_VERSION_MINOR > 1)) || ((LIBAVCODEC_VERSION_MAJOR == 53) && (LIBAVCODEC_VERSION_MINOR == 1) && (LIBAVCODEC_VERSION_MICRO >= 1)) || ((LIBAVCODEC_VERSION_MAJOR == 52) && (LIBAVCODEC_VERSION_MINOR >= 121))
#define FFMPEG_HAVE_DEFAULT_VAL_UNION 1
#endif

View File

@@ -37,17 +37,16 @@ set(INC_SYS
set(SRC
intern/GHOST_Buttons.cpp
intern/GHOST_CallbackEventConsumer.cpp
intern/GHOST_C-api.cpp
intern/GHOST_Path-api.cpp
intern/GHOST_CallbackEventConsumer.cpp
intern/GHOST_DisplayManager.cpp
intern/GHOST_EventManager.cpp
intern/GHOST_EventPrinter.cpp
intern/GHOST_ISystem.cpp
intern/GHOST_ISystemPaths.cpp
intern/GHOST_ModifierKeys.cpp
intern/GHOST_NDOFManager.cpp
intern/GHOST_Path-api.cpp
intern/GHOST_Path-api.cpp
intern/GHOST_Rect.cpp
intern/GHOST_System.cpp
intern/GHOST_TimerManager.cpp
@@ -64,6 +63,7 @@ set(SRC
GHOST_Path-api.h
GHOST_Rect.h
GHOST_Types.h
intern/GHOST_Buttons.h
intern/GHOST_CallbackEventConsumer.h
intern/GHOST_Debug.h
@@ -75,7 +75,6 @@ set(SRC
intern/GHOST_EventKey.h
intern/GHOST_EventManager.h
intern/GHOST_EventNDOF.h
intern/GHOST_EventPrinter.h
intern/GHOST_EventString.h
intern/GHOST_EventTrackpad.h
intern/GHOST_EventWheel.h
@@ -89,13 +88,37 @@ set(SRC
intern/GHOST_WindowManager.h
)
if(WITH_HEADLESS)
if(WITH_GHOST_DEBUG)
list(APPEND SRC
intern/GHOST_DisplayManagerNULL.h
intern/GHOST_SystemNULL.h
intern/GHOST_WindowNULL.h
intern/GHOST_EventPrinter.cpp
intern/GHOST_EventPrinter.h
)
add_definitions(-DWITH_HEADLESS)
add_definitions(-DWITH_GHOST_DEBUG)
endif()
if(WITH_HEADLESS OR WITH_GHOST_SDL)
if(WITH_HEADLESS)
list(APPEND SRC
intern/GHOST_DisplayManagerNULL.h
intern/GHOST_SystemNULL.h
intern/GHOST_WindowNULL.h
)
add_definitions(-DWITH_HEADLESS)
else()
list(APPEND SRC
intern/GHOST_DisplayManagerSDL.cpp
intern/GHOST_SystemSDL.cpp
intern/GHOST_WindowSDL.cpp
intern/GHOST_DisplayManagerSDL.h
intern/GHOST_SystemSDL.h
intern/GHOST_WindowSDL.h
)
add_definitions(-DWITH_GHOST_SDL)
endif()
# ack, this is still system dependant
if(APPLE)
@@ -124,6 +147,10 @@ if(WITH_HEADLESS)
)
endif()
list(APPEND INC_SYS
${SDL_INCLUDE_DIR}
)
elseif(APPLE)
if(WITH_COCOA)
list(APPEND SRC
@@ -161,7 +188,9 @@ elseif(UNIX)
add_definitions(-DWITH_X11_XINPUT)
endif()
list(APPEND INC_SYS ${X11_X11_INCLUDE_PATH})
list(APPEND INC_SYS
${X11_X11_INCLUDE_PATH}
)
list(APPEND SRC
intern/GHOST_DisplayManagerX11.cpp
@@ -181,7 +210,9 @@ elseif(UNIX)
if(X11_XF86keysym_INCLUDE_PATH)
add_definitions(-DWITH_XF86KEYSYM)
list(APPEND INC_SYS ${X11_XF86keysym_INCLUDE_PATH})
list(APPEND INC_SYS
${X11_XF86keysym_INCLUDE_PATH}
)
endif()
elseif(WIN32)
@@ -189,7 +220,9 @@ elseif(WIN32)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /WX")
endif()
list(APPEND INC_SYS ${WINTAB_INC})
list(APPEND INC_SYS
${WINTAB_INC}
)
list(APPEND SRC
intern/GHOST_DisplayManagerWin32.cpp

View File

@@ -218,8 +218,9 @@ typedef enum {
GHOST_kStandardCursorBottomLeftCorner,
GHOST_kStandardCursorCopy,
GHOST_kStandardCursorCustom,
GHOST_kStandardCursorNumCursors,
GHOST_kStandardCursorPencil
GHOST_kStandardCursorPencil,
GHOST_kStandardCursorNumCursors
} GHOST_TStandardCursor;

View File

@@ -14,11 +14,24 @@ if window_system == 'darwin':
pf = ['GHOST_DisplayManager', 'GHOST_System', 'GHOST_SystemPaths', 'GHOST_Window', 'GHOST_DropTarget']
defs=['_USE_MATH_DEFINES']
if window_system in ('linux2', 'openbsd3', 'sunos5', 'freebsd7', 'freebsd8', 'freebsd9', 'irix6', 'aix4', 'aix5'):
incs = '. ../string #extern/glew/include #source/blender/imbuf #source/blender/makesdna ' + env['BF_OPENGL_INC']
if env['WITH_GHOST_SDL']:
for f in pf:
try:
sources.remove('intern' + os.sep + f + 'Carbon.cpp')
sources.remove('intern' + os.sep + f + 'Win32.cpp')
sources.remove('intern' + os.sep + f + 'X11.cpp')
except ValueError:
pass
incs += ' ' + env['BF_SDL_INC']
defs += ['WITH_GHOST_SDL']
elif window_system in ('linux2', 'openbsd3', 'sunos5', 'freebsd7', 'freebsd8', 'freebsd9', 'irix6', 'aix4', 'aix5'):
for f in pf:
try:
sources.remove('intern' + os.sep + f + 'Win32.cpp')
sources.remove('intern' + os.sep + f + 'Carbon.cpp')
sources.remove('intern' + os.sep + f + 'SDL.cpp')
except ValueError:
pass
defs += ['PREFIX=\\"/usr/local/\\"'] # XXX, make an option
@@ -29,6 +42,7 @@ elif window_system in ('win32-vc', 'win32-mingw', 'cygwin', 'linuxcross', 'win64
try:
sources.remove('intern' + os.sep + f + 'X11.cpp')
sources.remove('intern' + os.sep + f + 'Carbon.cpp')
sources.remove('intern' + os.sep + f + 'SDL.cpp')
except ValueError:
pass
elif window_system == 'darwin':
@@ -42,6 +56,7 @@ elif window_system == 'darwin':
sources.remove('intern' + os.sep + f + 'Win32.cpp')
sources.remove('intern' + os.sep + f + 'X11.cpp')
sources.remove('intern' + os.sep + f + 'Carbon.cpp')
sources.remove('intern' + os.sep + f + 'SDL.cpp')
except ValueError:
pass
else:
@@ -50,6 +65,7 @@ elif window_system == 'darwin':
sources.remove('intern' + os.sep + f + 'Win32.cpp')
sources.remove('intern' + os.sep + f + 'X11.cpp')
sources.remove('intern' + os.sep + f + 'Cocoa.mm')
sources.remove('intern' + os.sep + f + 'SDL.cpp')
except ValueError:
pass
@@ -58,9 +74,10 @@ else:
Exit()
if env['BF_GHOST_DEBUG']:
defs.append('BF_GHOST_DEBUG')
defs.append('WITH_GHOST_DEBUG')
else:
sources.remove('intern' + os.sep + 'GHOST_EventPrinter.cpp')
incs = '. ../string #extern/glew/include #source/blender/imbuf #source/blender/makesdna ' + env['BF_OPENGL_INC']
if window_system in ('win32-vc', 'win32-mingw', 'cygwin', 'linuxcross', 'win64-vc'):
incs = env['BF_WINTAB_INC'] + ' ' + incs

View File

@@ -41,9 +41,9 @@
#endif // DEBUG
#endif // WIN32
#ifdef BF_GHOST_DEBUG
#ifdef WITH_GHOST_DEBUG
#define GHOST_DEBUG // spit ghost events to stdout
#endif // BF_GHOST_DEBUG
#endif // WITH_GHOST_DEBUG
#ifdef GHOST_DEBUG
#include <iostream>

View File

@@ -164,5 +164,5 @@ GHOST_TSuccess GHOST_DisplayManagerCocoa::setCurrentDisplaySetting(GHOST_TUns8 d
//CGDisplayErr err = ::CGDisplaySwitchToMode(m_displayIDs[display], displayModeValues);
return /*err == CGDisplayNoErr ? GHOST_kSuccess :*/ GHOST_kFailure;
return /*err == CGDisplayNoErr ?*/ GHOST_kSuccess /*: GHOST_kFailure*/;
}

View File

@@ -0,0 +1,93 @@
/*
* $Id$
* ***** BEGIN GPL LICENSE BLOCK *****
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* Contributor(s): Campbell Barton
*
* ***** END GPL LICENSE BLOCK *****
*/
/** \file ghost/intern/GHOST_DisplayManagerSDL.cpp
* \ingroup GHOST
*/
#include "GHOST_SystemSDL.h"
#include "GHOST_DisplayManagerSDL.h"
GHOST_DisplayManagerSDL::GHOST_DisplayManagerSDL(GHOST_SystemSDL *system)
:
GHOST_DisplayManager(),
m_system(system)
{
/* do nothing */
}
GHOST_TSuccess
GHOST_DisplayManagerSDL::getNumDisplays(GHOST_TUns8& numDisplays)
{
numDisplays= SDL_GetNumVideoDisplays();
return GHOST_kSuccess;
}
GHOST_TSuccess GHOST_DisplayManagerSDL::getNumDisplaySettings(GHOST_TUns8 display,
GHOST_TInt32& numSettings)
{
GHOST_ASSERT(display < 1, "Only single display systems are currently supported.\n");
numSettings= GHOST_TInt32(1);
return GHOST_kSuccess;
}
GHOST_TSuccess
GHOST_DisplayManagerSDL::getDisplaySetting(GHOST_TUns8 display,
GHOST_TInt32 index,
GHOST_DisplaySetting& setting)
{
GHOST_ASSERT(display < 1, "Only single display systems are currently supported.\n");
GHOST_ASSERT(index < 1, "Requested setting outside of valid range.\n");
SDL_DisplayMode mode;
SDL_GetDesktopDisplayMode(display, &mode);
setting.xPixels= mode.w;
setting.yPixels= mode.h;
setting.bpp= SDL_BYTESPERPIXEL(mode.format);
/* assume 60 when unset */
setting.frequency= mode.refresh_rate ? mode.refresh_rate : 60;
return GHOST_kSuccess;
}
GHOST_TSuccess
GHOST_DisplayManagerSDL::getCurrentDisplaySetting(GHOST_TUns8 display,
GHOST_DisplaySetting& setting)
{
return getDisplaySetting(display,GHOST_TInt32(0),setting);
}
GHOST_TSuccess
GHOST_DisplayManagerSDL:: setCurrentDisplaySetting(GHOST_TUns8 display,
const GHOST_DisplaySetting& setting)
{
// This is never going to work robustly in X
// but it's currently part of the full screen interface
// we fudge it for now.
return GHOST_kSuccess;
}

View File

@@ -0,0 +1,73 @@
/*
* $Id$
* ***** BEGIN GPL LICENSE BLOCK *****
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* Contributor(s): Campbell Barton
*
* ***** END GPL LICENSE BLOCK *****
*/
/** \file ghost/intern/GHOST_DisplayManagerSDL.h
* \ingroup GHOST
* Declaration of GHOST_DisplayManagerSDL class.
*/
#ifndef _GHOST_DISPLAY_MANAGER_SDL_H_
#define _GHOST_DISPLAY_MANAGER_SDL_H_
#include "GHOST_DisplayManager.h"
extern "C" {
#include "SDL.h"
}
#if !SDL_VERSION_ATLEAST(1, 3, 0)
# error "SDL 1.3 or newer is needed to build with Ghost"
#endif
class GHOST_SystemSDL;
class GHOST_DisplayManagerSDL : public GHOST_DisplayManager
{
public:
GHOST_DisplayManagerSDL(GHOST_SystemSDL *system);
GHOST_TSuccess
getNumDisplays(GHOST_TUns8& numDisplays);
GHOST_TSuccess
getNumDisplaySettings(GHOST_TUns8 display,
GHOST_TInt32& numSettings);
GHOST_TSuccess
getDisplaySetting(GHOST_TUns8 display,
GHOST_TInt32 index,
GHOST_DisplaySetting& setting);
GHOST_TSuccess
getCurrentDisplaySetting(GHOST_TUns8 display,
GHOST_DisplaySetting& setting);
GHOST_TSuccess
setCurrentDisplaySetting(GHOST_TUns8 display,
const GHOST_DisplaySetting& setting);
private :
GHOST_SystemSDL * m_system;
};
#endif /* _GHOST_DISPLAY_MANAGER_SDL_H_ */

View File

@@ -37,6 +37,7 @@
#include "GHOST_EventDragnDrop.h"
#include "GHOST_Debug.h"
#include <stdio.h>
bool GHOST_EventPrinter::processEvent(GHOST_IEvent* event)
{
@@ -82,17 +83,17 @@ bool GHOST_EventPrinter::processEvent(GHOST_IEvent* event)
case GHOST_kEventKeyUp:
{
GHOST_TEventKeyData* keyData = (GHOST_TEventKeyData*)((GHOST_IEvent*)event)->getData();
STR_String str;
char str[32]= {'\0'};
getKeyString(keyData->key, str);
std::cout << "GHOST_kEventKeyUp, key: " << str.Ptr();
std::cout << "GHOST_kEventKeyUp, key: " << str;
}
break;
case GHOST_kEventKeyDown:
{
GHOST_TEventKeyData* keyData = (GHOST_TEventKeyData*)((GHOST_IEvent*)event)->getData();
STR_String str;
char str[32]= {'\0'};
getKeyString(keyData->key, str);
std::cout << "GHOST_kEventKeyDown, key: " << str.Ptr();
std::cout << "GHOST_kEventKeyDown, key: " << str;
}
break;
@@ -183,165 +184,161 @@ bool GHOST_EventPrinter::processEvent(GHOST_IEvent* event)
}
void GHOST_EventPrinter::getKeyString(GHOST_TKey key, STR_String& str) const
void GHOST_EventPrinter::getKeyString(GHOST_TKey key, char str[32]) const
{
if ((key >= GHOST_kKeyComma) && (key <= GHOST_kKeyRightBracket)) {
str = ((char)key);
sprintf(str, "%c", (char)key);
} else if ((key >= GHOST_kKeyNumpad0) && (key <= GHOST_kKeyNumpad9)) {
int number = key - GHOST_kKeyNumpad0;
STR_String numberStr (number);
str = "Numpad";
str += numberStr;
sprintf(str, "Numpad %d", (key - GHOST_kKeyNumpad0));
#if defined(__sun__) || defined(__sun)
} else if (key == 268828432) { /* solaris keyboards are messed up */
/* This should really test XK_F11 but that doesn't work */
str = "F11";
strcpy(str, "F11");
} else if (key == 268828433) { /* solaris keyboards are messed up */
/* This should really test XK_F12 but that doesn't work */
str = "F12";
strcpy(str, "F12");
#endif
} else if ((key >= GHOST_kKeyF1) && (key <= GHOST_kKeyF24)) {
int number = key - GHOST_kKeyF1 + 1;
STR_String numberStr (number);
str = "F";
str += numberStr;
sprintf(str, "F%d", key - GHOST_kKeyF1 + 1);
} else {
switch (key)
{
const char *tstr= NULL;
switch (key) {
case GHOST_kKeyBackSpace:
str = "BackSpace";
tstr = "BackSpace";
break;
case GHOST_kKeyTab:
str = "Tab";
tstr = "Tab";
break;
case GHOST_kKeyLinefeed:
str = "Linefeed";
tstr = "Linefeed";
break;
case GHOST_kKeyClear:
str = "Clear";
tstr = "Clear";
break;
case GHOST_kKeyEnter:
str = "Enter";
tstr = "Enter";
break;
case GHOST_kKeyEsc:
str = "Esc";
tstr = "Esc";
break;
case GHOST_kKeySpace:
str = "Space";
tstr = "Space";
break;
case GHOST_kKeyQuote:
str = "Quote";
tstr = "Quote";
break;
case GHOST_kKeyBackslash:
str = "\\";
tstr = "\\";
break;
case GHOST_kKeyAccentGrave:
str = "`";
tstr = "`";
break;
case GHOST_kKeyLeftShift:
str = "LeftShift";
tstr = "LeftShift";
break;
case GHOST_kKeyRightShift:
str = "RightShift";
tstr = "RightShift";
break;
case GHOST_kKeyLeftControl:
str = "LeftControl";
tstr = "LeftControl";
break;
case GHOST_kKeyRightControl:
str = "RightControl";
tstr = "RightControl";
break;
case GHOST_kKeyLeftAlt:
str = "LeftAlt";
tstr = "LeftAlt";
break;
case GHOST_kKeyRightAlt:
str = "RightAlt";
tstr = "RightAlt";
break;
case GHOST_kKeyOS:
str = "OS";
tstr = "OS";
break;
case GHOST_kKeyGrLess:
// PC german!
str = "GrLess";
tstr = "GrLess";
break;
case GHOST_kKeyCapsLock:
str = "CapsLock";
tstr = "CapsLock";
break;
case GHOST_kKeyNumLock:
str = "NumLock";
tstr = "NumLock";
break;
case GHOST_kKeyScrollLock:
str = "ScrollLock";
tstr = "ScrollLock";
break;
case GHOST_kKeyLeftArrow:
str = "LeftArrow";
tstr = "LeftArrow";
break;
case GHOST_kKeyRightArrow:
str = "RightArrow";
tstr = "RightArrow";
break;
case GHOST_kKeyUpArrow:
str = "UpArrow";
tstr = "UpArrow";
break;
case GHOST_kKeyDownArrow:
str = "DownArrow";
tstr = "DownArrow";
break;
case GHOST_kKeyPrintScreen:
str = "PrintScreen";
tstr = "PrintScreen";
break;
case GHOST_kKeyPause:
str = "Pause";
tstr = "Pause";
break;
case GHOST_kKeyInsert:
str = "Insert";
tstr = "Insert";
break;
case GHOST_kKeyDelete:
str = "Delete";
tstr = "Delete";
break;
case GHOST_kKeyHome:
str = "Home";
tstr = "Home";
break;
case GHOST_kKeyEnd:
str = "End";
tstr = "End";
break;
case GHOST_kKeyUpPage:
str = "UpPage";
tstr = "UpPage";
break;
case GHOST_kKeyDownPage:
str = "DownPage";
tstr = "DownPage";
break;
case GHOST_kKeyNumpadPeriod:
str = "NumpadPeriod";
tstr = "NumpadPeriod";
break;
case GHOST_kKeyNumpadEnter:
str = "NumpadEnter";
tstr = "NumpadEnter";
break;
case GHOST_kKeyNumpadPlus:
str = "NumpadPlus";
tstr = "NumpadPlus";
break;
case GHOST_kKeyNumpadMinus:
str = "NumpadMinus";
tstr = "NumpadMinus";
break;
case GHOST_kKeyNumpadAsterisk:
str = "NumpadAsterisk";
tstr = "NumpadAsterisk";
break;
case GHOST_kKeyNumpadSlash:
str = "NumpadSlash";
tstr = "NumpadSlash";
break;
case GHOST_kKeyMediaPlay:
str = "MediaPlayPause";
tstr = "MediaPlayPause";
break;
case GHOST_kKeyMediaStop:
str = "MediaStop";
tstr = "MediaStop";
break;
case GHOST_kKeyMediaFirst:
str = "MediaFirst";
tstr = "MediaFirst";
break;
case GHOST_kKeyMediaLast:
str = "MediaLast";
tstr = "MediaLast";
break;
default:
str = "unknown";
tstr = "unknown";
break;
}
sprintf(str, "%s", tstr);
}
}

View File

@@ -58,7 +58,7 @@ protected:
* @param key The GHOST key code to convert.
* @param str The GHOST key code converted to a readable string.
*/
void getKeyString(GHOST_TKey key, STR_String& str) const;
void getKeyString(GHOST_TKey key, char str[32]) const;
};
#endif // _GHOST_EVENT_PRINTER_H_

View File

@@ -43,6 +43,8 @@
#ifdef WITH_HEADLESS
# include "GHOST_SystemNULL.h"
#elif defined(WITH_GHOST_SDL)
# include "GHOST_SystemSDL.h"
#elif defined(WIN32)
# include "GHOST_SystemWin32.h"
#else
@@ -67,6 +69,8 @@ GHOST_TSuccess GHOST_ISystem::createSystem()
if (!m_system) {
#ifdef WITH_HEADLESS
m_system = new GHOST_SystemNULL();
#elif defined(WITH_GHOST_SDL)
m_system = new GHOST_SystemSDL();
#elif defined(WIN32)
m_system = new GHOST_SystemWin32 ();
#else

View File

@@ -85,6 +85,8 @@ GHOST_NDOFManager::deviceOpen(GHOST_IWindow* window,
/* do nothing */
#elif defined(_WIN32) || defined(__APPLE__)
m_DeviceHandle = ndofDeviceOpen((void *)&currentNdofValues);
#elif defined(WITH_GHOST_SDL)
/* do nothing */
#else
GHOST_SystemX11 *sys;
sys = static_cast<GHOST_SystemX11*>(GHOST_ISystem::getSystem());

View File

@@ -119,14 +119,6 @@ public:
const GHOST_TEmbedderWindowID parentWindow = 0
);
virtual GHOST_TSuccess beginFullScreen(
const GHOST_DisplaySetting& setting,
GHOST_IWindow** window,
const bool stereoVisual
);
virtual GHOST_TSuccess endFullScreen( void );
/***************************************************************************************
** Event management functionality
***************************************************************************************/
@@ -272,17 +264,6 @@ protected:
*/
GHOST_TSuccess setMouseCursorPosition(GHOST_TInt32 x, GHOST_TInt32 y);
/**
* Push cursor event, with coordinate conversion to follow GHOST convention.
*/
void pushEventCursor(GHOST_TUns64 msec, GHOST_TEventType type, GHOST_IWindow* window, GHOST_TInt32 x, GHOST_TInt32 y);
/**
* Push trackpad event, with coordinate conversion to follow GHOST convention.
*/
void pushEventTrackpad(GHOST_TUns64 msec, GHOST_IWindow* window, GHOST_TTrackpadEventSubTypes subtype,
GHOST_TInt32 x, GHOST_TInt32 y, GHOST_TInt32 deltaX, GHOST_TInt32 deltaY);
/** Start time at initialization. */
GHOST_TUns64 m_start_time;

View File

@@ -773,26 +773,6 @@ GHOST_IWindow* GHOST_SystemCocoa::createWindow(
return window;
}
GHOST_TSuccess GHOST_SystemCocoa::beginFullScreen(const GHOST_DisplaySetting& setting, GHOST_IWindow** window, const bool stereoVisual)
{
GHOST_IWindow* currentWindow = m_windowManager->getActiveWindow();
*window = currentWindow;
if(!currentWindow) return GHOST_kFailure;
return currentWindow->setState(GHOST_kWindowStateFullScreen);
}
GHOST_TSuccess GHOST_SystemCocoa::endFullScreen(void)
{
GHOST_IWindow* currentWindow = m_windowManager->getActiveWindow();
if(!currentWindow) return GHOST_kFailure;
return currentWindow->setState(GHOST_kWindowStateNormal);
}
/**
* @note : returns coordinates in Cocoa screen coordinates
*/
@@ -806,37 +786,11 @@ GHOST_TSuccess GHOST_SystemCocoa::getCursorPosition(GHOST_TInt32& x, GHOST_TInt3
return GHOST_kSuccess;
}
void GHOST_SystemCocoa::pushEventCursor(GHOST_TUns64 msec, GHOST_TEventType type, GHOST_IWindow* window, GHOST_TInt32 x, GHOST_TInt32 y)
{
GHOST_Rect cBnds;
window->getClientBounds(cBnds);
y = (cBnds.getHeight() - 1) - y;
GHOST_TInt32 screen_x, screen_y;
window->clientToScreen(x, y, screen_x, screen_y);
pushEvent(new GHOST_EventCursor(msec, type, window, screen_x, screen_y));
}
void GHOST_SystemCocoa::pushEventTrackpad(GHOST_TUns64 msec, GHOST_IWindow* window, GHOST_TTrackpadEventSubTypes subtype, GHOST_TInt32 x, GHOST_TInt32 y, GHOST_TInt32 deltaX, GHOST_TInt32 deltaY)
{
GHOST_Rect cBnds;
window->getClientBounds(cBnds);
y = (cBnds.getHeight() - 1) - y;
deltaY = -deltaY;
GHOST_TInt32 screen_x, screen_y;
window->clientToScreen(x, y, screen_x, screen_y);
pushEvent(new GHOST_EventTrackpad(msec, window, subtype, screen_x, screen_y, deltaX, deltaY));
}
/**
* @note : expect Cocoa screen coordinates
*/
GHOST_TSuccess GHOST_SystemCocoa::setCursorPosition(GHOST_TInt32 x, GHOST_TInt32 y)
{
GHOST_TInt32 wx,wy;
GHOST_WindowCocoa* window = (GHOST_WindowCocoa*)m_windowManager->getActiveWindow();
if (!window) return GHOST_kFailure;
@@ -847,8 +801,7 @@ GHOST_TSuccess GHOST_SystemCocoa::setCursorPosition(GHOST_TInt32 x, GHOST_TInt32
CGAssociateMouseAndMouseCursorPosition(true);
//Force mouse move event (not pushed by Cocoa)
window->screenToClient(x, y, wx, wy);
pushEventCursor(getMilliSeconds(), GHOST_kEventCursorMove, window, wx,wy);
pushEvent(new GHOST_EventCursor(getMilliSeconds(), GHOST_kEventCursorMove, window, x, y));
m_outsideLoopEventProcessed = true;
return GHOST_kSuccess;
@@ -1460,9 +1413,9 @@ GHOST_TSuccess GHOST_SystemCocoa::handleTabletEvent(void *eventPtr, short eventT
GHOST_TSuccess GHOST_SystemCocoa::handleMouseEvent(void *eventPtr)
{
NSEvent *event = (NSEvent *)eventPtr;
GHOST_Window* window;
GHOST_WindowCocoa* window;
window = (GHOST_Window*)m_windowManager->getWindowAssociatedWithOSWindow((void*)[event window]);
window = (GHOST_WindowCocoa*)m_windowManager->getWindowAssociatedWithOSWindow((void*)[event window]);
if (!window) {
//printf("\nW failure for event 0x%x",[event type]);
return GHOST_kFailure;
@@ -1526,7 +1479,7 @@ GHOST_TSuccess GHOST_SystemCocoa::handleMouseEvent(void *eventPtr)
switch (window->getCursorGrabMode()) {
case GHOST_kGrabHide: //Cursor hidden grab operation : no cursor move
{
GHOST_TInt32 x_warp, y_warp, x_accum, y_accum;
GHOST_TInt32 x_warp, y_warp, x_accum, y_accum, x, y;
window->getCursorGrabInitPos(x_warp, y_warp);
@@ -1535,7 +1488,8 @@ GHOST_TSuccess GHOST_SystemCocoa::handleMouseEvent(void *eventPtr)
y_accum += -[event deltaY]; //Strange Apple implementation (inverted coordinates for the deltaY) ...
window->setCursorGrabAccum(x_accum, y_accum);
pushEventCursor([event timestamp]*1000, GHOST_kEventCursorMove, window, x_warp+x_accum, y_warp+y_accum);
window->clientToScreenIntern(x_warp+x_accum, y_warp+y_accum, x, y);
pushEvent(new GHOST_EventCursor([event timestamp]*1000, GHOST_kEventCursorMove, window, x, y));
}
break;
case GHOST_kGrabWrap: //Wrap cursor at area/window boundaries
@@ -1543,7 +1497,7 @@ GHOST_TSuccess GHOST_SystemCocoa::handleMouseEvent(void *eventPtr)
NSPoint mousePos = [event locationInWindow];
GHOST_TInt32 x_mouse= mousePos.x;
GHOST_TInt32 y_mouse= mousePos.y;
GHOST_TInt32 x_accum, y_accum, x_cur, y_cur;
GHOST_TInt32 x_accum, y_accum, x_cur, y_cur, x, y;
GHOST_Rect bounds, windowBounds, correctedBounds;
/* fallback to window bounds */
@@ -1552,7 +1506,7 @@ GHOST_TSuccess GHOST_SystemCocoa::handleMouseEvent(void *eventPtr)
//Switch back to Cocoa coordinates orientation (y=0 at botton,the same as blender internal btw!), and to client coordinates
window->getClientBounds(windowBounds);
window->screenToClient(bounds.m_l,bounds.m_b, correctedBounds.m_l, correctedBounds.m_t);
window->screenToClient(bounds.m_l, bounds.m_b, correctedBounds.m_l, correctedBounds.m_t);
window->screenToClient(bounds.m_r, bounds.m_t, correctedBounds.m_r, correctedBounds.m_b);
correctedBounds.m_b = (windowBounds.m_b - windowBounds.m_t) - correctedBounds.m_b;
correctedBounds.m_t = (windowBounds.m_b - windowBounds.m_t) - correctedBounds.m_t;
@@ -1574,19 +1528,24 @@ GHOST_TSuccess GHOST_SystemCocoa::handleMouseEvent(void *eventPtr)
m_cursorDelta_y = y_mouse-mousePos.y;
//Set new cursor position
window->clientToScreen(x_mouse, y_mouse, x_cur, y_cur);
window->clientToScreenIntern(x_mouse, y_mouse, x_cur, y_cur);
setMouseCursorPosition(x_cur, y_cur); /* wrap */
//Post event
window->getCursorGrabInitPos(x_cur, y_cur);
pushEventCursor([event timestamp]*1000, GHOST_kEventCursorMove, window, x_cur + x_accum, y_cur + y_accum);
window->clientToScreenIntern(x_cur + x_accum, y_cur + y_accum, x, y);
pushEvent(new GHOST_EventCursor([event timestamp]*1000, GHOST_kEventCursorMove, window, x, y));
}
break;
default:
{
//Normal cursor operation: send mouse position in window
NSPoint mousePos = [event locationInWindow];
pushEventCursor([event timestamp]*1000, GHOST_kEventCursorMove, window, mousePos.x, mousePos.y);
GHOST_TInt32 x, y;
window->clientToScreenIntern(mousePos.x, mousePos.y, x, y);
pushEvent(new GHOST_EventCursor([event timestamp]*1000, GHOST_kEventCursorMove, window, x, y));
m_cursorDelta_x=0;
m_cursorDelta_y=0; //Mouse motion occurred between two cursor warps, so we can reset the delta counter
}
@@ -1608,6 +1567,7 @@ GHOST_TSuccess GHOST_SystemCocoa::handleMouseEvent(void *eventPtr)
}
else {
NSPoint mousePos = [event locationInWindow];
GHOST_TInt32 x, y;
double dx = [event deltaX];
double dy = -[event deltaY];
@@ -1624,7 +1584,10 @@ GHOST_TSuccess GHOST_SystemCocoa::handleMouseEvent(void *eventPtr)
if (dy<0.0) dy-=0.5; else dy+=0.5;
if (dy< -deltaMax) dy= -deltaMax; else if (dy>deltaMax) dy=deltaMax;
pushEventTrackpad([event timestamp]*1000, window, GHOST_kTrackpadEventScroll, mousePos.x, mousePos.y, dx, dy);
window->clientToScreenIntern(mousePos.x, mousePos.y, x, y);
dy = -dy;
pushEvent(new GHOST_EventTrackpad([event timestamp]*1000, window, GHOST_kTrackpadEventScroll, x, y, dx, dy));
}
}
break;
@@ -1632,16 +1595,20 @@ GHOST_TSuccess GHOST_SystemCocoa::handleMouseEvent(void *eventPtr)
case NSEventTypeMagnify:
{
NSPoint mousePos = [event locationInWindow];
pushEventTrackpad([event timestamp]*1000, window, GHOST_kTrackpadEventMagnify, mousePos.x, mousePos.y,
[event magnification]*250.0 + 0.1, 0);
GHOST_TInt32 x, y;
window->clientToScreenIntern(mousePos.x, mousePos.y, x, y);
pushEvent(new GHOST_EventTrackpad([event timestamp]*1000, window, GHOST_kTrackpadEventMagnify, x, y,
[event magnification]*250.0 + 0.1, 0));
}
break;
case NSEventTypeRotate:
{
NSPoint mousePos = [event locationInWindow];
pushEventTrackpad([event timestamp]*1000, window, GHOST_kTrackpadEventRotate, mousePos.x, mousePos.y,
-[event rotation] * 5.0, 0);
GHOST_TInt32 x, y;
window->clientToScreenIntern(mousePos.x, mousePos.y, x, y);
pushEvent(new GHOST_EventTrackpad([event timestamp]*1000, window, GHOST_kTrackpadEventRotate, x, y,
-[event rotation] * 5.0, 0));
}
case NSEventTypeBeginGesture:
m_isGestureInProgress = true;

View File

@@ -0,0 +1,555 @@
/*
* $Id$
* ***** BEGIN GPL LICENSE BLOCK *****
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* Contributor(s): Campbell Barton
*
* ***** END GPL LICENSE BLOCK *****
*/
/** \file ghost/intern/GHOST_SystemSDL.cpp
* \ingroup GHOST
*/
#include <assert.h>
#include "GHOST_SystemSDL.h"
#include "GHOST_WindowManager.h"
#include "GHOST_EventCursor.h"
#include "GHOST_EventKey.h"
#include "GHOST_EventButton.h"
#include "GHOST_EventWheel.h"
GHOST_SystemSDL::GHOST_SystemSDL()
:
GHOST_System()
{
if(SDL_Init(SDL_INIT_VIDEO|SDL_INIT_TIMER) != 0) {
printf ("Error initializing SDL: %s\n", SDL_GetError());
}
/* SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1); */
/* SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 4); */
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
}
GHOST_SystemSDL::~GHOST_SystemSDL()
{
SDL_Quit();
}
GHOST_IWindow *
GHOST_SystemSDL::createWindow(const STR_String& title,
GHOST_TInt32 left,
GHOST_TInt32 top,
GHOST_TUns32 width,
GHOST_TUns32 height,
GHOST_TWindowState state,
GHOST_TDrawingContextType type,
bool stereoVisual,
const GHOST_TUns16 numOfAASamples,
const GHOST_TEmbedderWindowID parentWindow
)
{
GHOST_WindowSDL *window= NULL;
window= new GHOST_WindowSDL (this, title, left, top, width, height, state, parentWindow, type, stereoVisual, 1);
if (window) {
if (window->getValid()) {
m_windowManager->addWindow(window);
pushEvent(new GHOST_Event(getMilliSeconds(), GHOST_kEventWindowSize, window));
}
else {
delete window;
window= NULL;
}
}
return window;
}
GHOST_TSuccess
GHOST_SystemSDL::init() {
GHOST_TSuccess success = GHOST_System::init();
if (success) {
m_displayManager = new GHOST_DisplayManagerSDL(this);
if (m_displayManager) {
return GHOST_kSuccess;
}
}
return GHOST_kFailure;
}
void
GHOST_SystemSDL::getMainDisplayDimensions(GHOST_TUns32& width,
GHOST_TUns32& height) const
{
SDL_DisplayMode mode;
SDL_GetCurrentDisplayMode(0, &mode); /* note, always 0 display */
width= mode.w;
height= mode.h;
}
GHOST_TUns8
GHOST_SystemSDL::getNumDisplays() const
{
return SDL_GetNumVideoDisplays();
}
GHOST_TSuccess
GHOST_SystemSDL::getModifierKeys(GHOST_ModifierKeys& keys) const
{
SDL_Keymod mod= SDL_GetModState();
keys.set(GHOST_kModifierKeyLeftShift, (mod & KMOD_LSHIFT) != 0);
keys.set(GHOST_kModifierKeyRightShift, (mod & KMOD_RSHIFT) != 0);
keys.set(GHOST_kModifierKeyLeftControl, (mod & KMOD_LCTRL) != 0);
keys.set(GHOST_kModifierKeyRightControl, (mod & KMOD_RCTRL) != 0);
keys.set(GHOST_kModifierKeyLeftAlt, (mod & KMOD_LALT) != 0);
keys.set(GHOST_kModifierKeyRightAlt, (mod & KMOD_RALT) != 0);
keys.set(GHOST_kModifierKeyOS, (mod & (KMOD_LGUI|KMOD_RGUI)) != 0);
return GHOST_kSuccess;
}
#define GXMAP(k,x,y) case x: k= y; break;
static GHOST_TKey
convertSDLKey(SDL_Scancode key)
{
GHOST_TKey type;
if ((key >= SDL_SCANCODE_A) && (key <= SDL_SCANCODE_Z)) {
type= GHOST_TKey( key - SDL_SCANCODE_A + int(GHOST_kKeyA));
} else if ((key >= SDL_SCANCODE_1) && (key <= SDL_SCANCODE_0)) {
type= GHOST_TKey(key - SDL_SCANCODE_1 + int(GHOST_kKey0));
} else if ((key >= SDL_SCANCODE_F1) && (key <= SDL_SCANCODE_F12)) {
type= GHOST_TKey(key - SDL_SCANCODE_F1 + int(GHOST_kKeyF1));
} else if ((key >= SDL_SCANCODE_F13) && (key <= SDL_SCANCODE_F24)) {
type= GHOST_TKey(key - SDL_SCANCODE_F13 + int(GHOST_kKeyF13));
} else {
switch(key) {
/* TODO SDL_SCANCODE_NONUSBACKSLASH */
GXMAP(type,SDL_SCANCODE_BACKSPACE, GHOST_kKeyBackSpace);
GXMAP(type,SDL_SCANCODE_TAB, GHOST_kKeyTab);
GXMAP(type,SDL_SCANCODE_RETURN, GHOST_kKeyEnter);
GXMAP(type,SDL_SCANCODE_ESCAPE, GHOST_kKeyEsc);
GXMAP(type,SDL_SCANCODE_SPACE, GHOST_kKeySpace);
GXMAP(type,SDL_SCANCODE_SEMICOLON, GHOST_kKeySemicolon);
GXMAP(type,SDL_SCANCODE_PERIOD, GHOST_kKeyPeriod);
GXMAP(type,SDL_SCANCODE_COMMA, GHOST_kKeyComma);
GXMAP(type,SDL_SCANCODE_APOSTROPHE, GHOST_kKeyQuote);
GXMAP(type,SDL_SCANCODE_GRAVE, GHOST_kKeyAccentGrave);
GXMAP(type,SDL_SCANCODE_MINUS, GHOST_kKeyMinus);
GXMAP(type,SDL_SCANCODE_SLASH, GHOST_kKeySlash);
GXMAP(type,SDL_SCANCODE_BACKSLASH, GHOST_kKeyBackslash);
GXMAP(type,SDL_SCANCODE_KP_EQUALS, GHOST_kKeyEqual);
GXMAP(type,SDL_SCANCODE_LEFTBRACKET, GHOST_kKeyLeftBracket);
GXMAP(type,SDL_SCANCODE_RIGHTBRACKET, GHOST_kKeyRightBracket);
GXMAP(type,SDL_SCANCODE_PAUSE, GHOST_kKeyPause);
GXMAP(type,SDL_SCANCODE_LSHIFT, GHOST_kKeyLeftShift);
GXMAP(type,SDL_SCANCODE_RSHIFT, GHOST_kKeyRightShift);
GXMAP(type,SDL_SCANCODE_LCTRL, GHOST_kKeyLeftControl);
GXMAP(type,SDL_SCANCODE_RCTRL, GHOST_kKeyRightControl);
GXMAP(type,SDL_SCANCODE_LALT, GHOST_kKeyLeftAlt);
GXMAP(type,SDL_SCANCODE_RALT, GHOST_kKeyRightAlt);
GXMAP(type,SDL_SCANCODE_RGUI, GHOST_kKeyOS);
GXMAP(type,SDL_SCANCODE_INSERT, GHOST_kKeyInsert);
GXMAP(type,SDL_SCANCODE_DELETE, GHOST_kKeyDelete);
GXMAP(type,SDL_SCANCODE_HOME, GHOST_kKeyHome);
GXMAP(type,SDL_SCANCODE_END, GHOST_kKeyEnd);
GXMAP(type,SDL_SCANCODE_PAGEUP, GHOST_kKeyUpPage);
GXMAP(type,SDL_SCANCODE_PAGEDOWN, GHOST_kKeyDownPage);
GXMAP(type,SDL_SCANCODE_LEFT, GHOST_kKeyLeftArrow);
GXMAP(type,SDL_SCANCODE_RIGHT, GHOST_kKeyRightArrow);
GXMAP(type,SDL_SCANCODE_UP, GHOST_kKeyUpArrow);
GXMAP(type,SDL_SCANCODE_DOWN, GHOST_kKeyDownArrow);
GXMAP(type,SDL_SCANCODE_CAPSLOCK, GHOST_kKeyCapsLock);
GXMAP(type,SDL_SCANCODE_SCROLLLOCK, GHOST_kKeyScrollLock);
GXMAP(type,SDL_SCANCODE_NUMLOCKCLEAR, GHOST_kKeyNumLock);
/* keypad events */
/* note, sdl defines a bunch of kp defines I never saw before like
* SDL_SCANCODE_KP_PERCENT, SDL_SCANCODE_KP_XOR - campbell */
GXMAP(type,SDL_SCANCODE_KP_0, GHOST_kKeyNumpad0);
GXMAP(type,SDL_SCANCODE_KP_1, GHOST_kKeyNumpad1);
GXMAP(type,SDL_SCANCODE_KP_2, GHOST_kKeyNumpad2);
GXMAP(type,SDL_SCANCODE_KP_3, GHOST_kKeyNumpad3);
GXMAP(type,SDL_SCANCODE_KP_4, GHOST_kKeyNumpad4);
GXMAP(type,SDL_SCANCODE_KP_5, GHOST_kKeyNumpad5);
GXMAP(type,SDL_SCANCODE_KP_6, GHOST_kKeyNumpad6);
GXMAP(type,SDL_SCANCODE_KP_7, GHOST_kKeyNumpad7);
GXMAP(type,SDL_SCANCODE_KP_8, GHOST_kKeyNumpad8);
GXMAP(type,SDL_SCANCODE_KP_9, GHOST_kKeyNumpad9);
GXMAP(type,SDL_SCANCODE_KP_PERIOD, GHOST_kKeyNumpadPeriod);
GXMAP(type,SDL_SCANCODE_KP_ENTER, GHOST_kKeyNumpadEnter);
GXMAP(type,SDL_SCANCODE_KP_PLUS, GHOST_kKeyNumpadPlus);
GXMAP(type,SDL_SCANCODE_KP_MINUS, GHOST_kKeyNumpadMinus);
GXMAP(type,SDL_SCANCODE_KP_MULTIPLY, GHOST_kKeyNumpadAsterisk);
GXMAP(type,SDL_SCANCODE_KP_DIVIDE, GHOST_kKeyNumpadSlash);
/* Media keys in some keyboards and laptops with XFree86/Xorg */
GXMAP(type,SDL_SCANCODE_AUDIOPLAY, GHOST_kKeyMediaPlay);
GXMAP(type,SDL_SCANCODE_AUDIOSTOP, GHOST_kKeyMediaStop);
GXMAP(type,SDL_SCANCODE_AUDIOPREV, GHOST_kKeyMediaFirst);
// GXMAP(type,XF86XK_AudioRewind, GHOST_kKeyMediaFirst);
GXMAP(type,SDL_SCANCODE_AUDIONEXT, GHOST_kKeyMediaLast);
default:
type= GHOST_kKeyUnknown;
break;
}
}
return type;
}
#undef GXMAP
void
GHOST_SystemSDL::processEvent(SDL_Event *sdl_event)
{
GHOST_Event * g_event= NULL;
switch(sdl_event->type) {
case SDL_WINDOWEVENT:
{
SDL_WindowEvent &sdl_sub_evt= sdl_event->window;
GHOST_WindowSDL *window= findGhostWindow(SDL_GetWindowFromID(sdl_sub_evt.windowID));
//assert(window != NULL); // can be NULL on close window.
switch (sdl_sub_evt.event) {
case SDL_WINDOWEVENT_EXPOSED:
g_event= new GHOST_Event(getMilliSeconds(), GHOST_kEventWindowUpdate, window);
break;
case SDL_WINDOWEVENT_RESIZED:
g_event= new GHOST_Event(getMilliSeconds(), GHOST_kEventWindowSize, window);
break;
case SDL_WINDOWEVENT_MOVED:
g_event= new GHOST_Event(getMilliSeconds(), GHOST_kEventWindowMove, window);
break;
case SDL_WINDOWEVENT_FOCUS_GAINED:
g_event= new GHOST_Event(getMilliSeconds(), GHOST_kEventWindowActivate, window);
break;
case SDL_WINDOWEVENT_FOCUS_LOST:
g_event= new GHOST_Event(getMilliSeconds(), GHOST_kEventWindowDeactivate, window);
break;
case SDL_WINDOWEVENT_CLOSE:
g_event= new GHOST_Event(getMilliSeconds(), GHOST_kEventWindowClose, window);
break;
}
}
break;
case SDL_QUIT:
g_event= new GHOST_Event(getMilliSeconds(), GHOST_kEventQuit, NULL);
break;
case SDL_MOUSEMOTION:
{
SDL_MouseMotionEvent &sdl_sub_evt= sdl_event->motion;
SDL_Window *sdl_win= SDL_GetWindowFromID(sdl_sub_evt.windowID);
GHOST_WindowSDL *window= findGhostWindow(sdl_win);
assert(window != NULL);
int x_win, y_win;
SDL_GetWindowPosition(sdl_win, &x_win, &y_win);
GHOST_TInt32 x_root= sdl_sub_evt.x + x_win;
GHOST_TInt32 y_root= sdl_sub_evt.y + y_win;
#if 0
if(window->getCursorGrabMode() != GHOST_kGrabDisable && window->getCursorGrabMode() != GHOST_kGrabNormal)
{
GHOST_TInt32 x_new= x_root;
GHOST_TInt32 y_new= y_root;
GHOST_TInt32 x_accum, y_accum;
GHOST_Rect bounds;
/* fallback to window bounds */
if(window->getCursorGrabBounds(bounds)==GHOST_kFailure)
window->getClientBounds(bounds);
/* could also clamp to screen bounds
* wrap with a window outside the view will fail atm */
bounds.wrapPoint(x_new, y_new, 8); /* offset of one incase blender is at screen bounds */
window->getCursorGrabAccum(x_accum, y_accum);
// cant use setCursorPosition because the mouse may have no focus!
if(x_new != x_root || y_new != y_root) {
if (1 ) { //xme.time > m_last_warp) {
/* when wrapping we don't need to add an event because the
* setCursorPosition call will cause a new event after */
SDL_WarpMouseInWindow(sdl_win, x_new - x_win, y_new - y_win); /* wrap */
window->setCursorGrabAccum(x_accum + (x_root - x_new), y_accum + (y_root - y_new));
// m_last_warp= lastEventTime(xme.time);
} else {
// setCursorPosition(x_new, y_new); /* wrap but don't accumulate */
SDL_WarpMouseInWindow(sdl_win, x_new - x_win, y_new - y_win);
}
g_event = new GHOST_EventCursor(getMilliSeconds(), GHOST_kEventCursorMove, window, x_new, y_new);
}
else {
g_event = new GHOST_EventCursor(getMilliSeconds(), GHOST_kEventCursorMove, window, x_root + x_accum, y_root + y_accum);
}
}
else
#endif
{
g_event= new GHOST_EventCursor(getMilliSeconds(), GHOST_kEventCursorMove, window, x_root, y_root);
}
break;
}
case SDL_MOUSEBUTTONUP:
case SDL_MOUSEBUTTONDOWN:
{
SDL_MouseButtonEvent &sdl_sub_evt= sdl_event->button;
GHOST_TButtonMask gbmask= GHOST_kButtonMaskLeft;
GHOST_TEventType type= (sdl_sub_evt.state==SDL_PRESSED) ? GHOST_kEventButtonDown : GHOST_kEventButtonUp;
GHOST_WindowSDL *window= findGhostWindow(SDL_GetWindowFromID(sdl_sub_evt.windowID));
assert(window != NULL);
/* process rest of normal mouse buttons */
if(sdl_sub_evt.button == SDL_BUTTON_LEFT)
gbmask= GHOST_kButtonMaskLeft;
else if(sdl_sub_evt.button == SDL_BUTTON_MIDDLE)
gbmask= GHOST_kButtonMaskMiddle;
else if(sdl_sub_evt.button == SDL_BUTTON_RIGHT)
gbmask= GHOST_kButtonMaskRight;
/* these buttons are untested! */
else if(sdl_sub_evt.button == SDL_BUTTON_X1)
gbmask= GHOST_kButtonMaskButton4;
else if(sdl_sub_evt.button == SDL_BUTTON_X2)
gbmask= GHOST_kButtonMaskButton5;
else
break;
g_event= new GHOST_EventButton(getMilliSeconds(), type, window, gbmask);
break;
}
case SDL_MOUSEWHEEL:
{
SDL_MouseWheelEvent &sdl_sub_evt= sdl_event->wheel;
GHOST_WindowSDL *window= findGhostWindow(SDL_GetWindowFromID(sdl_sub_evt.windowID));
assert(window != NULL);
g_event= new GHOST_EventWheel(getMilliSeconds(), window, sdl_sub_evt.y);
}
break;
case SDL_KEYDOWN:
case SDL_KEYUP:
{
SDL_KeyboardEvent &sdl_sub_evt= sdl_event->key;
GHOST_TEventType type= (sdl_sub_evt.state == SDL_PRESSED) ? GHOST_kEventKeyDown : GHOST_kEventKeyUp;
GHOST_WindowSDL *window= findGhostWindow(SDL_GetWindowFromID(sdl_sub_evt.windowID));
assert(window != NULL);
GHOST_TKey gkey= convertSDLKey(sdl_sub_evt.keysym.scancode);
/* note, the sdl_sub_evt.keysym.sym is truncated, for unicode support ghost has to be modified */
g_event= new GHOST_EventKey(getMilliSeconds(), type, window, gkey, sdl_sub_evt.keysym.sym);
}
break;
}
if (g_event) {
pushEvent(g_event);
}
}
GHOST_TSuccess
GHOST_SystemSDL::getCursorPosition(GHOST_TInt32& x,
GHOST_TInt32& y) const
{
int x_win, y_win;
SDL_Window *win= SDL_GetMouseFocus();
SDL_GetWindowPosition(win, &x_win, &y_win);
int xi, yi;
SDL_GetMouseState(&xi, &yi);
x= xi + x_win;
y= yi + x_win;
return GHOST_kSuccess;
}
GHOST_TSuccess
GHOST_SystemSDL::setCursorPosition(GHOST_TInt32 x,
GHOST_TInt32 y)
{
int x_win, y_win;
SDL_Window *win= SDL_GetMouseFocus();
SDL_GetWindowPosition(win, &x_win, &y_win);
SDL_WarpMouseInWindow(win, x - x_win, y - y_win);
return GHOST_kSuccess;
}
bool
GHOST_SystemSDL::generateWindowExposeEvents()
{
vector<GHOST_WindowSDL *>::iterator w_start= m_dirty_windows.begin();
vector<GHOST_WindowSDL *>::const_iterator w_end= m_dirty_windows.end();
bool anyProcessed= false;
for (;w_start != w_end; ++w_start) {
GHOST_Event * g_event= new
GHOST_Event(
getMilliSeconds(),
GHOST_kEventWindowUpdate,
*w_start
);
(*w_start)->validate();
if (g_event) {
printf("Expose events pushed\n");
pushEvent(g_event);
anyProcessed= true;
}
}
m_dirty_windows.clear();
return anyProcessed;
}
bool
GHOST_SystemSDL::processEvents(bool waitForEvent)
{
// Get all the current events -- translate them into
// ghost events and call base class pushEvent() method.
bool anyProcessed= false;
do {
GHOST_TimerManager* timerMgr= getTimerManager();
if (waitForEvent && m_dirty_windows.empty() && !SDL_HasEvents(SDL_FIRSTEVENT, SDL_LASTEVENT)) {
GHOST_TUns64 next= timerMgr->nextFireTime();
if (next==GHOST_kFireTimeNever) {
SDL_WaitEventTimeout(NULL, -1);
//SleepTillEvent(m_display, -1);
} else {
GHOST_TInt64 maxSleep= next - getMilliSeconds();
if(maxSleep >= 0) {
SDL_WaitEventTimeout(NULL, next - getMilliSeconds());
// SleepTillEvent(m_display, next - getMilliSeconds()); // X11
}
}
}
if (timerMgr->fireTimers(getMilliSeconds())) {
anyProcessed= true;
}
SDL_Event sdl_event;
while (SDL_PollEvent(&sdl_event)) {
processEvent(&sdl_event);
anyProcessed= true;
}
if (generateWindowExposeEvents()) {
anyProcessed= true;
}
} while (waitForEvent && !anyProcessed);
return anyProcessed;
}
GHOST_WindowSDL *
GHOST_SystemSDL::findGhostWindow(SDL_Window *sdl_win)
{
if (sdl_win == NULL) return NULL;
// It is not entirely safe to do this as the backptr may point
// to a window that has recently been removed.
// We should always check the window manager's list of windows
// and only process events on these windows.
vector<GHOST_IWindow *> & win_vec= m_windowManager->getWindows();
vector<GHOST_IWindow *>::iterator win_it= win_vec.begin();
vector<GHOST_IWindow *>::const_iterator win_end= win_vec.end();
for (; win_it != win_end; ++win_it) {
GHOST_WindowSDL * window= static_cast<GHOST_WindowSDL *>(*win_it);
if (window->getSDLWindow() == sdl_win) {
return window;
}
}
return NULL;
}
void
GHOST_SystemSDL::addDirtyWindow(GHOST_WindowSDL *bad_wind)
{
GHOST_ASSERT((bad_wind != NULL), "addDirtyWindow() NULL ptr trapped (window)");
m_dirty_windows.push_back(bad_wind);
}
GHOST_TSuccess GHOST_SystemSDL::getButtons(GHOST_Buttons& buttons) const
{
Uint8 state= SDL_GetMouseState(NULL, NULL);
buttons.set(GHOST_kButtonMaskLeft, (state & SDL_BUTTON_LMASK) != 0);
buttons.set(GHOST_kButtonMaskMiddle, (state & SDL_BUTTON_MMASK) != 0);
buttons.set(GHOST_kButtonMaskRight, (state & SDL_BUTTON_RMASK) != 0);
return GHOST_kSuccess;
}
GHOST_TUns8 *
GHOST_SystemSDL::getClipboard(bool selection) const
{
return (GHOST_TUns8 *)SDL_GetClipboardText();
}
void
GHOST_SystemSDL::putClipboard(GHOST_TInt8 *buffer, bool selection) const
{
SDL_SetClipboardText(buffer);
}
GHOST_TUns64
GHOST_SystemSDL::getMilliSeconds()
{
return GHOST_TUns64(SDL_GetTicks()); /* note, 32 -> 64bits */
}

View File

@@ -0,0 +1,126 @@
/*
* $Id$
* ***** BEGIN GPL LICENSE BLOCK *****
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* Contributor(s): Campbell Barton
*
* ***** END GPL LICENSE BLOCK *****
*/
/** \file ghost/intern/GHOST_SystemSDL.h
* \ingroup GHOST
* Declaration of GHOST_SystemSDL class.
*/
#ifndef _GHOST_SYSTEM_SDL_H_
#define _GHOST_SYSTEM_SDL_H_
#include "GHOST_System.h"
#include "../GHOST_Types.h"
#include "GHOST_DisplayManagerSDL.h"
#include "GHOST_TimerManager.h"
#include "GHOST_WindowSDL.h"
#include "GHOST_Event.h"
extern "C" {
#include "SDL.h"
}
#if !SDL_VERSION_ATLEAST(1, 3, 0)
# error "SDL 1.3 or newer is needed to build with Ghost"
#endif
class GHOST_WindowSDL;
class GHOST_SystemSDL : public GHOST_System {
public:
void addDirtyWindow(GHOST_WindowSDL *bad_wind);
GHOST_SystemSDL();
~GHOST_SystemSDL();
bool
processEvents(bool waitForEvent);
int
toggleConsole(int action) { return 0; }
GHOST_TSuccess
getModifierKeys(GHOST_ModifierKeys& keys) const;
GHOST_TSuccess
getButtons(GHOST_Buttons& buttons) const;
GHOST_TUns8 *
getClipboard(bool selection) const;
void
putClipboard(GHOST_TInt8 *buffer, bool selection) const;
GHOST_TUns64
getMilliSeconds();
GHOST_TUns8
getNumDisplays() const;
GHOST_TSuccess
getCursorPosition(GHOST_TInt32& x,
GHOST_TInt32& y) const;
GHOST_TSuccess
setCursorPosition(GHOST_TInt32 x,
GHOST_TInt32 y);
void
getMainDisplayDimensions(GHOST_TUns32& width,
GHOST_TUns32& height) const;
private:
GHOST_TSuccess
init();
GHOST_IWindow *
createWindow(const STR_String& title,
GHOST_TInt32 left,
GHOST_TInt32 top,
GHOST_TUns32 width,
GHOST_TUns32 height,
GHOST_TWindowState state,
GHOST_TDrawingContextType type,
bool stereoVisual,
const GHOST_TUns16 numOfAASamples,
const GHOST_TEmbedderWindowID parentWindow
);
/* SDL spesific */
GHOST_WindowSDL * findGhostWindow(SDL_Window *sdl_win);
bool
generateWindowExposeEvents();
void
processEvent(SDL_Event *sdl_event);
/// The vector of windows that need to be updated.
std::vector<GHOST_WindowSDL *> m_dirty_windows;
};
#endif

View File

@@ -763,7 +763,7 @@ GHOST_EventKey* GHOST_SystemWin32::processKeyEvent(GHOST_IWindow *window, WPARAM
event = new GHOST_EventKey(system->getMilliSeconds(), keyDown ? GHOST_kEventKeyDown: GHOST_kEventKeyUp, window, key, ascii);
#ifdef BF_GHOST_DEBUG
#ifdef GHOST_DEBUG
std::cout << ascii << std::endl;
#endif
}

View File

@@ -76,6 +76,9 @@
#include <stdio.h> // for fprintf only
#include <cstdlib> // for exit
static GHOST_TKey
convertXKey(KeySym key);
typedef struct NDOFPlatformInfo {
Display *display;
Window window;
@@ -147,8 +150,9 @@ GHOST_SystemX11(
if (gettimeofday(&tv,NULL) == -1) {
GHOST_ASSERT(false,"Could not instantiate timer!");
}
m_start_time = GHOST_TUns64(tv.tv_sec*1000 + tv.tv_usec/1000);
// Taking care not to overflow the tv.tv_sec*1000
m_start_time = GHOST_TUns64(tv.tv_sec)*1000 + tv.tv_usec/1000;
/* use detectable autorepeate, mac and windows also do this */
@@ -196,7 +200,8 @@ getMilliSeconds(
GHOST_ASSERT(false,"Could not compute time!");
}
return GHOST_TUns64(tv.tv_sec*1000 + tv.tv_usec/1000) - m_start_time;
// Taking care not to overflow the tv.tv_sec*1000
return GHOST_TUns64(tv.tv_sec)*1000 + tv.tv_usec/1000 - m_start_time;
}
GHOST_TUns8
@@ -856,60 +861,28 @@ getModifierKeys(
// now translate key symobols into keycodes and
// test with vector.
const KeyCode shift_l = XKeysymToKeycode(m_display,XK_Shift_L);
const KeyCode shift_r = XKeysymToKeycode(m_display,XK_Shift_R);
const KeyCode control_l = XKeysymToKeycode(m_display,XK_Control_L);
const KeyCode control_r = XKeysymToKeycode(m_display,XK_Control_R);
const KeyCode alt_l = XKeysymToKeycode(m_display,XK_Alt_L);
const KeyCode alt_r = XKeysymToKeycode(m_display,XK_Alt_R);
const KeyCode super_l = XKeysymToKeycode(m_display,XK_Super_L);
const KeyCode super_r = XKeysymToKeycode(m_display,XK_Super_R);
const static KeyCode shift_l = XKeysymToKeycode(m_display,XK_Shift_L);
const static KeyCode shift_r = XKeysymToKeycode(m_display,XK_Shift_R);
const static KeyCode control_l = XKeysymToKeycode(m_display,XK_Control_L);
const static KeyCode control_r = XKeysymToKeycode(m_display,XK_Control_R);
const static KeyCode alt_l = XKeysymToKeycode(m_display,XK_Alt_L);
const static KeyCode alt_r = XKeysymToKeycode(m_display,XK_Alt_R);
const static KeyCode super_l = XKeysymToKeycode(m_display,XK_Super_L);
const static KeyCode super_r = XKeysymToKeycode(m_display,XK_Super_R);
// Shift
if ((m_keyboard_vector[shift_l >> 3] >> (shift_l & 7)) & 1) {
keys.set(GHOST_kModifierKeyLeftShift,true);
} else {
keys.set(GHOST_kModifierKeyLeftShift,false);
}
if ((m_keyboard_vector[shift_r >> 3] >> (shift_r & 7)) & 1) {
// shift
keys.set(GHOST_kModifierKeyLeftShift, ((m_keyboard_vector[shift_l >> 3] >> (shift_l & 7)) & 1) != 0);
keys.set(GHOST_kModifierKeyRightShift, ((m_keyboard_vector[shift_r >> 3] >> (shift_r & 7)) & 1) != 0);
// control
keys.set(GHOST_kModifierKeyLeftControl, ((m_keyboard_vector[control_l >> 3] >> (control_l & 7)) & 1) != 0);
keys.set(GHOST_kModifierKeyRightControl, ((m_keyboard_vector[control_r >> 3] >> (control_r & 7)) & 1) != 0);
// alt
keys.set(GHOST_kModifierKeyLeftAlt, ((m_keyboard_vector[alt_l >> 3] >> (alt_l & 7)) & 1) != 0);
keys.set(GHOST_kModifierKeyRightAlt, ((m_keyboard_vector[alt_r >> 3] >> (alt_r & 7)) & 1) != 0);
// super (windows) - only one GHOST-kModifierKeyOS, so mapping to either
keys.set(GHOST_kModifierKeyOS, ( ((m_keyboard_vector[super_l >> 3] >> (super_l & 7)) & 1) ||
((m_keyboard_vector[super_r >> 3] >> (super_r & 7)) & 1) ) != 0);
keys.set(GHOST_kModifierKeyRightShift,true);
} else {
keys.set(GHOST_kModifierKeyRightShift,false);
}
// control (weep)
if ((m_keyboard_vector[control_l >> 3] >> (control_l & 7)) & 1) {
keys.set(GHOST_kModifierKeyLeftControl,true);
} else {
keys.set(GHOST_kModifierKeyLeftControl,false);
}
if ((m_keyboard_vector[control_r >> 3] >> (control_r & 7)) & 1) {
keys.set(GHOST_kModifierKeyRightControl,true);
} else {
keys.set(GHOST_kModifierKeyRightControl,false);
}
// Alt (yawn)
if ((m_keyboard_vector[alt_l >> 3] >> (alt_l & 7)) & 1) {
keys.set(GHOST_kModifierKeyLeftAlt,true);
} else {
keys.set(GHOST_kModifierKeyLeftAlt,false);
}
if ((m_keyboard_vector[alt_r >> 3] >> (alt_r & 7)) & 1) {
keys.set(GHOST_kModifierKeyRightAlt,true);
} else {
keys.set(GHOST_kModifierKeyRightAlt,false);
}
// Super (Windows) - only one GHOST-kModifierKeyOS, so mapping
// to either
if ( ((m_keyboard_vector[super_l >> 3] >> (super_l & 7)) & 1) ||
((m_keyboard_vector[super_r >> 3] >> (super_r & 7)) & 1) ) {
keys.set(GHOST_kModifierKeyOS,true);
} else {
keys.set(GHOST_kModifierKeyOS,false);
}
return GHOST_kSuccess;
}
@@ -923,35 +896,20 @@ getButtons(
int rx,ry,wx,wy;
unsigned int mask_return;
if (XQueryPointer(
m_display,
RootWindow(m_display,DefaultScreen(m_display)),
&root_return,
&child_return,
&rx,&ry,
&wx,&wy,
&mask_return
) == False) {
if (XQueryPointer(m_display,
RootWindow(m_display,DefaultScreen(m_display)),
&root_return,
&child_return,
&rx,&ry,
&wx,&wy,
&mask_return) == True)
{
buttons.set(GHOST_kButtonMaskLeft, (mask_return & Button1Mask) != 0);
buttons.set(GHOST_kButtonMaskMiddle, (mask_return & Button2Mask) != 0);
buttons.set(GHOST_kButtonMaskRight, (mask_return & Button3Mask) != 0);
}
else {
return GHOST_kFailure;
} else {
if (mask_return & Button1Mask) {
buttons.set(GHOST_kButtonMaskLeft,true);
} else {
buttons.set(GHOST_kButtonMaskLeft,false);
}
if (mask_return & Button2Mask) {
buttons.set(GHOST_kButtonMaskMiddle,true);
} else {
buttons.set(GHOST_kButtonMaskMiddle,false);
}
if (mask_return & Button3Mask) {
buttons.set(GHOST_kButtonMaskRight,true);
} else {
buttons.set(GHOST_kButtonMaskRight,false);
}
}
return GHOST_kSuccess;
@@ -1056,11 +1014,9 @@ generateWindowExposeEvents(
#define GXMAP(k,x,y) case x: k = y; break;
GHOST_TKey
GHOST_SystemX11::
convertXKey(
KeySym key
){
static GHOST_TKey
convertXKey(KeySym key)
{
GHOST_TKey type;
if ((key >= XK_A) && (key <= XK_Z)) {
@@ -1175,7 +1131,9 @@ convertXKey(
GXMAP(type,XF86XK_AudioPrev, GHOST_kKeyMediaFirst);
GXMAP(type,XF86XK_AudioRewind, GHOST_kKeyMediaFirst);
GXMAP(type,XF86XK_AudioNext, GHOST_kKeyMediaLast);
#ifdef XF86XK_AudioForward /* Debian lenny's XF86keysym.h has no XF86XK_AudioForward define */
GXMAP(type,XF86XK_AudioForward, GHOST_kKeyMediaLast);
#endif
#endif
/* some extra sun cruft (NICE KEYBOARD!) */

View File

@@ -300,12 +300,6 @@ private :
bool
generateWindowExposeEvents(
);
GHOST_TKey
convertXKey(
KeySym key
);
};
#endif

View File

@@ -42,6 +42,7 @@
#include "STR_String.h"
@class CocoaWindow;
@class CocoaOpenGLView;
class GHOST_SystemCocoa;
@@ -180,6 +181,26 @@ public:
*/
virtual void clientToScreen(GHOST_TInt32 inX, GHOST_TInt32 inY, GHOST_TInt32& outX, GHOST_TInt32& outY) const;
/**
* Converts a point in screen coordinates to client rectangle coordinates
* but without the y coordinate conversion needed for ghost compatibility.
* @param inX The x-coordinate in the client rectangle.
* @param inY The y-coordinate in the client rectangle.
* @param outX The x-coordinate on the screen.
* @param outY The y-coordinate on the screen.
*/
void clientToScreenIntern(GHOST_TInt32 inX, GHOST_TInt32 inY, GHOST_TInt32& outX, GHOST_TInt32& outY) const;
/**
* Converts a point in screen coordinates to client rectangle coordinates,
* but without the y coordinate conversion needed for ghost compatibility.
* @param inX The x-coordinate in the client rectangle.
* @param inY The y-coordinate in the client rectangle.
* @param outX The x-coordinate on the screen.
* @param outY The y-coordinate on the screen.
*/
void screenToClientIntern(GHOST_TInt32 inX, GHOST_TInt32 inY, GHOST_TInt32& outX, GHOST_TInt32& outY) const;
/**
* Gets the screen the window is displayed in
* @return The NSScreen object
@@ -289,7 +310,7 @@ protected:
CocoaWindow *m_window;
/** The openGL view */
NSOpenGLView *m_openGLView;
CocoaOpenGLView *m_openGLView;
/** The opgnGL drawing context */
NSOpenGLContext *m_openGLContext;

View File

@@ -241,10 +241,19 @@ extern "C" {
//We need to subclass it in order to give Cocoa the feeling key events are trapped
@interface CocoaOpenGLView : NSOpenGLView
{
GHOST_SystemCocoa *systemCocoa;
GHOST_WindowCocoa *associatedWindow;
}
- (void)setSystemAndWindowCocoa:(GHOST_SystemCocoa *)sysCocoa windowCocoa:(GHOST_WindowCocoa *)winCocoa;
@end
@implementation CocoaOpenGLView
- (void)setSystemAndWindowCocoa:(GHOST_SystemCocoa *)sysCocoa windowCocoa:(GHOST_WindowCocoa *)winCocoa
{
systemCocoa = sysCocoa;
associatedWindow = winCocoa;
}
- (BOOL)acceptsFirstResponder
{
return YES;
@@ -294,6 +303,7 @@ extern "C" {
else
{
[super drawRect:rect];
systemCocoa->handleWindowEvent(GHOST_kEventWindowUpdate, associatedWindow);
}
}
@@ -424,6 +434,8 @@ GHOST_WindowCocoa::GHOST_WindowCocoa(
//Creates the OpenGL View inside the window
m_openGLView = [[CocoaOpenGLView alloc] initWithFrame:rect
pixelFormat:pixelFormat];
[m_openGLView setSystemAndWindowCocoa:systemCocoa windowCocoa:this];
[pixelFormat release];
@@ -691,17 +703,8 @@ GHOST_TWindowState GHOST_WindowCocoa::getState() const
void GHOST_WindowCocoa::screenToClient(GHOST_TInt32 inX, GHOST_TInt32 inY, GHOST_TInt32& outX, GHOST_TInt32& outY) const
{
GHOST_ASSERT(getValid(), "GHOST_WindowCocoa::screenToClient(): window invalid")
NSPoint screenCoord;
NSPoint baseCoord;
screenCoord.x = inX;
screenCoord.y = inY;
baseCoord = [m_window convertScreenToBase:screenCoord];
outX = baseCoord.x;
outY = baseCoord.y;
screenToClientIntern(inX, inY, outX, outY);
/* switch y to match ghost convention */
GHOST_Rect cBnds;
@@ -718,7 +721,26 @@ void GHOST_WindowCocoa::clientToScreen(GHOST_TInt32 inX, GHOST_TInt32 inY, GHOST
GHOST_Rect cBnds;
getClientBounds(cBnds);
inY = (cBnds.getHeight() - 1) - inY;
clientToScreenIntern(inX, inY, outX, outY);
}
void GHOST_WindowCocoa::screenToClientIntern(GHOST_TInt32 inX, GHOST_TInt32 inY, GHOST_TInt32& outX, GHOST_TInt32& outY) const
{
NSPoint screenCoord;
NSPoint baseCoord;
screenCoord.x = inX;
screenCoord.y = inY;
baseCoord = [m_window convertScreenToBase:screenCoord];
outX = baseCoord.x;
outY = baseCoord.y;
}
void GHOST_WindowCocoa::clientToScreenIntern(GHOST_TInt32 inX, GHOST_TInt32 inY, GHOST_TInt32& outX, GHOST_TInt32& outY) const
{
NSPoint screenCoord;
NSPoint baseCoord;
@@ -1220,7 +1242,7 @@ GHOST_TSuccess GHOST_WindowCocoa::setWindowCursorGrab(GHOST_TGrabCursorMode mode
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
m_systemCocoa->getCursorPosition(x_old,y_old);
screenToClient(x_old, y_old, m_cursorGrabInitPos[0], m_cursorGrabInitPos[1]);
screenToClientIntern(x_old, y_old, m_cursorGrabInitPos[0], m_cursorGrabInitPos[1]);
//Warp position is stored in client (window base) coordinates
setCursorGrabAccum(0, 0);

View File

@@ -54,7 +54,7 @@ public:
const bool stereoVisual,
const GHOST_TUns16 numOfAASamples
) :
GHOST_Window(title,left,top,width,height,state,type,stereoVisual,numOfAASamples),
GHOST_Window(width,height,state,type,stereoVisual,numOfAASamples),
m_system (system)
{
setTitle(title);

View File

@@ -0,0 +1,628 @@
/*
* $Id$
* ***** BEGIN GPL LICENSE BLOCK *****
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* Contributor(s): Campbell Barton
*
* ***** END GPL LICENSE BLOCK *****
*/
/** \file ghost/intern/GHOST_WindowSDL.cpp
* \ingroup GHOST
*/
#include "GHOST_WindowSDL.h"
#include "SDL_mouse.h"
#include <assert.h>
static SDL_GLContext s_firstContext= NULL;
GHOST_WindowSDL::GHOST_WindowSDL(GHOST_SystemSDL *system,
const STR_String& title,
GHOST_TInt32 left,
GHOST_TInt32 top,
GHOST_TUns32 width,
GHOST_TUns32 height,
GHOST_TWindowState state,
const GHOST_TEmbedderWindowID parentWindow,
GHOST_TDrawingContextType type,
const bool stereoVisual,
const GHOST_TUns16 numOfAASamples
)
:
GHOST_Window(width,height,state,type,stereoVisual,numOfAASamples),
m_system (system),
m_invalid_window(false),
m_sdl_custom_cursor(NULL)
{
m_sdl_win= SDL_CreateWindow(title,
left,
top,
width,
height,
SDL_WINDOW_RESIZABLE|SDL_WINDOW_OPENGL|SDL_WINDOW_SHOWN);
//SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
//SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 4);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
m_sdl_glcontext= SDL_GL_CreateContext(m_sdl_win);
//fprintf(stderr, "Ignoring Xlib error: error code %d request code %d\n",
// theEvent->error_code, theEvent->request_code) ;
setTitle(title);
}
GHOST_WindowSDL::~GHOST_WindowSDL()
{
if(m_sdl_custom_cursor) {
SDL_FreeCursor(m_sdl_custom_cursor);
}
if (m_sdl_glcontext != s_firstContext) {
SDL_GL_DeleteContext(m_sdl_glcontext);
}
SDL_DestroyWindow(m_sdl_win);
}
GHOST_TSuccess
GHOST_WindowSDL::installDrawingContext(GHOST_TDrawingContextType type)
{
// only support openGL for now.
GHOST_TSuccess success;
switch (type) {
case GHOST_kDrawingContextTypeOpenGL:
m_sdl_glcontext= SDL_GL_CreateContext(m_sdl_win);
if (m_sdl_glcontext != NULL) {
if (!s_firstContext) {
s_firstContext= m_sdl_glcontext;
}
success= (SDL_GL_MakeCurrent(m_sdl_win, m_sdl_glcontext) < 0) ?
GHOST_kFailure : GHOST_kSuccess;
}
else {
success= GHOST_kFailure;
}
break;
case GHOST_kDrawingContextTypeNone:
success= GHOST_kSuccess;
break;
default:
success= GHOST_kFailure;
}
return success;
}
GHOST_TSuccess
GHOST_WindowSDL::invalidate(void)
{
// So the idea of this function is to generate an expose event
// for the window.
// Unfortunately X does not handle expose events for you and
// it is the client's job to refresh the dirty part of the window.
// We need to queue up invalidate calls and generate GHOST events
// for them in the system.
// We implement this by setting a boolean in this class to concatenate
// all such calls into a single event for this window.
// At the same time we queue the dirty windows in the system class
// and generate events for them at the next processEvents call.
if (m_invalid_window == false) {
m_system->addDirtyWindow(this);
m_invalid_window= true;
}
return GHOST_kSuccess;
}
GHOST_TSuccess
GHOST_WindowSDL::swapBuffers()
{
if (getDrawingContextType() == GHOST_kDrawingContextTypeOpenGL) {
SDL_GL_SwapWindow(m_sdl_win);
return GHOST_kSuccess;
}
else {
return GHOST_kFailure;
}
}
GHOST_TSuccess
GHOST_WindowSDL::activateDrawingContext()
{
if (m_sdl_glcontext !=NULL) {
int status=SDL_GL_MakeCurrent(m_sdl_win, m_sdl_glcontext);
(void)status;
return GHOST_kSuccess;
}
return GHOST_kFailure;
}
GHOST_TSuccess
GHOST_WindowSDL::removeDrawingContext()
{
GHOST_TSuccess success;
if (m_sdl_glcontext != NULL) {
SDL_GL_DeleteContext(m_sdl_glcontext);
success= GHOST_kSuccess;
}
else {
success= GHOST_kFailure;
}
return success;
}
GHOST_TSuccess
GHOST_WindowSDL::setState(GHOST_TWindowState state)
{
switch(state) {
case GHOST_kWindowStateNormal:
SDL_SetWindowFullscreen(m_sdl_win, SDL_FALSE);
SDL_RestoreWindow(m_sdl_win);
break;
case GHOST_kWindowStateMaximized:
SDL_SetWindowFullscreen(m_sdl_win, SDL_FALSE);
SDL_MaximizeWindow(m_sdl_win);
break;
case GHOST_kWindowStateMinimized:
SDL_MinimizeWindow(m_sdl_win);
break;
case GHOST_kWindowStateFullScreen:
SDL_SetWindowFullscreen(m_sdl_win, SDL_TRUE);
break;
default:
break;
}
return GHOST_kSuccess;
}
GHOST_TWindowState
GHOST_WindowSDL::getState() const
{
Uint32 flags= SDL_GetWindowFlags(m_sdl_win);
if(flags & SDL_WINDOW_FULLSCREEN) return GHOST_kWindowStateFullScreen;
else if(flags & SDL_WINDOW_MAXIMIZED) return GHOST_kWindowStateMaximized;
else if(flags & SDL_WINDOW_MINIMIZED) return GHOST_kWindowStateMinimized;
return GHOST_kWindowStateNormal;
}
void
GHOST_WindowSDL::setTitle(const STR_String& title)
{
SDL_SetWindowTitle(m_sdl_win, title.ReadPtr());
}
void
GHOST_WindowSDL::getTitle(STR_String& title) const
{
title= SDL_GetWindowTitle(m_sdl_win);
}
void
GHOST_WindowSDL::getWindowBounds(GHOST_Rect& bounds) const
{
getClientBounds(bounds);
}
void
GHOST_WindowSDL::getClientBounds(GHOST_Rect& bounds) const
{
int x, y, w, h;
SDL_GetWindowSize(m_sdl_win, &w, &h);
SDL_GetWindowPosition(m_sdl_win, &x, &y);
bounds.m_l= x;
bounds.m_r= x + w;
bounds.m_t= y;
bounds.m_b= y + h;
}
GHOST_TSuccess
GHOST_WindowSDL::setClientWidth(GHOST_TUns32 width)
{
int height;
SDL_GetWindowSize(m_sdl_win, NULL, &height);
SDL_SetWindowSize(m_sdl_win, width, height);
return GHOST_kSuccess;
}
GHOST_TSuccess
GHOST_WindowSDL::setClientHeight(GHOST_TUns32 height)
{
int width;
SDL_GetWindowSize(m_sdl_win, &width, NULL);
SDL_SetWindowSize(m_sdl_win, width, height);
return GHOST_kSuccess;
}
GHOST_TSuccess
GHOST_WindowSDL::setClientSize(GHOST_TUns32 width,
GHOST_TUns32 height)
{
SDL_SetWindowSize(m_sdl_win, width, height);
return GHOST_kSuccess;
}
void
GHOST_WindowSDL::screenToClient( GHOST_TInt32 inX, GHOST_TInt32 inY, GHOST_TInt32& outX, GHOST_TInt32& outY ) const
{
/* XXXSDL_WEAK_ABS_COORDS */
int x_win, y_win;
SDL_GetWindowPosition(m_sdl_win, &x_win, &y_win);
outX = inX - x_win;
outY = inY - y_win;
}
void
GHOST_WindowSDL::clientToScreen( GHOST_TInt32 inX, GHOST_TInt32 inY, GHOST_TInt32& outX, GHOST_TInt32& outY ) const
{
/* XXXSDL_WEAK_ABS_COORDS */
int x_win, y_win;
SDL_GetWindowPosition(m_sdl_win, &x_win, &y_win);
outX = inX + x_win;
outY = inY + y_win;
}
/* mouse cursor */
static unsigned char sdl_std_cursor_mask_xterm[]= {0xef,0x01,0xff,0x01,0xff,0x01,0x7c,0x00,0x38,0x00,0x38,0x00,0x38,0x00,0x38,0x00,0x38,0x00,0x38,0x00,0x38,0x00,0x38,0x00,0x7c,0x00,0xff,0x01,0xff,0x01,0xef,0x01,};
static unsigned char sdl_std_cursor_xterm[]= {0x00,0x77,0x00,0x1c,0x00,0x08,0x00,0x08,0x00,0x08,0x00,0x08,0x00,0x08,0x00,0x08,0x00,0x08,0x00,0x08,0x00,0x08,0x00,0x08,0x00,0x1c,0x00,0x77,0x00,0x00,0x00,0x00,};
#define sdl_std_cursor_WIDTH_xterm 9
#define sdl_std_cursor_HEIGHT_xterm 16
#define sdl_std_cursor_HOT_X_xterm -3
#define sdl_std_cursor_HOT_Y_xterm -7
static unsigned char sdl_std_cursor_mask_watch[]= {0xfc,0x0f,0xfc,0x0f,0xfc,0x0f,0xfe,0x1f,0xff,0x3f,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x3f,0xfe,0x1f,0xfc,0x0f,0xfc,0x0f,0xfc,0x0f,};
static unsigned char sdl_std_cursor_watch[]= {0xf8,0x07,0xf8,0x07,0xf8,0x07,0xfc,0x0f,0x86,0x18,0x83,0x30,0x81,0xe0,0xc1,0xe1,0xc1,0xe1,0x21,0xe0,0x13,0x30,0x06,0x18,0xfc,0x0f,0xf8,0x07,0xf8,0x07,0xf8,0x07,};
#define sdl_std_cursor_WIDTH_watch 16
#define sdl_std_cursor_HEIGHT_watch 16
#define sdl_std_cursor_HOT_X_watch -15
#define sdl_std_cursor_HOT_Y_watch -7
static unsigned char sdl_std_cursor_mask_umbrella[]= {0xe8,0x76,0xfb,0xdf,0xfd,0x3f,0xfe,0xff,0xff,0x3f,0xff,0xff,0xcf,0x79,0xc0,0x01,0xc0,0x01,0xc0,0x01,0xc0,0x01,0xc0,0x07,0xc0,0x07,0xc0,0x07,0xc0,0x07,0x80,0x03,};
static unsigned char sdl_std_cursor_umbrella[]= {0x88,0x04,0x20,0x0a,0xc9,0x32,0xf2,0x09,0x4c,0x06,0x43,0x18,0x40,0x00,0x40,0x00,0x40,0x00,0x40,0x00,0x40,0x00,0x40,0x01,0x40,0x01,0x80,0x00,0x00,0x00,0x00,0x00,};
#define sdl_std_cursor_WIDTH_umbrella 16
#define sdl_std_cursor_HEIGHT_umbrella 16
#define sdl_std_cursor_HOT_X_umbrella -7
#define sdl_std_cursor_HOT_Y_umbrella -12
static unsigned char sdl_std_cursor_mask_top_side[]= {0xff,0x7f,0xff,0x7f,0xff,0x7f,0xff,0x7f,0xc0,0x01,0xe0,0x03,0xf0,0x07,0xf8,0x0f,0xdc,0x1d,0xcc,0x19,0xc0,0x01,0xc0,0x01,0xc0,0x01,0xc0,0x01,0xc0,0x01,0xc0,0x01,};
static unsigned char sdl_std_cursor_top_side[]= {0xff,0x1f,0xff,0x1f,0x00,0x00,0x40,0x00,0xe0,0x00,0x50,0x01,0x48,0x02,0x44,0x04,0x40,0x00,0x40,0x00,0x40,0x00,0x40,0x00,0x40,0x00,0x40,0x00,0x00,0x00,0x00,0x00,};
#define sdl_std_cursor_WIDTH_top_side 15
#define sdl_std_cursor_HEIGHT_top_side 16
#define sdl_std_cursor_HOT_X_top_side -6
#define sdl_std_cursor_HOT_Y_top_side -14
static unsigned char sdl_std_cursor_mask_top_right_corner[]= {0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x00,0xf0,0xfc,0xf7,0xfc,0xf7,0xfc,0xf7,0xc0,0xf7,0xe0,0xf7,0x70,0xf7,0x38,0xf7,0x1c,0xf7,0x0c,0xf7,0x00,0xf0,0x00,0xf0,};
static unsigned char sdl_std_cursor_top_right_corner[]= {0xff,0x3f,0xff,0x3f,0x00,0x30,0x00,0x30,0x00,0x30,0xfc,0x31,0x80,0x31,0x40,0x31,0x20,0x31,0x10,0x31,0x08,0x31,0x04,0x31,0x00,0x30,0x00,0x30,0x00,0x00,0x00,0x00,};
#define sdl_std_cursor_WIDTH_top_right_corner 16
#define sdl_std_cursor_HEIGHT_top_right_corner 16
#define sdl_std_cursor_HOT_X_top_right_corner -13
#define sdl_std_cursor_HOT_Y_top_right_corner -14
static unsigned char sdl_std_cursor_mask_top_left_corner[]= {0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x0f,0x00,0xef,0x3f,0xef,0x3f,0xef,0x3f,0xef,0x03,0xef,0x07,0xef,0x0e,0xef,0x1c,0xef,0x38,0xef,0x30,0x0f,0x00,0x0f,0x00,};
static unsigned char sdl_std_cursor_top_left_corner[]= {0xff,0x3f,0xff,0x3f,0x03,0x00,0x03,0x00,0x03,0x00,0xe3,0x0f,0x63,0x00,0xa3,0x00,0x23,0x01,0x23,0x02,0x23,0x04,0x23,0x08,0x03,0x00,0x03,0x00,0x00,0x00,0x00,0x00,};
#define sdl_std_cursor_WIDTH_top_left_corner 16
#define sdl_std_cursor_HEIGHT_top_left_corner 16
#define sdl_std_cursor_HOT_X_top_left_corner 0
#define sdl_std_cursor_HOT_Y_top_left_corner -14
static unsigned char sdl_std_cursor_mask_spraycan[]= {0x00,0x0c,0x18,0x0d,0x7c,0x0d,0x7c,0x0d,0x7e,0x0d,0xff,0x00,0xff,0x00,0xff,0x00,0xff,0x00,0xff,0x00,0xff,0x00,0xff,0x00,0xff,0x00,0xff,0x00,0xff,0x00,0xff,0x00,};
static unsigned char sdl_std_cursor_spraycan[]= {0x00,0x06,0x80,0x00,0x2c,0x06,0x9e,0x00,0x16,0x06,0x3f,0x00,0x21,0x00,0x27,0x00,0x25,0x00,0x27,0x00,0x25,0x00,0x27,0x00,0x27,0x00,0x21,0x00,0x21,0x00,0x3f,0x00,};
#define sdl_std_cursor_WIDTH_spraycan 12
#define sdl_std_cursor_HEIGHT_spraycan 16
#define sdl_std_cursor_HOT_X_spraycan -9
#define sdl_std_cursor_HOT_Y_spraycan -14
static unsigned char sdl_std_cursor_mask_sb_v_double_arrow[]= {0x38,0x00,0x7c,0x00,0xfe,0x00,0xff,0x01,0xff,0x01,0x7c,0x00,0x7c,0x00,0x7c,0x00,0x7c,0x00,0x7c,0x00,0xff,0x01,0xff,0x01,0xfe,0x00,0x7c,0x00,0x38,0x00,};
static unsigned char sdl_std_cursor_sb_v_double_arrow[]= {0x10,0x00,0x38,0x00,0x7c,0x00,0xfe,0x00,0x28,0x00,0x28,0x00,0x28,0x00,0x28,0x00,0x28,0x00,0x28,0x00,0x28,0x00,0xfe,0x00,0x7c,0x00,0x38,0x00,0x10,0x00,};
#define sdl_std_cursor_WIDTH_sb_v_double_arrow 9
#define sdl_std_cursor_HEIGHT_sb_v_double_arrow 15
#define sdl_std_cursor_HOT_X_sb_v_double_arrow -3
#define sdl_std_cursor_HOT_Y_sb_v_double_arrow -8
static unsigned char sdl_std_cursor_mask_sb_h_double_arrow[]= {0x18,0x0c,0x1c,0x1c,0xfe,0x3f,0xff,0x7f,0xff,0x7f,0xff,0x7f,0xfe,0x3f,0x1c,0x1c,0x18,0x0c,};
static unsigned char sdl_std_cursor_sb_h_double_arrow[]= {0x00,0x00,0x08,0x08,0x0c,0x18,0xfe,0x3f,0x0f,0x78,0xfe,0x3f,0x0c,0x18,0x08,0x08,0x00,0x00};
#define sdl_std_cursor_WIDTH_sb_h_double_arrow 15
#define sdl_std_cursor_HEIGHT_sb_h_double_arrow 9
#define sdl_std_cursor_HOT_X_sb_h_double_arrow -7
#define sdl_std_cursor_HOT_Y_sb_h_double_arrow -4
static unsigned char sdl_std_cursor_mask_right_side[]= {0x00,0xf0,0x00,0xf0,0xc0,0xf0,0xc0,0xf1,0x80,0xf3,0x00,0xf7,0xff,0xff,0xff,0xff,0xff,0xff,0x00,0xf7,0x80,0xf3,0xc0,0xf1,0xc0,0xf0,0x00,0xf0,0x00,0xf0,};
static unsigned char sdl_std_cursor_right_side[]= {0x00,0x30,0x00,0x30,0x40,0x30,0x80,0x30,0x00,0x31,0x00,0x32,0xff,0x37,0x00,0x32,0x00,0x31,0x80,0x30,0x40,0x30,0x00,0x30,0x00,0x30,0x00,0x00,0x00,0x00,};
#define sdl_std_cursor_WIDTH_right_side 16
#define sdl_std_cursor_HEIGHT_right_side 15
#define sdl_std_cursor_HOT_X_right_side -13
#define sdl_std_cursor_HOT_Y_right_side -7
static unsigned char sdl_std_cursor_mask_right_ptr[]= {0x00,0x03,0x80,0x03,0xc0,0x03,0xe0,0x03,0xf0,0x03,0xf8,0x03,0xfc,0x03,0xfe,0x03,0xff,0x03,0xff,0x03,0xf8,0x03,0xbc,0x03,0x3c,0x03,0x1e,0x00,0x1e,0x00,0x0c,0x00,};
static unsigned char sdl_std_cursor_right_ptr[]= {0x00,0x80,0x00,0xc0,0x00,0xe0,0x00,0xf0,0x00,0xf8,0x00,0xfc,0x00,0xfe,0x00,0xff,0x00,0xf8,0x00,0xd8,0x00,0x8c,0x00,0x0c,0x00,0x06,0x00,0x06,0x00,0x00,0x00,0x00,};
#define sdl_std_cursor_WIDTH_right_ptr 10
#define sdl_std_cursor_HEIGHT_right_ptr 16
#define sdl_std_cursor_HOT_X_right_ptr -7
#define sdl_std_cursor_HOT_Y_right_ptr -14
static unsigned char sdl_std_cursor_mask_question_arrow[]= {0xf8,0x00,0xfc,0x01,0xfe,0x03,0xff,0x07,0x8f,0x07,0x9f,0x07,0xde,0x07,0xfc,0x03,0xf8,0x01,0xf8,0x00,0xf8,0x00,0xfc,0x01,0xfe,0x03,0xfc,0x01,0xf8,0x00,0x70,0x00,};
static unsigned char sdl_std_cursor_question_arrow[]= {0x7c,0x00,0xfe,0x00,0xc7,0x01,0x83,0x01,0x87,0x01,0xc6,0x01,0xe0,0x00,0x78,0x00,0x38,0x00,0x28,0x00,0x28,0x00,0xee,0x00,0x6c,0x00,0x38,0x00,0x10,0x00,0x00,0x00,};
#define sdl_std_cursor_WIDTH_question_arrow 11
#define sdl_std_cursor_HEIGHT_question_arrow 16
#define sdl_std_cursor_HOT_X_question_arrow -4
#define sdl_std_cursor_HOT_Y_question_arrow -8
static unsigned char sdl_std_cursor_mask_pirate[]= {0xf0,0x03,0xf8,0x07,0xfc,0x0f,0xfe,0x1f,0xfe,0x1f,0xfc,0x0f,0xf8,0x07,0xf1,0x83,0xf1,0xe3,0xf3,0xf3,0xef,0x39,0x1e,0x1e,0xe0,0x01,0xfe,0xc7,0xff,0xff,0x0f,0x7c,};
static unsigned char sdl_std_cursor_pirate[]= {0xe0,0x01,0xf0,0x03,0xf8,0x07,0xcc,0x0c,0xcc,0x0c,0xf8,0x07,0xf0,0x03,0xe0,0x01,0xe1,0x21,0xe1,0x61,0xc2,0x10,0x1c,0x0e,0xe0,0x01,0xf8,0x47,0x0f,0x7c,0x01,0x20,};
#define sdl_std_cursor_WIDTH_pirate 16
#define sdl_std_cursor_HEIGHT_pirate 16
#define sdl_std_cursor_HOT_X_pirate -7
#define sdl_std_cursor_HOT_Y_pirate -4
static unsigned char sdl_std_cursor_mask_left_side[]= {0x0f,0x00,0x0f,0x00,0x0f,0x03,0x8f,0x03,0xcf,0x01,0xef,0x00,0xff,0xff,0xff,0xff,0xff,0xff,0xef,0x00,0xcf,0x01,0x8f,0x03,0x0f,0x03,0x0f,0x00,0x0f,0x00,};
static unsigned char sdl_std_cursor_left_side[]= {0x03,0x00,0x03,0x00,0x83,0x00,0x43,0x00,0x23,0x00,0x13,0x00,0xfb,0x3f,0x13,0x00,0x23,0x00,0x43,0x00,0x83,0x00,0x03,0x00,0x03,0x00,0x00,0x00,0x00,0x00,};
#define sdl_std_cursor_WIDTH_left_side 16
#define sdl_std_cursor_HEIGHT_left_side 15
#define sdl_std_cursor_HOT_X_left_side 0
#define sdl_std_cursor_HOT_Y_left_side -7
static unsigned char sdl_std_cursor_mask_left_ptr[]= {0x03,0x00,0x07,0x00,0x0f,0x00,0x1f,0x00,0x3f,0x00,0x7f,0x00,0xff,0x00,0xff,0x01,0xff,0x03,0xff,0x03,0x7f,0x00,0xf7,0x00,0xf3,0x00,0xe0,0x01,0xe0,0x01,0xc0,0x00,};
static unsigned char sdl_std_cursor_left_ptr[]= {0x00,0x00,0x02,0x00,0x06,0x00,0x0e,0x00,0x1e,0x00,0x3e,0x00,0x7e,0x00,0xfe,0x00,0xfe,0x00,0x3e,0x00,0x36,0x00,0x62,0x00,0x60,0x00,0xc0,0x00,0xc0,0x00,0x00,0x00,};
#define sdl_std_cursor_WIDTH_left_ptr 10
#define sdl_std_cursor_HEIGHT_left_ptr 16
#define sdl_std_cursor_HOT_X_left_ptr -8
#define sdl_std_cursor_HOT_Y_left_ptr -14
static unsigned char sdl_std_cursor_mask_exchange[]= {0xe3,0x07,0xf7,0x0f,0xff,0x1f,0xff,0x3f,0x3f,0x38,0xff,0x30,0xff,0x00,0xff,0x00,0x00,0xff,0x00,0xff,0x0c,0xfe,0x1c,0xfc,0xfc,0xff,0xf8,0xff,0xf0,0xef,0xe0,0xc7,};
static unsigned char sdl_std_cursor_exchange[]= {0xf1,0x03,0xfb,0x07,0x1f,0x0c,0x09,0x08,0x19,0x00,0x3f,0x00,0x00,0x00,0x00,0x00,0x00,0x3f,0x00,0x26,0x04,0x24,0x0c,0x3e,0xf8,0x37,0xf0,0x23,0x00,0x00,0x00,0x00,};
#define sdl_std_cursor_WIDTH_exchange 16
#define sdl_std_cursor_HEIGHT_exchange 16
#define sdl_std_cursor_HOT_X_exchange -6
#define sdl_std_cursor_HOT_Y_exchange -8
static unsigned char sdl_std_cursor_mask_crosshair[]= {0xc0,0x01,0xc0,0x01,0xc0,0x01,0xc0,0x01,0xc0,0x01,0xc0,0x01,0xff,0xff,0xff,0xff,0xff,0xff,0xc0,0x01,0xc0,0x01,0xc0,0x01,0xc0,0x01,0xc0,0x01,0xc0,0x01,0xc0,0x01,};
static unsigned char sdl_std_cursor_crosshair[]= {0x80,0x00,0x80,0x00,0x80,0x00,0x80,0x00,0x80,0x00,0x80,0x00,0x80,0x00,0x7f,0xff,0x80,0x00,0x80,0x00,0x80,0x00,0x80,0x00,0x80,0x00,0x80,0x00,0x80,0x00,0x00,0x00,};
#define sdl_std_cursor_WIDTH_crosshair 16
#define sdl_std_cursor_HEIGHT_crosshair 16
#define sdl_std_cursor_HOT_X_crosshair -7
#define sdl_std_cursor_HOT_Y_crosshair -8
static unsigned char sdl_std_cursor_mask_bottom_side[]= {0xc0,0x01,0xc0,0x01,0xc0,0x01,0xc0,0x01,0xc0,0x01,0xc0,0x01,0xcc,0x19,0xdc,0x1d,0xf8,0x0f,0xf0,0x07,0xe0,0x03,0xc0,0x01,0xff,0x7f,0xff,0x7f,0xff,0x7f,0xff,0x7f,};
static unsigned char sdl_std_cursor_bottom_side[]= {0x40,0x00,0x40,0x00,0x40,0x00,0x40,0x00,0x40,0x00,0x40,0x00,0x44,0x04,0x48,0x02,0x50,0x01,0xe0,0x00,0x40,0x00,0x00,0x00,0xff,0x1f,0xff,0x1f,0x00,0x00,0x00,0x00,};
#define sdl_std_cursor_WIDTH_bottom_side 15
#define sdl_std_cursor_HEIGHT_bottom_side 16
#define sdl_std_cursor_HOT_X_bottom_side -6
#define sdl_std_cursor_HOT_Y_bottom_side -1
static unsigned char sdl_std_cursor_mask_bottom_right_corner[]= {0x00,0xf0,0x00,0xf0,0x0c,0xf7,0x1c,0xf7,0x38,0xf7,0x70,0xf7,0xe0,0xf7,0xc0,0xf7,0xfc,0xf7,0xfc,0xf7,0xfc,0xf7,0x00,0xf0,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,};
static unsigned char sdl_std_cursor_bottom_right_corner[]= {0x00,0x30,0x00,0x30,0x04,0x31,0x08,0x31,0x10,0x31,0x20,0x31,0x40,0x31,0x80,0x31,0xfc,0x31,0x00,0x30,0x00,0x30,0x00,0x30,0xff,0x3f,0xff,0x3f,0x00,0x00,0x00,0x00,};
#define sdl_std_cursor_WIDTH_bottom_right_corner 16
#define sdl_std_cursor_HEIGHT_bottom_right_corner 16
#define sdl_std_cursor_HOT_X_bottom_right_corner -13
#define sdl_std_cursor_HOT_Y_bottom_right_corner -1
static unsigned char sdl_std_cursor_mask_bottom_left_corner[]= {0x0f,0x00,0x0f,0x00,0xef,0x30,0xef,0x38,0xef,0x1c,0xef,0x0e,0xef,0x07,0xef,0x03,0xef,0x3f,0xef,0x3f,0xef,0x3f,0x0f,0x00,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,};
static unsigned char sdl_std_cursor_bottom_left_corner[]= {0x03,0x00,0x03,0x00,0x23,0x08,0x23,0x04,0x23,0x02,0x23,0x01,0xa3,0x00,0x63,0x00,0xe3,0x0f,0x03,0x00,0x03,0x00,0x03,0x00,0xff,0x3f,0xff,0x3f,0x00,0x00,0x00,0x00,};
#define sdl_std_cursor_WIDTH_bottom_left_corner 16
#define sdl_std_cursor_HEIGHT_bottom_left_corner 16
#define sdl_std_cursor_HOT_X_bottom_left_corner 0
#define sdl_std_cursor_HOT_Y_bottom_left_corner -1
static unsigned char sdl_std_cursor_mask_arrow[]= {0x00,0xe0,0x00,0xf8,0x00,0xfe,0x80,0x7f,0xe0,0x7f,0xf8,0x3f,0xfc,0x3f,0xfc,0x1f,0xe0,0x1f,0xf0,0x0f,0xf8,0x0f,0x7c,0x07,0x3e,0x07,0x1f,0x02,0x0e,0x00,0x04,0x00,};
static unsigned char sdl_std_cursor_arrow[]= {0x00,0x30,0x00,0x3c,0x00,0x1f,0xc0,0x1f,0xf0,0x0f,0xfc,0x0f,0xc0,0x07,0xe0,0x07,0x70,0x03,0x38,0x03,0x1c,0x01,0x0e,0x01,0x07,0x00,0x02,0x00,0x00,0x00,0x00,0x00,};
#define sdl_std_cursor_WIDTH_arrow 16
#define sdl_std_cursor_HEIGHT_arrow 16
#define sdl_std_cursor_HOT_X_arrow -13
#define sdl_std_cursor_HOT_Y_arrow -14
/* end cursor data */
static SDL_Cursor *sdl_std_cursor_array[(int)GHOST_kStandardCursorNumCursors]= {0};
/* utility function mostly a copy of SDL_CreateCursor but allows us to change
* color and supports blenders flipped bits */
static SDL_Cursor *
sdl_ghost_CreateCursor(const Uint8 *data,
const Uint8 *mask,
int w,
int h,
int hot_x,
int hot_y)
{
SDL_Surface *surface;
SDL_Cursor *cursor;
int x, y;
Uint32 *pixel;
Uint8 datab= 0, maskb= 0;
const Uint32 black= 0xFF000000;
const Uint32 white= 0xFFFFFFFF;
const Uint32 transparent= 0x00000000;
/* Make sure the width is a multiple of 8 */
w= ((w + 7) & ~7);
/* Create the surface from a bitmap */
surface= SDL_CreateRGBSurface(0, w, h, 32,
0x00FF0000,
0x0000FF00,
0x000000FF,
0xFF000000);
if (!surface) {
return NULL;
}
for (y= 0; y < h; ++y) {
pixel= (Uint32 *) ((Uint8 *) surface->pixels + y * surface->pitch);
for (x= 0; x < w; ++x) {
if ((x % 8) == 0) {
datab= *data++;
maskb= *mask++;
/* reverse bit order */
datab= (datab * 0x0202020202ULL & 0x010884422010ULL) % 1023;
maskb= (maskb * 0x0202020202ULL & 0x010884422010ULL) % 1023;
}
if (maskb & 0x80) {
*pixel++= (datab & 0x80) ? white : black;
}
else {
*pixel++= (datab & 0x80) ? white : transparent;
}
datab <<= 1;
maskb <<= 1;
}
}
cursor= SDL_CreateColorCursor(surface, hot_x, hot_y);
SDL_FreeSurface(surface);
return cursor;
}
/* TODO, this is currently never freed but it wont leak either. */
static void sdl_cursor_init(void)
{
#define DEF_CURSOR(name, ind) \
assert(\
(\
sdl_std_cursor_array[(int)ind]= \
sdl_ghost_CreateCursor(sdl_std_cursor_##name, \
sdl_std_cursor_mask_##name, \
sdl_std_cursor_WIDTH_##name, \
sdl_std_cursor_HEIGHT_##name, \
(sdl_std_cursor_WIDTH_##name + (sdl_std_cursor_HOT_X_##name)) - 1, \
(sdl_std_cursor_HEIGHT_##name + (sdl_std_cursor_HOT_Y_##name)) - 1) \
) != NULL) \
DEF_CURSOR(left_ptr, GHOST_kStandardCursorDefault);
DEF_CURSOR(right_ptr, GHOST_kStandardCursorRightArrow);
DEF_CURSOR(left_ptr, GHOST_kStandardCursorLeftArrow);
DEF_CURSOR(umbrella, GHOST_kStandardCursorInfo); // TODO, replace this one.
DEF_CURSOR(pirate, GHOST_kStandardCursorDestroy);
DEF_CURSOR(question_arrow, GHOST_kStandardCursorHelp);
DEF_CURSOR(exchange, GHOST_kStandardCursorCycle);
DEF_CURSOR(spraycan, GHOST_kStandardCursorSpray);
DEF_CURSOR(watch, GHOST_kStandardCursorWait);
DEF_CURSOR(xterm, GHOST_kStandardCursorText);
DEF_CURSOR(crosshair, GHOST_kStandardCursorCrosshair);
DEF_CURSOR(sb_v_double_arrow, GHOST_kStandardCursorUpDown);
DEF_CURSOR(sb_h_double_arrow, GHOST_kStandardCursorLeftRight);
DEF_CURSOR(top_side, GHOST_kStandardCursorTopSide);
DEF_CURSOR(bottom_side, GHOST_kStandardCursorBottomSide);
DEF_CURSOR(left_side, GHOST_kStandardCursorLeftSide);
DEF_CURSOR(right_side, GHOST_kStandardCursorRightSide);
DEF_CURSOR(top_left_corner, GHOST_kStandardCursorTopLeftCorner);
DEF_CURSOR(top_right_corner, GHOST_kStandardCursorTopRightCorner);
DEF_CURSOR(bottom_right_corner, GHOST_kStandardCursorBottomRightCorner);
DEF_CURSOR(bottom_left_corner , GHOST_kStandardCursorBottomLeftCorner);
DEF_CURSOR(arrow , GHOST_kStandardCursorCopy);
//DEF_CURSOR(arrow, GHOST_kStandardCursorCustom);
DEF_CURSOR(arrow, GHOST_kStandardCursorPencil);
#undef DEF_CURSOR
}
GHOST_TSuccess
GHOST_WindowSDL::setWindowCursorGrab(GHOST_TGrabCursorMode mode)
{
return GHOST_kSuccess;
}
GHOST_TSuccess
GHOST_WindowSDL::setWindowCursorShape(GHOST_TStandardCursor shape)
{
if(sdl_std_cursor_array[0] == NULL) {
sdl_cursor_init();
}
SDL_SetCursor(sdl_std_cursor_array[(int)shape]);
return GHOST_kSuccess;
}
GHOST_TSuccess
GHOST_WindowSDL::setWindowCustomCursorShape(GHOST_TUns8 bitmap[16][2],
GHOST_TUns8 mask[16][2],
int hotX,
int hotY)
{
return setWindowCustomCursorShape((GHOST_TUns8 *)bitmap,
(GHOST_TUns8 *)mask,
16, 16,
hotX, hotY,
0, 1);
}
GHOST_TSuccess
GHOST_WindowSDL::setWindowCustomCursorShape(GHOST_TUns8 *bitmap,
GHOST_TUns8 *mask,
int sizex, int sizey,
int hotX, int hotY,
int fg_color, int bg_color)
{
if(m_sdl_custom_cursor) {
SDL_FreeCursor(m_sdl_custom_cursor);
}
m_sdl_custom_cursor= sdl_ghost_CreateCursor((const Uint8 *)bitmap,
(const Uint8 *)mask,
sizex, sizex,
hotX, hotY);
SDL_SetCursor(m_sdl_custom_cursor);
return GHOST_kSuccess;
}
GHOST_TSuccess
GHOST_WindowSDL::setWindowCursorVisibility(bool visible)
{
SDL_ShowCursor(visible);
return GHOST_kSuccess;
}

View File

@@ -0,0 +1,167 @@
/*
* $Id$
* ***** BEGIN GPL LICENSE BLOCK *****
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* Contributor(s): Campbell Barton
*
* ***** END GPL LICENSE BLOCK *****
*/
/** \file ghost/intern/GHOST_WindowSDL.h
* \ingroup GHOST
* Declaration of GHOST_WindowSDL class.
*/
#ifndef _GHOST_WINDOWSDL_H_
#define _GHOST_WINDOWSDL_H_
#include "GHOST_Window.h"
#include "GHOST_SystemSDL.h"
#include <map>
extern "C" {
#include "SDL.h"
}
#if !SDL_VERSION_ATLEAST(1, 3, 0)
# error "SDL 1.3 or newer is needed to build with Ghost"
#endif
class STR_String;
class GHOST_WindowSDL : public GHOST_Window
{
private :
GHOST_SystemSDL * m_system;
bool m_invalid_window;
SDL_Window * m_sdl_win;
SDL_GLContext m_sdl_glcontext;
SDL_Cursor * m_sdl_custom_cursor;
public:
const GHOST_TabletData* GetTabletData() { return NULL; }
GHOST_WindowSDL(GHOST_SystemSDL *system,
const STR_String& title,
GHOST_TInt32 left, GHOST_TInt32 top,
GHOST_TUns32 width, GHOST_TUns32 height,
GHOST_TWindowState state,
const GHOST_TEmbedderWindowID parentWindow,
GHOST_TDrawingContextType type,
const bool stereoVisual,
const GHOST_TUns16 numOfAASamples
);
~GHOST_WindowSDL();
/* SDL spesific */
SDL_Window *
getSDLWindow()
{
return m_sdl_win;
}
GHOST_TSuccess invalidate(void);
/**
* called by the X11 system implementation when expose events
* for the window have been pushed onto the GHOST queue
*/
void validate()
{
m_invalid_window = false;
}
bool getValid() const
{
return (m_sdl_win != NULL);
}
void getWindowBounds(GHOST_Rect& bounds) const;
void getClientBounds(GHOST_Rect& bounds) const;
protected:
GHOST_TSuccess installDrawingContext(GHOST_TDrawingContextType type);
GHOST_TSuccess removeDrawingContext();
GHOST_TSuccess
setWindowCursorGrab(GHOST_TGrabCursorMode mode);
GHOST_TSuccess
setWindowCursorShape(GHOST_TStandardCursor shape);
GHOST_TSuccess
setWindowCustomCursorShape(GHOST_TUns8 bitmap[16][2],
GHOST_TUns8 mask[16][2],
int hotX, int hotY);
GHOST_TSuccess
setWindowCustomCursorShape(GHOST_TUns8 *bitmap,
GHOST_TUns8 *mask,
int sizex, int sizey,
int hotX, int hotY,
int fg_color, int bg_color);
GHOST_TSuccess
setWindowCursorVisibility(bool visible);
void
setTitle(const STR_String& title);
void
getTitle(STR_String& title) const;
GHOST_TSuccess
setClientWidth(GHOST_TUns32 width);
GHOST_TSuccess
setClientHeight(GHOST_TUns32 height);
GHOST_TSuccess
setClientSize(GHOST_TUns32 width,
GHOST_TUns32 height);
void
screenToClient(GHOST_TInt32 inX, GHOST_TInt32 inY,
GHOST_TInt32& outX, GHOST_TInt32& outY) const;
void
clientToScreen(GHOST_TInt32 inX, GHOST_TInt32 inY,
GHOST_TInt32& outX, GHOST_TInt32& outY) const;
GHOST_TSuccess
swapBuffers();
GHOST_TSuccess
activateDrawingContext();
GHOST_TSuccess
setState(GHOST_TWindowState state);
GHOST_TWindowState
getState() const;
GHOST_TSuccess setOrder(GHOST_TWindowOrder order) { return GHOST_kSuccess; } // TODO
};
#endif // _GHOST_WINDOWSDL_H_

View File

@@ -0,0 +1,155 @@
cmake_policy(SET CMP0003 NEW)
cmake_policy(SET CMP0005 NEW)
cmake_minimum_required(VERSION 2.8)
# -----------------------------------------------------------------------------
# Macros
# stub macro, does nothing
macro(blender_add_lib
name
sources
includes
includes_sys
)
endmacro()
# suffix relative paths so we can use external cmake files
macro(suffix_relpaths
new_files files prefix)
set(${new_files})
foreach(_file ${files})
if(IS_ABSOLUTE _file)
list(APPEND ${new_files} ${_file})
else()
list(APPEND ${new_files} "${prefix}${_file}")
endif()
endforeach()
unset(_file)
endmacro()
# -----------------------------------------------------------------------------
# Libraries
# ghost
include(${CMAKE_SOURCE_DIR}/../CMakeLists.txt)
suffix_relpaths(INC_NEW "${INC}" "../")
suffix_relpaths(SRC_NEW "${SRC}" "../")
include_directories(${INC_NEW})
add_library(ghost_lib ${SRC_NEW})
# string
include(${CMAKE_SOURCE_DIR}/../../string/CMakeLists.txt)
suffix_relpaths(INC_NEW "${INC}" "../../string/")
suffix_relpaths(SRC_NEW "${SRC}" "../../string/")
include_directories(${INC_NEW})
add_library(string_lib ${SRC_NEW})
# guardedalloc
include(${CMAKE_SOURCE_DIR}/../../guardedalloc/CMakeLists.txt)
suffix_relpaths(INC_NEW "${INC}" "../../guardedalloc/")
suffix_relpaths(SRC_NEW "${SRC}" "../../guardedalloc/")
include_directories(${INC_NEW})
add_library(guardedalloc_lib ${SRC_NEW})
# blenfont
include(${CMAKE_SOURCE_DIR}/../../../source/blender/blenfont/CMakeLists.txt)
suffix_relpaths(INC_NEW "${INC}" "../../../source/blender/blenfont/")
suffix_relpaths(SRC_NEW "${SRC}" "../../../source/blender/blenfont/")
include_directories(${INC_NEW})
add_library(blenfont_lib ${SRC_NEW})
# grr, blenfont needs BLI
include_directories(
"../../../source/blender/blenlib"
"../../../source/blender/blenloader"
)
add_library(bli_lib
"../../../source/blender/blenlib/intern/fileops.c"
"../../../source/blender/blenlib/intern/rct.c"
"../../../source/blender/blenlib/intern/string.c"
"../../../source/blender/blenlib/intern/listbase.c"
"../../../source/blender/blenlib/intern/storage.c"
"../../../source/blender/blenlib/intern/path_util.c"
"../../../source/blender/blenlib/intern/BLI_dynstr.c"
"../../../source/blender/blenlib/intern/BLI_linklist.c"
"../../../source/blender/blenlib/intern/BLI_memarena.c"
)
find_package(OpenGL REQUIRED)
find_package(Freetype REQUIRED)
include_directories(${CMAKE_SOURCE_DIR}/../)
include_directories(${OPENGL_INCLUDE_DIR})
include_directories(${FREETYPE_INCLUDE_DIRS})
include_directories(${CMAKE_SOURCE_DIR}/../../../source/blender/blenfont)
if(UNIX AND NOT APPLE)
find_package(X11 REQUIRED)
set(PLATFORM_LINKLIBS
${X11_X11_LIB}
${X11_Xinput_LIB}
)
endif()
# -----------------------------------------------------------------------------
# Executables
# Gears (C)
add_executable(gears_c
${CMAKE_SOURCE_DIR}/gears/GHOST_C-Test.c)
target_link_libraries(gears_c
ghost_lib
string_lib
${OPENGL_gl_LIBRARY}
${OPENGL_glu_LIBRARY}
${PLATFORM_LINKLIBS}
)
# Gears (C++)
add_executable(gears_cpp
${CMAKE_SOURCE_DIR}/gears/GHOST_Test.cpp)
target_link_libraries(gears_cpp
ghost_lib
string_lib
${OPENGL_gl_LIBRARY}
${OPENGL_glu_LIBRARY}
${PLATFORM_LINKLIBS}
)
# MultiTest (C)
add_executable(multitest_c
${CMAKE_SOURCE_DIR}/../../../source/blender/editors/datafiles/bfont.ttf.c
${CMAKE_SOURCE_DIR}/multitest/Basic.c
${CMAKE_SOURCE_DIR}/multitest/EventToBuf.c
${CMAKE_SOURCE_DIR}/multitest/MultiTest.c
${CMAKE_SOURCE_DIR}/multitest/ScrollBar.c
${CMAKE_SOURCE_DIR}/multitest/Util.c
${CMAKE_SOURCE_DIR}/multitest/WindowData.c
)
target_link_libraries(multitest_c
blenfont_lib
bli_lib
ghost_lib
string_lib
guardedalloc_lib
${OPENGL_gl_LIBRARY}
${OPENGL_glu_LIBRARY}
${FREETYPE_LIBRARY}
${PLATFORM_LINKLIBS}
)

View File

@@ -474,6 +474,7 @@ int main(int argc, char** argv)
200,
GHOST_kWindowStateNormal,
GHOST_kDrawingContextTypeOpenGL,
FALSE,
FALSE);
if (!sMainWindow)
{
@@ -490,6 +491,7 @@ int main(int argc, char** argv)
200,
GHOST_kWindowStateNormal,
GHOST_kDrawingContextTypeOpenGL,
FALSE,
FALSE);
if (!sSecondaryWindow)
{

View File

@@ -428,7 +428,7 @@ Application::Application(GHOST_ISystem* system)
// Create the main window
STR_String title1 ("gears - main window");
m_mainWindow = system->createWindow(title1, 10, 64, 320, 200, GHOST_kWindowStateNormal,
GHOST_kDrawingContextTypeOpenGL, true /* stereo flag */);
GHOST_kDrawingContextTypeOpenGL, false, false);
if (!m_mainWindow) {
std::cout << "could not create main window\n";
@@ -438,7 +438,7 @@ Application::Application(GHOST_ISystem* system)
// Create a secondary window
STR_String title2 ("gears - secondary window");
m_secondaryWindow = system->createWindow(title2, 340, 64, 320, 200, GHOST_kWindowStateNormal,
GHOST_kDrawingContextTypeOpenGL, false /* stereo flag */);
GHOST_kDrawingContextTypeOpenGL, false, false);
if (!m_secondaryWindow) {
cout << "could not create secondary window\n";
exit(-1);

View File

@@ -42,7 +42,18 @@
#include "MEM_guardedalloc.h"
#include "GHOST_C-api.h"
#include "BMF_Api.h"
#ifdef USE_BMF
# include "BMF_Api.h"
#else
# include "BLF_api.h"
extern int datatoc_bfont_ttf_size;
extern char datatoc_bfont_ttf[];
// XXX, bad, but BLI uses these
char bprogname[160]= "";
char U[1024]= {0};
#endif
#include "Util.h"
#include "Basic.h"
@@ -291,7 +302,7 @@ MainWindow *mainwindow_new(MultiTestApp *app) {
win= GHOST_CreateWindow(sys, "MultiTest:Main", 40, 40, 400, 400,
GHOST_kWindowStateNormal, GHOST_kDrawingContextTypeOpenGL,
FALSE);
FALSE, FALSE);
if (win) {
MainWindow *mw= MEM_callocN(sizeof(*mw), "mainwindow_new");
@@ -324,8 +335,12 @@ struct _LoggerWindow {
MultiTestApp *app;
GHOST_WindowHandle win;
#ifdef USE_BMF
BMF_Font *font;
#else
int font;
#endif
int fonttexid;
int fontheight;
@@ -429,18 +444,26 @@ static void loggerwindow_do_draw(LoggerWindow *lw) {
char *line= lw->loglines[(lw->nloglines-1)-(i+startline)];
int x_pos= lw->textarea[0][0] + 4;
int y_pos= lw->textarea[0][1] + 4 + i*lw->fontheight;
#ifdef USE_BMF
if (lw->fonttexid==-1) {
glRasterPos2i(x_pos, y_pos);
BMF_DrawString(lw->font, line);
} else {
BMF_DrawStringTexture(lw->font, line, x_pos, y_pos, 0.0);
}
#else
BLF_position(lw->font, x_pos, y_pos, 0.0);
BLF_draw(lw->font, line, 256); // XXX
#endif
}
#ifdef USE_BMF
if (lw->fonttexid!=-1) {
glDisable(GL_TEXTURE_2D);
glDisable(GL_BLEND);
}
#endif
GHOST_SwapWindowBuffers(lw->win);
}
@@ -531,19 +554,25 @@ LoggerWindow *loggerwindow_new(MultiTestApp *app) {
GHOST_GetMainDisplayDimensions(sys, &screensize[0], &screensize[1]);
win= GHOST_CreateWindow(sys, "MultiTest:Logger", 40, screensize[1]-432,
800, 300, GHOST_kWindowStateNormal,
GHOST_kDrawingContextTypeOpenGL, FALSE);
GHOST_kDrawingContextTypeOpenGL, FALSE, FALSE);
if (win) {
LoggerWindow *lw= MEM_callocN(sizeof(*lw), "loggerwindow_new");
int bbox[2][2];
lw->app= app;
lw->win= win;
#ifdef USE_BMF
lw->font= BMF_GetFont(BMF_kScreen12);
lw->fonttexid= BMF_GetFontTexture(lw->font);
BMF_GetBoundingBox(lw->font, &bbox[0][0], &bbox[0][1], &bbox[1][0], &bbox[1][1]);
lw->fontheight= rect_height(bbox);
#else
lw->font= BLF_load_mem("default", (unsigned char*)datatoc_bfont_ttf, datatoc_bfont_ttf_size);
BLF_size(lw->font, 11, 72);
lw->fontheight= BLF_height(lw->font, "A_");
#endif
lw->nloglines= lw->logsize= 0;
lw->loglines= MEM_mallocN(sizeof(*lw->loglines)*lw->nloglines, "loglines");
@@ -711,7 +740,7 @@ ExtraWindow *extrawindow_new(MultiTestApp *app) {
win= GHOST_CreateWindow(sys, "MultiTest:Extra", 500, 40, 400, 400,
GHOST_kWindowStateNormal, GHOST_kDrawingContextTypeOpenGL,
FALSE);
FALSE, FALSE);
if (win) {
ExtraWindow *ew= MEM_callocN(sizeof(*ew), "mainwindow_new");
@@ -786,7 +815,7 @@ static int multitest_event_handler(GHOST_EventHandle evt, GHOST_TUserDataPtr dat
MultiTestApp *multitestapp_new(void) {
MultiTestApp *app= MEM_mallocN(sizeof(*app), "multitestapp_new");
GHOST_EventConsumerHandle consumer= GHOST_CreateEventConsumer(multitest_event_handler, app);
app->sys= GHOST_CreateSystem();
if (!app->sys)
fatal("Unable to create ghost system");
@@ -850,6 +879,10 @@ void multitestapp_free(MultiTestApp *app) {
/***/
int main(int argc, char **argv) {
#ifndef USE_BMF
BLF_init(11, 72);
#endif
MultiTestApp *app= multitestapp_new();
multitestapp_run(app);

View File

@@ -59,6 +59,7 @@ void IK_QJacobian::ArmMatrices(int dof, int task_size)
m_d_theta.newsize(dof);
m_d_theta_tmp.newsize(dof);
m_d_norm_weight.newsize(dof);
m_norm.newsize(dof);
m_norm = 0.0;
@@ -111,11 +112,13 @@ void IK_QJacobian::SetBetas(int id, int, const MT_Vector3& v)
m_beta[id+2] = v.z();
}
void IK_QJacobian::SetDerivatives(int id, int dof_id, const MT_Vector3& v)
void IK_QJacobian::SetDerivatives(int id, int dof_id, const MT_Vector3& v, MT_Scalar norm_weight)
{
m_jacobian[id][dof_id] = v.x()*m_weight_sqrt[dof_id];
m_jacobian[id+1][dof_id] = v.y()*m_weight_sqrt[dof_id];
m_jacobian[id+2][dof_id] = v.z()*m_weight_sqrt[dof_id];
m_d_norm_weight[dof_id] = norm_weight;
}
void IK_QJacobian::Invert()
@@ -429,7 +432,7 @@ MT_Scalar IK_QJacobian::AngleUpdateNorm() const
MT_Scalar mx = 0.0, dtheta_abs;
for (i = 0; i < m_d_theta.size(); i++) {
dtheta_abs = MT_abs(m_d_theta[i]);
dtheta_abs = MT_abs(m_d_theta[i]*m_d_norm_weight[i]);
if (dtheta_abs > mx)
mx = dtheta_abs;
}

View File

@@ -56,7 +56,7 @@ public:
// Iteratively called
void SetBetas(int id, int size, const MT_Vector3& v);
void SetDerivatives(int id, int dof_id, const MT_Vector3& v);
void SetDerivatives(int id, int dof_id, const MT_Vector3& v, MT_Scalar norm_weight);
void Invert();
@@ -89,6 +89,7 @@ private:
/// the vector of computed angle changes
TVector m_d_theta;
TVector m_d_norm_weight;
/// space required for SVD computation

View File

@@ -905,9 +905,6 @@ void IK_QElbowSegment::SetLimit(int axis, MT_Scalar lmin, MT_Scalar lmax)
lmin = MT_clamp(lmin, -MT_PI, MT_PI);
lmax = MT_clamp(lmax, -MT_PI, MT_PI);
lmin = lmin;
lmax = lmax;
if (axis == 1) {
m_min_twist = lmin;
m_max_twist = lmax;

View File

@@ -95,10 +95,10 @@ void IK_QPositionTask::ComputeJacobian(IK_QJacobian& jacobian)
MT_Vector3 axis = seg->Axis(i)*m_weight;
if (seg->Translational())
jacobian.SetDerivatives(m_id, seg->DoFId()+i, axis);
jacobian.SetDerivatives(m_id, seg->DoFId()+i, axis, 1e2);
else {
MT_Vector3 pa = p.cross(axis);
jacobian.SetDerivatives(m_id, seg->DoFId()+i, pa);
jacobian.SetDerivatives(m_id, seg->DoFId()+i, pa, 1e0);
}
}
}
@@ -147,10 +147,10 @@ void IK_QOrientationTask::ComputeJacobian(IK_QJacobian& jacobian)
for (i = 0; i < seg->NumberOfDoF(); i++) {
if (seg->Translational())
jacobian.SetDerivatives(m_id, seg->DoFId()+i, MT_Vector3(0, 0, 0));
jacobian.SetDerivatives(m_id, seg->DoFId()+i, MT_Vector3(0, 0, 0), 1e2);
else {
MT_Vector3 axis = seg->Axis(i)*m_weight;
jacobian.SetDerivatives(m_id, seg->DoFId()+i, axis);
jacobian.SetDerivatives(m_id, seg->DoFId()+i, axis, 1e0);
}
}
}
@@ -202,10 +202,10 @@ void IK_QCenterOfMassTask::JacobianSegment(IK_QJacobian& jacobian, MT_Vector3& c
axis *= /*segment->Mass()**/m_total_mass_inv;
if (segment->Translational())
jacobian.SetDerivatives(m_id, segment->DoFId()+i, axis);
jacobian.SetDerivatives(m_id, segment->DoFId()+i, axis, 1e2);
else {
MT_Vector3 pa = axis.cross(p);
jacobian.SetDerivatives(m_id, segment->DoFId()+i, pa);
jacobian.SetDerivatives(m_id, segment->DoFId()+i, pa, 1e0);
}
}

View File

@@ -134,6 +134,7 @@ bool ConstraintSet::setControlParameter(int id, ConstraintAction action, double
break;
default:
assert(action==ACT_NONE);
break;
}
return setControlParameters(&values, 1, timestep);
}

View File

@@ -243,7 +243,7 @@ tbool genTangSpace(const SMikkTSpaceContext * pContext, const float fAngularThre
int iNrActiveGroups = 0, index = 0;
const int iNrFaces = pContext->m_pInterface->m_getNumFaces(pContext);
tbool bRes = TFALSE;
const float fThresCos = (const float) cos((fAngularThreshold*(float)M_PI)/180.0f);
const float fThresCos = (float) cos((fAngularThreshold*(float)M_PI)/180.0f);
// verify all call-backs have been set
if( pContext->m_pInterface->m_getNumFaces==NULL ||
@@ -1411,7 +1411,7 @@ STSpace EvalTspace(int face_indices[], const int iFaces, const int piTriListIn[]
// weight contribution by the angle
// between the two edge vectors
fCos = vdot(v1,v2); fCos=fCos>1?1:(fCos<(-1) ? (-1) : fCos);
fAngle = (const float) acos(fCos);
fAngle = (float) acos(fCos);
fMagS = pTriInfos[f].fMagS;
fMagT = pTriInfos[f].fMagT;

View File

@@ -84,12 +84,14 @@ set(SRC
)
if(WITH_OPENMP)
add_definitions(-DPARALLEL=1)
add_definitions(-DPARALLEL=1)
endif()
if(WITH_FFTW3)
add_definitions(-DFFTW3=1)
list(APPEND INC ${FFTW3_INCLUDE_DIRS})
list(APPEND INC
${FFTW3_INCLUDE_DIRS}
)
endif()
blender_add_lib(bf_intern_smoke "${SRC}" "${INC}" "${INC_SYS}")

View File

@@ -45,6 +45,11 @@
#include <MERSENNETWISTER.h>
#ifdef WIN32
#include <float.h>
#define isnan _isnan
#endif
// Tile file header, update revision upon any change done to the noise generator
static const char tilefile_headerstring[] = "Noise Tile File rev. ";
static const char tilefile_revision[] = "001";
@@ -69,7 +74,7 @@ static void downsampleX(float *from, float *to, int n){
const float *a = &downCoeffs[16];
for (int i = 0; i < n / 2; i++) {
to[i] = 0;
for (int k = 2 * i - 16; k <= 2 * i + 16; k++)
for (int k = 2 * i - 16; k < 2 * i + 16; k++)
to[i] += a[k - 2 * i] * from[modFast128(k)];
}
}
@@ -79,7 +84,7 @@ static void downsampleY(float *from, float *to, int n){
const float *a = &downCoeffs[16];
for (int i = 0; i < n / 2; i++) {
to[i * n] = 0;
for (int k = 2 * i - 16; k <= 2 * i + 16; k++)
for (int k = 2 * i - 16; k < 2 * i + 16; k++)
to[i * n] += a[k - 2 * i] * from[modFast128(k) * n];
}
}
@@ -89,7 +94,7 @@ static void downsampleZ(float *from, float *to, int n){
const float *a = &downCoeffs[16];
for (int i = 0; i < n / 2; i++) {
to[i * n * n] = 0;
for (int k = 2 * i - 16; k <= 2 * i + 16; k++)
for (int k = 2 * i - 16; k < 2 * i + 16; k++)
to[i * n * n] += a[k - 2 * i] * from[modFast128(k) * n * n];
}
}
@@ -262,6 +267,14 @@ static bool loadTile(float* const noiseTileData, std::string filename)
printf("loadTile: Noise tile '%s' is wrong size %d.\n", filename.c_str(), (int)bread);
return false;
}
// check for invalid nan tile data that could be generated. bug is now
// fixed, but invalid files may still hang around
if (isnan(noiseTileData[0])) {
printf("loadTile: Noise tile '%s' contains nan values.\n", filename.c_str());
return false;
}
return true;
}

View File

@@ -31,6 +31,8 @@ __all__ = (
import bpy as _bpy
error_duplicates = False
def paths():
# RELEASE SCRIPTS: official scripts distributed in Blender releases
paths = _bpy.utils.script_paths("addons")
@@ -47,9 +49,10 @@ def paths():
def modules(module_cache):
global error_duplicates
import os
import sys
import time
error_duplicates = False
path_list = paths()
@@ -119,7 +122,12 @@ def modules(module_cache):
modules_stale -= {mod_name}
mod = module_cache.get(mod_name)
if mod:
if mod.__time__ != os.path.getmtime(mod_path):
if mod.__file__ != mod_path:
print("multiple addons with the same name:\n %r\n %r" %
(mod.__file__, mod_path))
error_duplicates = True
elif mod.__time__ != os.path.getmtime(mod_path):
print("reloading addon:", mod_name, mod.__time__, os.path.getmtime(mod_path), mod_path)
del module_cache[mod_name]
mod = None
@@ -173,11 +181,9 @@ def enable(module_name, default_set=True):
:return: the loaded module or None on failier.
:rtype: module
"""
# note, this still gets added to _bpy_types.TypeMap
import os
import sys
import bpy_types as _bpy_types
import imp
def handle_error():
@@ -246,8 +252,6 @@ def disable(module_name, default_set=True):
:type module_name: string
"""
import sys
import bpy_types as _bpy_types
mod = sys.modules.get(module_name)
# possible this addon is from a previous session and didnt load a module this time.

View File

@@ -22,24 +22,29 @@
Give access to blender data and utility functions.
"""
# internal blender C module
import _bpy
from _bpy import types, props, app
__all__ = (
"app",
"context",
"data",
"ops",
"path",
"props",
"types",
"utils",
)
data = _bpy.data
context = _bpy.context
# internal blender C module
from _bpy import types, props, app, data, context
# python modules
from . import utils, path
from . import ops as _ops_module
from . import utils, path, ops
# fake operator module
ops = _ops_module.ops_fake_module
import sys as _sys
ops = ops.ops_fake_module
def _main():
import sys as _sys
# Possibly temp. addons path
from os.path import join, dirname, normpath
@@ -59,3 +64,5 @@ def _main():
_main()
del _main

View File

@@ -29,7 +29,7 @@ op_as_string = ops_module.as_string
op_get_rna = ops_module.get_rna
class bpy_ops(object):
class BPyOps(object):
'''
Fake module like class.
@@ -42,7 +42,7 @@ class bpy_ops(object):
'''
if module.startswith('__'):
raise AttributeError(module)
return bpy_ops_submodule(module)
return BPyOpsSubMod(module)
def __dir__(self):
@@ -67,7 +67,7 @@ class bpy_ops(object):
return "<module like class 'bpy.ops'>"
class bpy_ops_submodule(object):
class BPyOpsSubMod(object):
'''
Utility class to fake submodules.
@@ -84,7 +84,7 @@ class bpy_ops_submodule(object):
'''
if func.startswith('__'):
raise AttributeError(func)
return bpy_ops_submodule_op(self.module, func)
return BPyOpsSubModOp(self.module, func)
def __dir__(self):
@@ -103,7 +103,7 @@ class bpy_ops_submodule(object):
return "<module like class 'bpy.ops.%s'>" % self.module
class bpy_ops_submodule_op(object):
class BPyOpsSubModOp(object):
'''
Utility class to fake submodule operators.
@@ -151,7 +151,7 @@ class bpy_ops_submodule_op(object):
self.func = func
def poll(self, *args):
C_dict, C_exec = __class__._parse_args(args)
C_dict, C_exec = BPyOpsSubModOp._parse_args(args)
return op_poll(self.idname_py(), C_dict, C_exec)
def idname(self):
@@ -170,16 +170,16 @@ class bpy_ops_submodule_op(object):
wm = context.window_manager
# run to account for any rna values the user changes.
__class__._scene_update(context)
BPyOpsSubModOp._scene_update(context)
if args:
C_dict, C_exec = __class__._parse_args(args)
C_dict, C_exec = BPyOpsSubModOp._parse_args(args)
ret = op_call(self.idname_py(), C_dict, kw, C_exec)
else:
ret = op_call(self.idname_py(), None, kw)
if 'FINISHED' in ret and context.window_manager == wm:
__class__._scene_update(context)
BPyOpsSubModOp._scene_update(context)
return ret
@@ -208,4 +208,4 @@ class bpy_ops_submodule_op(object):
return "<function bpy.ops.%s.%s at 0x%x'>" % \
(self.module, self.func, id(self))
ops_fake_module = bpy_ops()
ops_fake_module = BPyOps()

View File

@@ -35,7 +35,7 @@ def abspath(path, start=None):
:type start: string
"""
if path.startswith("//"):
return _os.path.join(_os.path.dirname(_bpy.data.filepath if start is None else start), path[2:])
return _os.path.join(_os.path.dirname(_bpy.data.filepath) if start is None else start, path[2:])
return path
@@ -117,7 +117,7 @@ def display_name_from_filepath(name):
"""
Returns the path stripped of directort and extension, ensured to be utf8 compatible.
"""
return _os.path.splitext(_os.path.basename(name))[0].encode("utf8", "replace").decode("utf8")
return _os.path.splitext(basename(name))[0].encode("utf8", "replace").decode("utf8")
def resolve_ncase(path):
@@ -231,3 +231,12 @@ def module_names(path, recursive=False):
modules.append(("%s.%s" % (filename, mod_name), mod_path))
return modules
def basename(path):
"""
Equivalent to os.path.basename, but skips a "//" suffix.
Use for Windows compatibility.
"""
return _os.path.basename(path[2:] if path.startswith("//") else path)

View File

@@ -298,11 +298,18 @@ _presets = _os.path.join(_scripts[0], "presets") # FIXME - multiple paths
def preset_paths(subdir):
"""
Returns a list of paths for a specific preset.
:arg subdir: preset subdirectory (must not be an absolute path).
:type subdir: string
:return: script paths.
:rtype: list
"""
dirs = []
for path in script_paths("presets", all=True):
directory = _os.path.join(path, subdir)
if _os.path.isdir(directory):
if not directory.startswith(path):
raise Exception("invalid subdir given %r" % subdir)
elif _os.path.isdir(directory):
dirs.append(directory)
return dirs

View File

@@ -86,7 +86,9 @@ def load_image(imagepath,
variants = [imagepath]
if dirname:
variants += [os.path.join(dirname, imagepath), os.path.join(dirname, os.path.basename(imagepath))]
variants += [os.path.join(dirname, imagepath),
os.path.join(dirname, bpy.path.basename(imagepath)),
]
for filepath_test in variants:
if ncase_cmp:
@@ -99,7 +101,7 @@ def load_image(imagepath,
return _image_load(nfilepath)
if place_holder:
image = bpy.data.images.new(os.path.basename(filepath), 128, 128)
image = bpy.data.images.new(bpy.path.basename(imagepath), 128, 128)
# allow the path to be resolved later
image.filepath = imagepath
return image

View File

@@ -22,6 +22,7 @@ __all__ = (
"ExportHelper",
"ImportHelper",
"axis_conversion",
"axis_conversion_ensure",
"create_derived_objects",
"free_derived_objects",
"unpack_list",
@@ -154,12 +155,50 @@ def axis_conversion(from_forward='Y', from_up='Z', to_forward='Y', to_up='Z'):
if from_forward == to_forward and from_up == to_up:
return Matrix().to_3x3()
if from_forward[-1] == from_up[-1] or to_forward[-1] == to_up[-1]:
raise Exception("invalid axis arguments passed, "
"can't use up/forward on the same axis.")
value = reduce(int.__or__, (_axis_convert_num[a] << (i * 3) for i, a in enumerate((from_forward, from_up, to_forward, to_up))))
for i, axis_lut in enumerate(_axis_convert_lut):
if value in axis_lut:
return Matrix(_axis_convert_matrix[i])
assert("internal error")
assert(0)
def axis_conversion_ensure(operator, forward_attr, up_attr):
"""
Function to ensure an operator has valid axis conversion settings, intended
to be used from :class:`Operator.check`.
:arg operator: the operator to access axis attributes from.
:type operator: :class:`Operator`
:arg forward_attr:
:type forward_attr: string
:arg up_attr: the directory the *filepath* will be referenced from (normally the export path).
:type up_attr: string
:return: True if the value was modified.
:rtype: boolean
"""
def validate(axis_forward, axis_up):
if axis_forward[-1] == axis_up[-1]:
axis_up = axis_up[0:-1] + 'XYZ'[('XYZ'.index(axis_up[-1]) + 1) % 3]
return axis_forward, axis_up
change = False
axis = getattr(operator, forward_attr), getattr(operator, up_attr)
axis_new = validate(*axis)
if axis != axis_new:
setattr(operator, forward_attr, axis_new[0])
setattr(operator, up_attr, axis_new[1])
return True
else:
return False
# return a tuple (free, object list), free is True if memory should be freed later with free_derived_objects()
@@ -262,7 +301,7 @@ def path_reference(filepath, base_src, base_dst, mode='AUTO', copy_subdir="", co
filepath_abs = filepath_cpy
mode = 'RELATIVE'
else:
Excaption("invalid mode given %r" % mode)
raise Exception("invalid mode given %r" % mode)
if mode == 'ABSOLUTE':
return filepath_abs

View File

@@ -16,7 +16,7 @@
#
# ##### END GPL LICENSE BLOCK #####
# <pep8 compliant>
# <pep8-80 compliant>
__all__ = (
"mesh_linked_faces",
@@ -25,6 +25,7 @@ __all__ = (
"edge_loops_from_faces",
"edge_loops_from_edges",
"ngon_tesselate",
"face_random_points",
)
@@ -67,7 +68,8 @@ def mesh_linked_faces(mesh):
if mapped_index != nxt_mapped_index:
ok = True
# Assign mapping to this group so they all map to this group
# Assign mapping to this group so they
# all map to this group
for grp_f in face_groups[nxt_mapped_index]:
face_mapping[grp_f.index] = mapped_index
@@ -105,9 +107,9 @@ def edge_face_count(mesh):
:return: list face users for each item in mesh.edges.
:rtype: list
"""
edge_face_count_dict = edge_face_count_dict(mesh)
edge_face_count = edge_face_count_dict(mesh)
get = dict.get
return [get(edge_face_count_dict, ed.key, 0) for ed in mesh.edges]
return [get(edge_face_count, ed.key, 0) for ed in mesh.edges]
def edge_loops_from_faces(mesh, faces=None, seams=()):
@@ -212,8 +214,6 @@ def edge_loops_from_edges(mesh, edges=None):
if not hasattr(edges, "pop"):
edges = edges[:]
edge_dict = {ed.key: ed for ed in mesh.edges if ed.select}
while edges:
current_edge = edges.pop()
vert_end, vert_start = current_edge.vertices[:]
@@ -287,7 +287,7 @@ def ngon_tesselate(from_data, indices, fix_loops=True):
else:
return v1[1], v2[1]
if not PREF_FIX_LOOPS:
if not fix_loops:
'''
Normal single concave loop filling
'''
@@ -300,7 +300,7 @@ def ngon_tesselate(from_data, indices, fix_loops=True):
if verts[i][1] == verts[i - 1][0]:
verts.pop(i - 1)
fill = fill_polygon([verts])
fill = tesselate_polygon([verts])
else:
'''
@@ -435,3 +435,70 @@ def ngon_tesselate(from_data, indices, fix_loops=True):
fill[i] = tuple([ii for ii in reversed(fi)])
return fill
def face_random_points(num_points, faces):
"""
Generates a list of random points over mesh faces.
:arg num_points: the number of random points to generate on each face.
:type int:
:arg faces: list of the faces to generate points on.
:type faces: :class:`MeshFaces`, sequence
:return: list of random points over all faces.
:rtype: list
"""
from random import random
from mathutils.geometry import area_tri
# Split all quads into 2 tris, tris remain unchanged
tri_faces = []
for f in faces:
tris = []
verts = f.id_data.vertices
fv = f.vertices[:]
tris.append((verts[fv[0]].co,
verts[fv[1]].co,
verts[fv[2]].co,
))
if len(fv) == 4:
tris.append((verts[fv[0]].co,
verts[fv[3]].co,
verts[fv[2]].co,
))
tri_faces.append(tris)
# For each face, generate the required number of random points
sampled_points = [None] * (num_points * len(faces))
for i, tf in enumerate(tri_faces):
for k in range(num_points):
# If this is a quad, we need to weight its 2 tris by their area
if len(tf) != 1:
area1 = area_tri(*tf[0])
area2 = area_tri(*tf[1])
area_tot = area1 + area2
area1 = area1 / area_tot
area2 = area2 / area_tot
vecs = tf[0 if (random() < area1) else 1]
else:
vecs = tf[0]
u1 = random()
u2 = random()
u_tot = u1 + u2
if u_tot > 1:
u1 = 1.0 - u1
u2 = 1.0 - u2
side1 = vecs[1] - vecs[0]
side2 = vecs[2] - vecs[0]
p = vecs[0] + u1 * side1 + u2 * side2
sampled_points[num_points * i + k] = p
return sampled_points

View File

@@ -22,7 +22,6 @@ __all__ = (
"region_2d_to_vector_3d",
"region_2d_to_location_3d",
"location_3d_to_region_2d",
"location_3d_to_region_2d",
)

View File

@@ -241,7 +241,7 @@ class _GenericBone:
chain.append(child)
else:
if len(children_basename):
print("multiple basenames found, this is probably not what you want!", bone.name, children_basename)
print("multiple basenames found, this is probably not what you want!", self.name, children_basename)
break

View File

@@ -22,7 +22,6 @@
import bpy as _bpy
import bpyml
from bpyml import TAG, ARGS, CHILDREN
from types import ModuleType
_uilayout_rna = _bpy.types.UILayout.bl_rna

View File

@@ -53,7 +53,7 @@ RE_UNQUOTED_WORD = re.compile(
re.UNICODE)
def complete(line, cursor, namespace, private=True):
def complete(line, cursor, namespace, private):
"""Returns a list of possible completions:
* name completion
@@ -82,6 +82,9 @@ def complete(line, cursor, namespace, private=True):
if RE_MODULE.match(line):
from . import complete_import
matches = complete_import.complete(line)
if not private:
matches[:] = [m for m in matches if m[:1] != "_"]
matches.sort()
else:
from . import complete_namespace
matches = complete_namespace.complete(word, namespace, private)
@@ -130,11 +133,15 @@ def expand(line, cursor, namespace, private=True):
else:
# causes blender bug [#27495] since string keys may contain '.'
# scrollback = ' '.join([m.split('.')[-1] for m in matches])
# add white space to align with the cursor
white_space = " " + (" " * (cursor + len(prefix)))
word_prefix = word + prefix
scrollback = ' '.join(
[m[len(word_prefix):]
scrollback = '\n'.join(
[white_space + m[len(word_prefix):]
if (word_prefix and m.startswith(word_prefix))
else m.split('.')[-1]
else
white_space + m.split('.')[-1]
for m in matches])
no_calltip = True

View File

@@ -114,7 +114,7 @@ def draw(layout, context, context_member, property_type, use_edit=True):
to_dict = getattr(val, "to_dict", None)
to_list = getattr(val, "to_list", None)
val_orig = val
# val_orig = val # UNUSED
if to_dict:
val = to_dict()
val_draw = str(val)

View File

@@ -60,7 +60,7 @@ class EditExternally(bpy.types.Operator):
filepath = bpy.path.abspath(self.filepath)
if not os.path.exists(filepath):
self.report({'ERROR'}, "Image path %r not found." % filepath)
self.report({'ERROR'}, "Image path %r not found, image may be packed or unsaved." % filepath)
return {'CANCELLED'}
cmd = self._editor_guess(context) + [filepath]
@@ -121,7 +121,6 @@ class ProjectEdit(bpy.types.Operator):
def execute(self, context):
import os
import subprocess
EXT = "png" # could be made an option but for now ok
@@ -164,7 +163,7 @@ class ProjectEdit(bpy.types.Operator):
filepath_final = filepath + ("%.3d.%s" % (i, EXT))
i += 1
image_new.name = os.path.basename(filepath_final)
image_new.name = bpy.path.basename(filepath_final)
ProjectEdit._proj_hack[0] = image_new.name
image_new.filepath_raw = filepath_final # TODO, filepath raw is crummy

View File

@@ -81,14 +81,12 @@ class MeshMirrorUV(bpy.types.Operator):
@classmethod
def poll(cls, context):
ob = context.active_object
return (ob and ob.type == 'MESH')
obj = context.active_object
return (obj and obj.type == 'MESH' and obj.data.uv_textures.active)
def execute(self, context):
DIR = (self.direction == 'NEGATIVE')
from mathutils import Vector
ob = context.active_object
is_editmode = (ob.mode == 'EDIT')
if is_editmode:
@@ -120,12 +118,7 @@ class MeshMirrorUV(bpy.types.Operator):
if j is not None:
vmap[i] = j
active_uv_layer = None
for lay in mesh.uv_textures:
if lay.active:
active_uv_layer = lay.data
break
active_uv_layer = mesh.uv_textures.active.data
fuvs = [(uv.uv1, uv.uv2, uv.uv3, uv.uv4) for uv in active_uv_layer]
fuvs_cpy = [(uv[0].copy(), uv[1].copy(), uv[2].copy(), uv[3].copy()) for uv in fuvs]

View File

@@ -21,13 +21,102 @@
import bpy
from mathutils import Vector
def GlobalBB_LQ(bb_world):
# Initialize the variables with the 8th vertex
left, right, front, back, down, up =\
bb_world[7][0],\
bb_world[7][0],\
bb_world[7][1],\
bb_world[7][1],\
bb_world[7][2],\
bb_world[7][2]
# Test against the other 7 verts
for i in range (7):
# X Range
val = bb_world[i][0]
if val < left:
left = val
if val > right:
right = val
# Y Range
val = bb_world[i][1]
if val < front:
front = val
if val > back:
back = val
# Z Range
val = bb_world[i][2]
if val < down:
down = val
if val > up:
up = val
return (Vector((left, front, up)), Vector((right, back, down)))
def align_objects(align_x, align_y, align_z, align_mode, relative_to):
def GlobalBB_HQ(obj):
matrix_world = obj.matrix_world.copy()
# Initialize the variables with the last vertex
verts = obj.data.vertices
val = verts[-1].co * matrix_world
left, right, front, back, down, up =\
val[0],\
val[0],\
val[1],\
val[1],\
val[2],\
val[2]
# Test against all other verts
for i in range (len(verts)-1):
vco = verts[i].co * matrix_world
# X Range
val = vco[0]
if val < left:
left = val
if val > right:
right = val
# Y Range
val = vco[1]
if val < front:
front = val
if val > back:
back = val
# Z Range
val = vco[2]
if val < down:
down = val
if val > up:
up = val
return (Vector((left, front, up)), Vector((right, back, down)))
def align_objects(align_x, align_y, align_z, align_mode, relative_to, bb_quality):
cursor = bpy.context.scene.cursor_location
Left_Up_Front_SEL = [0.0, 0.0, 0.0]
Right_Down_Back_SEL = [0.0, 0.0, 0.0]
Left_Front_Up_SEL = [0.0, 0.0, 0.0]
Right_Back_Down_SEL = [0.0, 0.0, 0.0]
flag_first = True
@@ -42,80 +131,89 @@ def align_objects(align_x, align_y, align_z, align_mode, relative_to):
return False
for obj, bb_world in objs:
Left_Up_Front = bb_world[1]
Right_Down_Back = bb_world[7]
if bb_quality:
GBB = GlobalBB_HQ(obj)
else:
GBB = GlobalBB_LQ(bb_world)
Left_Front_Up = GBB[0]
Right_Back_Down = GBB[1]
# Active Center
if obj == bpy.context.active_object:
center_active_x = (Left_Up_Front[0] + Right_Down_Back[0]) / 2.0
center_active_y = (Left_Up_Front[1] + Right_Down_Back[1]) / 2.0
center_active_z = (Left_Up_Front[2] + Right_Down_Back[2]) / 2.0
center_active_x = (Left_Front_Up[0] + Right_Back_Down[0]) / 2.0
center_active_y = (Left_Front_Up[1] + Right_Back_Down[1]) / 2.0
center_active_z = (Left_Front_Up[2] + Right_Back_Down[2]) / 2.0
size_active_x = (Right_Down_Back[0] - Left_Up_Front[0]) / 2.0
size_active_y = (Right_Down_Back[1] - Left_Up_Front[1]) / 2.0
size_active_z = (Left_Up_Front[2] - Right_Down_Back[2]) / 2.0
size_active_x = (Right_Back_Down[0] - Left_Front_Up[0]) / 2.0
size_active_y = (Right_Back_Down[1] - Left_Front_Up[1]) / 2.0
size_active_z = (Left_Front_Up[2] - Right_Back_Down[2]) / 2.0
# Selection Center
if flag_first:
flag_first = False
Left_Up_Front_SEL[0] = Left_Up_Front[0]
Left_Up_Front_SEL[1] = Left_Up_Front[1]
Left_Up_Front_SEL[2] = Left_Up_Front[2]
Left_Front_Up_SEL[0] = Left_Front_Up[0]
Left_Front_Up_SEL[1] = Left_Front_Up[1]
Left_Front_Up_SEL[2] = Left_Front_Up[2]
Right_Down_Back_SEL[0] = Right_Down_Back[0]
Right_Down_Back_SEL[1] = Right_Down_Back[1]
Right_Down_Back_SEL[2] = Right_Down_Back[2]
Right_Back_Down_SEL[0] = Right_Back_Down[0]
Right_Back_Down_SEL[1] = Right_Back_Down[1]
Right_Back_Down_SEL[2] = Right_Back_Down[2]
else:
# X axis
if Left_Up_Front[0] < Left_Up_Front_SEL[0]:
Left_Up_Front_SEL[0] = Left_Up_Front[0]
if Left_Front_Up[0] < Left_Front_Up_SEL[0]:
Left_Front_Up_SEL[0] = Left_Front_Up[0]
# Y axis
if Left_Up_Front[1] < Left_Up_Front_SEL[1]:
Left_Up_Front_SEL[1] = Left_Up_Front[1]
if Left_Front_Up[1] < Left_Front_Up_SEL[1]:
Left_Front_Up_SEL[1] = Left_Front_Up[1]
# Z axis
if Left_Up_Front[2] > Left_Up_Front_SEL[2]:
Left_Up_Front_SEL[2] = Left_Up_Front[2]
if Left_Front_Up[2] > Left_Front_Up_SEL[2]:
Left_Front_Up_SEL[2] = Left_Front_Up[2]
# X axis
if Right_Down_Back[0] > Right_Down_Back_SEL[0]:
Right_Down_Back_SEL[0] = Right_Down_Back[0]
if Right_Back_Down[0] > Right_Back_Down_SEL[0]:
Right_Back_Down_SEL[0] = Right_Back_Down[0]
# Y axis
if Right_Down_Back[1] > Right_Down_Back_SEL[1]:
Right_Down_Back_SEL[1] = Right_Down_Back[1]
if Right_Back_Down[1] > Right_Back_Down_SEL[1]:
Right_Back_Down_SEL[1] = Right_Back_Down[1]
# Z axis
if Right_Down_Back[2] < Right_Down_Back_SEL[2]:
Right_Down_Back_SEL[2] = Right_Down_Back[2]
if Right_Back_Down[2] < Right_Back_Down_SEL[2]:
Right_Back_Down_SEL[2] = Right_Back_Down[2]
center_sel_x = (Left_Up_Front_SEL[0] + Right_Down_Back_SEL[0]) / 2.0
center_sel_y = (Left_Up_Front_SEL[1] + Right_Down_Back_SEL[1]) / 2.0
center_sel_z = (Left_Up_Front_SEL[2] + Right_Down_Back_SEL[2]) / 2.0
center_sel_x = (Left_Front_Up_SEL[0] + Right_Back_Down_SEL[0]) / 2.0
center_sel_y = (Left_Front_Up_SEL[1] + Right_Back_Down_SEL[1]) / 2.0
center_sel_z = (Left_Front_Up_SEL[2] + Right_Back_Down_SEL[2]) / 2.0
# Main Loop
for obj, bb_world in objs:
loc_world = obj.location
bb_world = [Vector(v[:]) * obj.matrix_world for v in obj.bound_box]
if bb_quality:
GBB = GlobalBB_HQ(obj)
else:
GBB = GlobalBB_LQ(bb_world)
Left_Front_Up = GBB[0]
Right_Back_Down = GBB[1]
Left_Up_Front = bb_world[1]
Right_Down_Back = bb_world[7]
center_x = (Left_Front_Up[0] + Right_Back_Down[0]) / 2.0
center_y = (Left_Front_Up[1] + Right_Back_Down[1]) / 2.0
center_z = (Left_Front_Up[2] + Right_Back_Down[2]) / 2.0
center_x = (Left_Up_Front[0] + Right_Down_Back[0]) / 2.0
center_y = (Left_Up_Front[1] + Right_Down_Back[1]) / 2.0
center_z = (Left_Up_Front[2] + Right_Down_Back[2]) / 2.0
positive_x = Right_Back_Down[0]
positive_y = Right_Back_Down[1]
positive_z = Left_Front_Up[2]
positive_x = Right_Down_Back[0]
positive_y = Right_Down_Back[1]
positive_z = Left_Up_Front[2]
negative_x = Left_Up_Front[0]
negative_y = Left_Up_Front[1]
negative_z = Right_Down_Back[2]
negative_x = Left_Front_Up[0]
negative_y = Left_Front_Up[1]
negative_z = Right_Back_Down[2]
obj_loc = obj.location
@@ -230,7 +328,7 @@ def align_objects(align_x, align_y, align_z, align_mode, relative_to):
return True
from bpy.props import EnumProperty
from bpy.props import EnumProperty, BoolProperty
class AlignObjects(bpy.types.Operator):
@@ -239,6 +337,11 @@ class AlignObjects(bpy.types.Operator):
bl_label = "Align Objects"
bl_options = {'REGISTER', 'UNDO'}
bb_quality = BoolProperty(
name="High Quality",
description="Enables high quality calculation of the bounding box for perfect results on complex shape meshes with rotation/scale (Slow)",
default=False)
align_mode = EnumProperty(items=(
('OPT_1', "Negative Sides", ""),
('OPT_2', "Centers", ""),
@@ -271,10 +374,10 @@ class AlignObjects(bpy.types.Operator):
def execute(self, context):
align_axis = self.align_axis
ret = align_objects('X' in align_axis, 'Y' in align_axis, 'Z' in align_axis, self.align_mode, self.relative_to)
ret = align_objects('X' in align_axis, 'Y' in align_axis, 'Z' in align_axis, self.align_mode, self.relative_to, self.bb_quality)
if not ret:
self.report({'WARNING'}, "No objects with bound-box selected")
return {'CANCELLED'}
else:
return {'FINISHED'}
return {'FINISHED'}

View File

@@ -132,7 +132,7 @@ class QuickExplode(bpy.types.Operator):
fake_context = bpy.context.copy()
obj_act = context.active_object
if obj_act.type != 'MESH':
if obj_act is None or obj_act.type != 'MESH':
self.report({'ERROR'}, "Active object is not a mesh")
return {'CANCELLED'}

View File

@@ -315,7 +315,7 @@ class AddPresetOperator(AddPresetBase, bpy.types.Operator):
@property
def preset_subdir(self):
return __class__.operator_path(self.operator)
return AddPresetOperator.operator_path(self.operator)
@property
def preset_values(self):

View File

@@ -78,7 +78,7 @@ class PlayRenderedAnim(bpy.types.Operator):
preset = prefs.filepaths.animation_player_preset
player_path = prefs.filepaths.animation_player
file_path = bpy.path.abspath(rd.filepath)
# file_path = bpy.path.abspath(rd.filepath) # UNUSED
is_movie = rd.is_movie_format
# try and guess a command line if it doesn't exist

View File

@@ -42,7 +42,6 @@ def extend(obj, operator, EXTEND_MODE):
edge_average_lengths = {}
OTHER_INDEX = 2, 3, 0, 1
FAST_INDICIES = 0, 2, 1, 3 # order is faster
def extend_uvs(face_source, face_target, edge_key):
'''

View File

@@ -406,7 +406,7 @@ def lightmap_uvpack(meshes,
ok = False
# Tall boxes in groups of 2
for d, boxes in odd_dict.items():
for d, boxes in list(odd_dict.items()):
if d[1] < max_int_dimension:
#\boxes.sort(key = lambda a: len(a.children))
while len(boxes) >= 2:
@@ -427,7 +427,7 @@ def lightmap_uvpack(meshes,
odd_dict.setdefault((w, h), []).append(pf_parent)
# Even boxes in groups of 4
for d, boxes in even_dict.items():
for d, boxes in list(even_dict.items()):
if d < max_int_dimension:
boxes.sort(key=lambda a: len(a.children))
@@ -444,7 +444,7 @@ def lightmap_uvpack(meshes,
del even_dict
del odd_dict
orig = len(pretty_faces)
# orig = len(pretty_faces)
pretty_faces = [pf for pf in pretty_faces if not pf.has_parent]
@@ -489,7 +489,10 @@ def lightmap_uvpack(meshes,
if PREF_APPLY_IMAGE:
if not PREF_PACK_IN_ONE:
image = Image.New("lightmap", PREF_IMG_PX_SIZE, PREF_IMG_PX_SIZE, 24)
image = bpy.data.images.new(name="lightmap",
width=PREF_IMG_PX_SIZE,
height=PREF_IMG_PX_SIZE,
)
for f in face_sel:
# f.image = image
@@ -530,7 +533,7 @@ def unwrap(operator, context, **kwargs):
return {'FINISHED'}
from bpy.props import BoolProperty, FloatProperty, IntProperty, EnumProperty
from bpy.props import BoolProperty, FloatProperty, IntProperty
class LightMapPack(bpy.types.Operator):

View File

@@ -746,13 +746,9 @@ def packIslands(islandList):
uv.y= (uv.y+yoffset) * yfactor
def VectoQuat(vec):
vec = vec.normalized()
if abs(vec.x) > 0.5:
return vec.to_track_quat('Z', 'X')
else:
return vec.to_track_quat('Z', 'Y')
return vec.to_track_quat('Z', 'X' if abs(vec.x) > 0.5 else 'Y').inverted()
class thickface(object):
@@ -791,7 +787,11 @@ def main_consts():
global ob
ob = None
def main(context, island_margin, projection_limit):
def main(context,
island_margin,
projection_limit,
user_area_weight,
):
global USER_FILL_HOLES
global USER_FILL_HOLES_QUALITY
global USER_STRETCH_ASPECT
@@ -844,7 +844,6 @@ def main(context, island_margin, projection_limit):
USER_FILL_HOLES = (0)
USER_FILL_HOLES_QUALITY = (50) # Only for hole filling.
USER_VIEW_INIT = (0) # Only for hole filling.
USER_AREA_WEIGHT = (1) # Only for hole filling.
# Reuse variable
if len(obList) == 1:
@@ -970,12 +969,15 @@ def main(context, island_margin, projection_limit):
# Add the average of all these faces normals as a projectionVec
averageVec = Vector((0.0, 0.0, 0.0))
if USER_AREA_WEIGHT:
for fprop in newProjectMeshFaces:
averageVec += (fprop.no * fprop.area)
else:
if user_area_weight == 0.0:
for fprop in newProjectMeshFaces:
averageVec += fprop.no
elif user_area_weight == 1.0:
for fprop in newProjectMeshFaces:
averageVec += fprop.no * fprop.area
else:
for fprop in newProjectMeshFaces:
averageVec += fprop.no * ((fprop.area * user_area_weight) + (1.0 - user_area_weight))
if averageVec.x != 0 or averageVec.y != 0 or averageVec.z != 0: # Avoid NAN
projectVecs.append(averageVec.normalized())
@@ -1062,7 +1064,7 @@ def main(context, island_margin, projection_limit):
f_uv = f.uv
for j, v in enumerate(f.v):
# XXX - note, between mathutils in 2.4 and 2.5 the order changed.
f_uv[j][:] = (v.co * MatQuat)[:2]
f_uv[j][:] = (v.co * MatQuat).xy
if USER_SHARE_SPACE:
@@ -1098,12 +1100,8 @@ def main(context, island_margin, projection_limit):
"""
pup_block = [\
'Projection',\
* ('Angle Limit:', USER_PROJECTION_LIMIT, 1, 89, ''),\
('Selected Faces Only', USER_ONLY_SELECTED_FACES, 'Use only selected faces from all selected meshes.'),\
('Init from view', USER_VIEW_INIT, 'The first projection will be from the view vector.'),\
('Area Weight', USER_AREA_WEIGHT, 'Weight projections vector by face area.'),\
'',\
'',\
'',\
'UV Layout',\
('Share Tex Space', USER_SHARE_SPACE, 'Objects Share texture space, map all objects into 1 uvmap.'),\
@@ -1125,11 +1123,15 @@ class SmartProject(bpy.types.Operator):
bl_options = {'REGISTER', 'UNDO'}
angle_limit = FloatProperty(name="Angle Limit",
description="lower for more projection groups, higher for less distortion.",
description="lower for more projection groups, higher for less distortion",
default=66.0, min=1.0, max=89.0)
island_margin = FloatProperty(name="Island Margin",
description="Margin to reduce bleed from adjacent islands.",
description="Margin to reduce bleed from adjacent islands",
default=0.0, min=0.0, max=1.0)
user_area_weight = FloatProperty(name="Area Weight",
description="Weight projections vector by faces with larger areas",
default=0.0, min=0.0, max=1.0)
@classmethod
@@ -1137,7 +1139,11 @@ class SmartProject(bpy.types.Operator):
return context.active_object != None
def execute(self, context):
main(context, self.island_margin, self.angle_limit)
main(context,
self.island_margin,
self.angle_limit,
self.user_area_weight,
)
return {'FINISHED'}
def invoke(self, context, event):

View File

@@ -19,7 +19,9 @@
# <pep8 compliant>
import bpy
from bpy.props import StringProperty, BoolProperty, IntProperty, FloatProperty
from bpy.props import StringProperty, BoolProperty, IntProperty, \
FloatProperty, EnumProperty
from rna_prop_ui import rna_idprop_ui_prop_get, rna_idprop_ui_prop_clear
@@ -457,6 +459,66 @@ doc_id = StringProperty(name="Doc ID",
doc_new = StringProperty(name="Edit Description",
description="", maxlen=1024, default="")
data_path_iter = StringProperty(
description="The data path relative to the context, must point to an iterable.")
data_path_item = StringProperty(
description="The data path from each iterable to the value (int or float)")
class WM_OT_context_collection_boolean_set(bpy.types.Operator):
'''Set boolean values for a collection of items'''
bl_idname = "wm.context_collection_boolean_set"
bl_label = "Context Collection Boolean Set"
bl_options = {'UNDO', 'REGISTER', 'INTERNAL'}
data_path_iter = data_path_iter
data_path_item = data_path_item
type = EnumProperty(items=(
('TOGGLE', "Toggle", ""),
('ENABLE', "Enable", ""),
('DISABLE', "Disable", ""),
),
name="Type")
def execute(self, context):
data_path_iter = self.data_path_iter
data_path_item = self.data_path_item
items = list(getattr(context, data_path_iter))
items_ok = []
is_set = False
for item in items:
try:
value_orig = eval("item." + data_path_item)
except:
continue
if value_orig == True:
is_set = True
elif value_orig == False:
pass
else:
self.report({'WARNING'}, "Non boolean value found: %s[ ].%s" %
(data_path_iter, data_path_item))
return {'CANCELLED'}
items_ok.append(item)
if self.type == 'ENABLE':
is_set = True
elif self.type == 'DISABLE':
is_set = False
else:
is_set = not is_set
exec_str = "item.%s = %s" % (data_path_item, is_set)
for item in items_ok:
exec(exec_str)
return {'FINISHED'}
class WM_OT_context_modal_mouse(bpy.types.Operator):
'''Adjust arbitrary values with mouse input'''
@@ -464,8 +526,9 @@ class WM_OT_context_modal_mouse(bpy.types.Operator):
bl_label = "Context Modal Mouse"
bl_options = {'GRAB_POINTER', 'BLOCKING', 'INTERNAL'}
data_path_iter = StringProperty(description="The data path relative to the context, must point to an iterable.")
data_path_item = StringProperty(description="The data path from each iterable to the value (int or float)")
data_path_iter = data_path_iter
data_path_item = data_path_item
input_scale = FloatProperty(default=0.01, description="Scale the mouse movement by this value before applying the delta")
invert = BoolProperty(default=False, description="Invert the mouse input")
initial_x = IntProperty(options={'HIDDEN'})

View File

@@ -94,4 +94,5 @@ class OnionSkinButtonsPanel():
col.prop(arm, "show_only_ghost_selected", text="Selected Only")
if __name__ == "__main__": # only for live edit.
import bpy
bpy.utils.register_module(__name__)

View File

@@ -299,10 +299,7 @@ class DATA_PT_onion_skinning(OnionSkinButtonsPanel): # , bpy.types.Panel): # in
return (context.object) and (context.armature)
def draw(self, context):
layout = self.layout
ob = context.object
self.draw_settings(context, ob.pose.animation_visualisation, bones=True)

View File

@@ -122,7 +122,6 @@ class DATA_PT_curve_texture_space(CurveButtonsPanel, bpy.types.Panel):
def draw(self, context):
layout = self.layout
ob = context.object
curve = context.curve
row = layout.row()

View File

@@ -290,9 +290,8 @@ class DATA_PT_texface(MeshButtonsPanel, bpy.types.Panel):
@classmethod
def poll(cls, context):
ob = context.active_object
return (context.mode == 'EDIT_MESH') and ob and ob.type == 'MESH'
obj = context.object
return (context.mode == 'EDIT_MESH') and obj and obj.type == 'MESH'
def draw(self, context):
layout = self.layout

View File

@@ -174,6 +174,7 @@ class MATERIAL_PT_pipeline(MaterialButtonsPanel, bpy.types.Panel):
row.prop(mat, "use_transparency")
sub = row.column()
sub.prop(mat, "offset_z")
sub.active = mat_type and mat.use_transparency and mat.transparency_method == 'Z_TRANSPARENCY'
row = layout.row()
@@ -199,6 +200,7 @@ class MATERIAL_PT_pipeline(MaterialButtonsPanel, bpy.types.Panel):
col.prop(mat, "shadow_cast_alpha", text="Casting Alpha")
col.prop(mat, "use_cast_buffer_shadows")
col.prop(mat, "use_cast_approximate")
col.prop(mat, "pass_index")
class MATERIAL_PT_diffuse(MaterialButtonsPanel, bpy.types.Panel):
@@ -729,6 +731,8 @@ class MATERIAL_PT_options(MaterialButtonsPanel, bpy.types.Panel):
col.prop(mat, "use_vertex_color_paint")
col.prop(mat, "use_vertex_color_light")
col.prop(mat, "use_object_color")
if simple_material(base_mat):
col.prop(mat, "pass_index")
class MATERIAL_PT_shadow(MaterialButtonsPanel, bpy.types.Panel):
@@ -883,7 +887,7 @@ class MATERIAL_PT_volume_lighting(VolumeButtonsPanel, bpy.types.Panel):
sub = col.column()
sub.enabled = True
sub.active = False
sub.prop(vol, "use_light_cache")
sub.label("Light Cache Enabled")
col.prop(vol, "cache_resolution")
sub = col.column(align=True)

View File

@@ -34,7 +34,6 @@ class OBJECT_PT_context_object(ObjectButtonsPanel, bpy.types.Panel):
def draw(self, context):
layout = self.layout
space = context.space_data
ob = context.object
if space.use_pin_id:
layout.template_ID(space, "pin_id")

View File

@@ -878,7 +878,7 @@ class PARTICLE_PT_render(ParticleButtonsPanel, bpy.types.Panel):
col.prop(part, "billboard_tilt_random", text="Random", slider=True)
col = row.column()
col.prop(part, "billboard_offset")
row = layout.row()
col = row.column()
col.prop(part, "billboard_size", text="Scale")

View File

@@ -142,6 +142,7 @@ class RENDER_PT_layers(RenderButtonsPanel, bpy.types.Panel):
col.prop(rl, "use_pass_uv")
col.prop(rl, "use_pass_mist")
col.prop(rl, "use_pass_object_index")
col.prop(rl, "use_pass_material_index")
col.prop(rl, "use_pass_color")
col = split.column()

View File

@@ -88,15 +88,15 @@ class TEXTURE_PT_context_texture(TextureButtonsPanel, bpy.types.Panel):
@classmethod
def poll(cls, context):
engine = context.scene.render.engine
if not hasattr(context, "texture_slot"):
if not (hasattr(context, "texture_slot") or hasattr(context, "texture_node")):
return False
return ((context.material or context.world or context.lamp or context.brush or context.texture or context.particle_system or isinstance(context.space_data.pin_id, bpy.types.ParticleSettings))
and (engine in cls.COMPAT_ENGINES))
def draw(self, context):
layout = self.layout
slot = context.texture_slot
node = context.texture_node
slot = getattr(context, "texture_slot", None)
node = getattr(context, "texture_node", None)
space = context.space_data
tex = context.texture
idblock = context_tex_datablock(context)
@@ -208,7 +208,7 @@ class TextureSlotPanel(TextureButtonsPanel):
return False
engine = context.scene.render.engine
return TextureButtonsPanel.poll(self, context) and (engine in cls.COMPAT_ENGINES)
return TextureButtonsPanel.poll(cls, context) and (engine in cls.COMPAT_ENGINES)
# Texture Type Panels #
@@ -393,7 +393,7 @@ class TEXTURE_PT_image_sampling(TextureTypePanel, bpy.types.Panel):
idblock = context_tex_datablock(context)
tex = context.texture
slot = context.texture_slot
slot = getattr(context, "texture_slot", None)
split = layout.split()
@@ -408,7 +408,7 @@ class TEXTURE_PT_image_sampling(TextureTypePanel, bpy.types.Panel):
col = split.column()
#Only for Material based textures, not for Lamp/World...
if isinstance(idblock, bpy.types.Material):
if slot and isinstance(idblock, bpy.types.Material):
col.prop(tex, "use_normal_map")
row = col.row()
row.active = tex.use_normal_map

View File

@@ -434,7 +434,6 @@ class IMAGE_PT_game_properties(bpy.types.Panel):
@classmethod
def poll(cls, context):
rd = context.scene.render
sima = context.space_data
# display even when not in game mode because these settings effect the 3d view
return (sima and sima.image) # and (rd.engine == 'BLENDER_GAME')
@@ -616,10 +615,9 @@ class IMAGE_PT_view_properties(bpy.types.Panel):
split = layout.split()
col = split.column()
col.prop(uvedit, "show_faces")
col.prop(uvedit, "show_smooth_edges", text="Smooth")
col.prop(uvedit, "show_modified_edges", text="Modified")
#col.prop(uvedit, "show_edges")
#col.prop(uvedit, "show_faces")
col = split.column()
col.prop(uvedit, "show_stretch", text="Stretch")

Some files were not shown because too many files have changed in this diff Show More