diff options
Diffstat (limited to 'o3d')
79 files changed, 1607 insertions, 6559 deletions
diff --git a/o3d/build/common.gypi b/o3d/build/common.gypi index 9f058c4..ca2b697 100644 --- a/o3d/build/common.gypi +++ b/o3d/build/common.gypi @@ -21,12 +21,12 @@ 'skiadir': 'third_party/skia/include', 'zlibdir': 'third_party/zlib', # If the DEPS file exists two levels up, then we're in a Chrome tree. - 'o3d_in_chrome%': '<!(python <(DEPTH)/o3d/build/file_exists.py ../../DEPS)', + 'o3d_in_chrome%': '<!(python <(DEPTH)/o3d/build/file_exists.py <(DEPTH)/DEPS)', # We default to building everything only if the assets exist. # (and the teapot is the least likely asset to change). # This is so that chrome developers get a much reduced dependency set. 'o3d_developer%': '<!(python <(DEPTH)/o3d/build/file_exists.py ' - '../o3d_assets/samples/convert_assets/teapot.zip)', + '<(DEPTH)/o3d/o3d_assets/samples/convert_assets/teapot.zip)', 'selenium_screenshots%': 0, 'conditions' : [ # These have to come first because GYP doesn't like it when @@ -72,7 +72,7 @@ }], ], 'conditions': [ - ['o3d_in_chrome != 0', + ['o3d_in_chrome == "True"', { 'defines': [ 'O3D_IN_CHROME', diff --git a/o3d/command_buffer/client/build.scons b/o3d/command_buffer/client/build.scons deleted file mode 100644 index eeefca6..0000000 --- a/o3d/command_buffer/client/build.scons +++ /dev/null @@ -1,70 +0,0 @@ -# Copyright 2009, Google Inc. -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: -# -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following disclaimer -# in the documentation and/or other materials provided with the -# distribution. -# * Neither the name of Google Inc. nor the names of its -# contributors may be used to endorse or promote products derived from -# this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - -Import('env') - -INPUTS = [ - 'cross/buffer_sync_proxy.cc', - 'cross/cmd_buffer_helper.cc', - 'cross/effect_helper.cc', - 'cross/fenced_allocator.cc', - 'cross/id_allocator.cc', -] - -# Create a target library from the sources called 'o3dCmdBuf' -o3dcmdbuf_lib = env.ComponentLibrary('o3dCmdBuf_client', INPUTS) - -# Add some flags and libraries to the build environment for the unit tests -env.Append( - LIBS = [ - 'o3dCmdBuf_client', - 'o3dCmdBuf_common', - ] + env['NACL_HTP_LIBS'], - LIBPATH = ['$NACL_LIB_DIR'], -) - -if env['TARGET_PLATFORM'] == 'WINDOWS': - env.Append(CCFLAGS = ['/Wp64'], - LINKFLAGS=['/SUBSYSTEM:CONSOLE']) - -if env['TARGET_PLATFORM'] != 'NACL': - env.Append(LIBS = ['o3d_base'] + env['ICU_LIBS']) - -# Build the big tests -BIG_TEST_CLIENT = [ - 'cross/big_test_client.cc', -] - -# Create a target executable program called 'o3dCmdBuf_bigtest_client' from the -# list of big test client files. -big_test_client = env.Program('o3dCmdBuf_bigtest_client', BIG_TEST_CLIENT) - -# Copy the resulting executable to the Artifacts directory. -env.Replicate('$ARTIFACTS_DIR', big_test_client) diff --git a/o3d/command_buffer/client/cross/big_test_client.cc b/o3d/command_buffer/client/cross/big_test_client.cc deleted file mode 100644 index 676b21b..0000000 --- a/o3d/command_buffer/client/cross/big_test_client.cc +++ /dev/null @@ -1,300 +0,0 @@ -/* - * Copyright 2009, Google Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - - -#include <math.h> -#ifdef __native_client__ -#include <sys/nacl_syscalls.h> -#else -#include "third_party/native_client/googleclient/native_client/src/trusted/desc/nrd_all_modules.h" -#endif -#include "command_buffer/common/cross/gapi_interface.h" -#include "command_buffer/common/cross/rpc_imc.h" -#include "command_buffer/client/cross/cmd_buffer_helper.h" -#include "command_buffer/client/cross/buffer_sync_proxy.h" -#include "third_party/vectormath/files/vectormathlibrary/include/vectormath/scalar/cpp/vectormath_aos.h" // NOLINT - -namespace o3d { -namespace command_buffer { - -namespace math = Vectormath::Aos; - -// Adds a SetViewport command into the buffer. -// Parameters: -// cmd_buffer: the command buffer helper. -// x, y, width, height: the dimensions of the Viewport. -// z_near, z_far: the near and far clip plane distances. -void SetViewportCmd(CommandBufferHelper *cmd_buffer, - unsigned int x, - unsigned int y, - unsigned int width, - unsigned int height, - float z_near, - float z_far) { - cmd_buffer->SetViewport(x, y, width, height, z_near, z_far); -} - -// Copy a data buffer to args, for IMMEDIATE commands. Returns the number of -// args used. -unsigned int CopyToArgs(CommandBufferEntry *args, - const void *data, - size_t size) { - memcpy(args, data, size); - const unsigned int arg_size = sizeof(args[0]); - return static_cast<unsigned int>((size + arg_size - 1) / arg_size); -} - -// Our effect: pass through position and UV, look up texture. -// This follows the command buffer effect format : -// vertex_program_entry \0 fragment_program_entry \0 effect_code. -const char effect_data[] = - "vs\0" // Vertex program entry point - "ps\0" // Fragment program entry point - "struct a2v {float4 pos: POSITION; float2 uv: TEXCOORD0;};\n" - "struct v2f {float4 pos: POSITION; float2 uv: TEXCOORD0;};\n" - "float4x4 worldViewProj : WorldViewProjection;\n" - "v2f vs(a2v i) {\n" - " v2f o;\n" - " o.pos = mul(i.pos, worldViewProj);\n" - " o.uv = i.uv;\n" - " return o;\n" - "}\n" - "sampler s0;\n" - "float4 ps(v2f i) : COLOR { return tex2D(s0, i.uv); }\n"; - -// Custom vertex, with position and color. -struct CustomVertex { - float x, y, z, w; - float u, v; -}; - -void BigTestClient(nacl::HtpHandle handle) { - IMCSender sender(handle); - BufferSyncProxy proxy(&sender); - - proxy.InitConnection(); - const int kShmSize = 2048; - RPCShmHandle shm = CreateShm(kShmSize); - void *shm_address = MapShm(shm, kShmSize); - unsigned int shm_id = proxy.RegisterSharedMemory(shm, kShmSize); - - { - CommandBufferHelper cmd_buffer(&proxy); - cmd_buffer.Init(500); - - // Clear the buffers. - RGBA color = {0.2f, 0.2f, 0.2f, 1.f}; - cmd_buffer.Clear(command_buffer::kColor | command_buffer::kDepth, - color.red, color.green, color.blue, color.alpha, - 1.f, 0); - - const ResourceId vertex_buffer_id = 1; - const ResourceId vertex_struct_id = 1; - - static const CustomVertex vertices[4] = { - {-.5f, -.5f, 0.f, 1.f, 0, 0}, - {.5f, -.5f, 0.f, 1.f, 1, 0}, - {-.5f, .5f, 0.f, 1.f, 0, 1}, - {.5f, .5f, 0.f, 1.f, 1, 1}, - }; - cmd_buffer.CreateVertexBuffer(vertex_buffer_id, sizeof(vertices), - vertex_buffer::kNone); - - memcpy(shm_address, vertices, sizeof(vertices)); - cmd_buffer.SetVertexBufferData( - vertex_buffer_id, 0, sizeof(vertices), shm_id, 0); - unsigned int token = cmd_buffer.InsertToken(); - - cmd_buffer.CreateVertexStruct(vertex_struct_id, 2); - - // Set POSITION input stream - cmd_buffer.SetVertexInput(vertex_struct_id, 0, vertex_buffer_id, 0, - vertex_struct::kPosition, 0, - vertex_struct::kFloat4, sizeof(CustomVertex)); - - // Set TEXCOORD0 input stream - cmd_buffer.SetVertexInput(vertex_struct_id, 1, vertex_buffer_id, 16, - vertex_struct::kTexCoord, 0, - vertex_struct::kFloat2, sizeof(CustomVertex)); - - // wait for previous transfer to be executed, so that we can re-use the - // transfer shared memory buffer. - cmd_buffer.WaitForToken(token); - memcpy(shm_address, effect_data, sizeof(effect_data)); - const ResourceId effect_id = 1; - cmd_buffer.CreateEffect(effect_id, sizeof(effect_data), shm_id, 0); - token = cmd_buffer.InsertToken(); - - // Create a 4x4 2D texture. - const ResourceId texture_id = 1; - cmd_buffer.CreateTexture2d(texture_id, 4, 4, 1, texture::kARGB8, 0); - - static const unsigned int texels[4] = { - 0xff0000ff, - 0xffff00ff, - 0xff00ffff, - 0xffffffff, - }; - // wait for previous transfer to be executed, so that we can re-use the - // transfer shared memory buffer. - cmd_buffer.WaitForToken(token); - memcpy(shm_address, texels, sizeof(texels)); - // Creates a 4x4 texture by uploading 2x2 data in each quadrant. - for (unsigned int x = 0; x < 2; ++x) - for (unsigned int y = 0; y < 2; ++y) { - cmd_buffer.SetTextureData(texture_id, x * 2, y * 2, 0, 2, 2, 1, 0, - texture::kFaceNone, - sizeof(texels[0]) * 2, // row_pitch - 0, // slice_pitch - sizeof(texels), // size - shm_id, - 0); - } - token = cmd_buffer.InsertToken(); - - const ResourceId sampler_id = 1; - cmd_buffer.CreateSampler(sampler_id); - cmd_buffer.SetSamplerTexture(sampler_id, texture_id); - cmd_buffer.SetSamplerStates(sampler_id, - sampler::kClampToEdge, - sampler::kClampToEdge, - sampler::kClampToEdge, - sampler::kPoint, - sampler::kPoint, - sampler::kNone, - 1); - - // Create a parameter for the sampler. - const ResourceId sampler_param_id = 1; - { - static const char param_name[] = "s0"; - cmd_buffer.CreateParamByNameImmediate(sampler_param_id, effect_id, - sizeof(param_name), param_name); - } - - const ResourceId matrix_param_id = 2; - { - static const char param_name[] = "worldViewProj"; - cmd_buffer.CreateParamByNameImmediate(matrix_param_id, effect_id, - sizeof(param_name), param_name); - } - - float t = 0.f; - while (true) { - t = fmodf(t + .01f, 1.f); - math::Matrix4 m = - math::Matrix4::translation(math::Vector3(0.f, 0.f, .5f)); - m *= math::Matrix4::rotationY(t * 2 * 3.1415926f); - cmd_buffer.BeginFrame(); - // Clear the background with an animated color (black to red). - cmd_buffer.Clear(command_buffer::kColor | command_buffer::kDepth, - color.red, color.green, color.blue, color.alpha, - 1.f, 0); - - cmd_buffer.SetVertexStruct(vertex_struct_id); - cmd_buffer.SetEffect(effect_id); - cmd_buffer.SetParamDataImmediate( - sampler_param_id, sizeof(uint32), &sampler_id); // NOLINT - cmd_buffer.SetParamDataImmediate( - matrix_param_id, sizeof(m), &m); - cmd_buffer.Draw(command_buffer::kTriangleStrips, 0, 2); - - cmd_buffer.EndFrame(); - cmd_buffer.Flush(); - } - - cmd_buffer.Finish(); - } - - proxy.CloseConnection(); - proxy.UnregisterSharedMemory(shm_id); - DestroyShm(shm); - - sender.SendCall(POISONED_MESSAGE_ID, NULL, 0, NULL, 0); -} - -} // namespace command_buffer -} // namespace o3d - -nacl::HtpHandle InitConnection(int argc, char **argv) { - nacl::Handle handle = nacl::kInvalidHandle; -#ifndef __native_client__ - NaClNrdAllModulesInit(); - - static nacl::SocketAddress g_address = { "command-buffer" }; - static nacl::SocketAddress g_local_address = { "cb-client" }; - - nacl::Handle sockets[2]; - nacl::SocketPair(sockets); - - nacl::MessageHeader msg; - msg.iov = NULL; - msg.iov_length = 0; - msg.handles = &sockets[1]; - msg.handle_count = 1; - nacl::Handle local_socket = nacl::BoundSocket(&g_local_address); - nacl::SendDatagramTo(local_socket, &msg, 0, &g_address); - nacl::Close(local_socket); - nacl::Close(sockets[1]); - handle = sockets[0]; -#else - if (argc < 3 || strcmp(argv[1], "-fd") != 0) { - fprintf(stderr, "Usage: %s -fd file_descriptor\n", argv[0]); - return nacl::kInvalidHtpHandle; - } - int fd = atoi(argv[2]); - handle = imc_connect(fd); - if (handle < 0) { - fprintf(stderr, "Could not connect to file descriptor %d.\n" - "Did you use the -a and -X options to sel_ldr ?\n", fd); - return nacl::kInvalidHtpHandle; - } -#endif - return nacl::CreateImcDesc(handle); -} - -void CloseConnection(nacl::HtpHandle handle) { - nacl::Close(handle); -#ifndef __native_client__ - NaClNrdAllModulesFini(); -#endif -} - -int main(int argc, char **argv) { - nacl::HtpHandle htp_handle = InitConnection(argc, argv); - if (htp_handle == nacl::kInvalidHtpHandle) { - return 1; - } - - o3d::command_buffer::BigTestClient(htp_handle); - CloseConnection(htp_handle); - return 0; -} diff --git a/o3d/command_buffer/client/cross/buffer_sync_proxy.cc b/o3d/command_buffer/client/cross/buffer_sync_proxy.cc deleted file mode 100644 index 8439085..0000000 --- a/o3d/command_buffer/client/cross/buffer_sync_proxy.cc +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Copyright 2009, Google Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - - -// This file has the implementation of the Command Buffer Synchronous API RPC -// glue, client-side (proxy). - -#include "command_buffer/client/cross/buffer_sync_proxy.h" -#include "command_buffer/service/cross/buffer_rpc.h" - -namespace o3d { -namespace command_buffer { - -// Implements the proxy InitConnection, forwarding the call with its argument to -// the RPC server. -void BufferSyncProxy::InitConnection() { - server_->SendCall(BufferRPCImpl::INIT_CONNECTION, NULL, 0, NULL, 0); -} - -// Implements the proxy CloseConnection, forwarding the call to the RPC server. -void BufferSyncProxy::CloseConnection() { - server_->SendCall(BufferRPCImpl::CLOSE_CONNECTION, NULL, 0, NULL, 0); -} - -unsigned int BufferSyncProxy::RegisterSharedMemory(RPCShmHandle buffer, - size_t size) { - RPCHandle handles[1] = {buffer}; - return server_->SendCall(BufferRPCImpl::REGISTER_SHARED_MEMORY, &size, - sizeof(size), handles, 1); -} - -void BufferSyncProxy::UnregisterSharedMemory(unsigned int shm_id) { - server_->SendCall(BufferRPCImpl::UNREGISTER_SHARED_MEMORY, &shm_id, - sizeof(shm_id), NULL, 0); -} - -// Implements the proxy SetCommandBuffer, forwarding the call with its -// arguments to the RPC server. -void BufferSyncProxy::SetCommandBuffer(unsigned int shm_id, - ptrdiff_t offset, - size_t size, - CommandBufferOffset start_get) { - BufferRPCImpl::SetCommandBufferStruct params; - params.shm_id = shm_id; - params.offset = offset; - params.size = size; - params.start_get = start_get; - server_->SendCall(BufferRPCImpl::SET_COMMAND_BUFFER, ¶ms, sizeof(params), - NULL, 0); -} - -// Implements the proxy Put, forwarding the call with its argument to the RPC -// server. -void BufferSyncProxy::Put(CommandBufferOffset offset) { - server_->SendCall(BufferRPCImpl::PUT, &offset, sizeof(offset), NULL, 0); -} - -// Implements the proxy Get, forwarding the call to the RPC server. -CommandBufferOffset BufferSyncProxy::Get() { - return server_->SendCall(BufferRPCImpl::GET, NULL, 0, NULL, 0); -} - -// Implements the proxy GetToken, forwarding the call to the RPC server. -unsigned int BufferSyncProxy::GetToken() { - return server_->SendCall(BufferRPCImpl::GET_TOKEN, NULL, 0, NULL, 0); -} - -// Implements the proxy WaitGetChanges, forwarding the call with its argument -// to the RPC server. -CommandBufferOffset BufferSyncProxy::WaitGetChanges( - CommandBufferOffset current_value) { - return server_->SendCall(BufferRPCImpl::WAIT_GET_CHANGES, ¤t_value, - sizeof(current_value), NULL, 0); -} - -// Implements the proxy SignalGetChanges, forwarding the call with its -// arguments to the RPC server. -void BufferSyncProxy::SignalGetChanges(CommandBufferOffset current_value, - int rpc_message_id) { - BufferRPCImpl::SignalGetChangesStruct params; - params.current_value = current_value; - params.rpc_message_id = rpc_message_id; - server_->SendCall(BufferRPCImpl::SIGNAL_GET_CHANGES, ¶ms, sizeof(params), - NULL, 0); -} - -// Implements the proxy GetStatus, forwarding the call to the RPC server. -BufferSyncInterface::ParserStatus BufferSyncProxy::GetStatus() { - return static_cast<BufferSyncInterface::ParserStatus>( - server_->SendCall(BufferRPCImpl::GET_STATUS, NULL, 0, NULL, 0)); -} - -// Implements the proxy GetParseError, forwarding the call to the RPC server. -BufferSyncInterface::ParseError BufferSyncProxy::GetParseError() { - return static_cast<ParseError>( - server_->SendCall(BufferRPCImpl::GET_PARSE_ERROR, NULL, 0, NULL, 0)); -} - -} // namespace command_buffer -} // namespace o3d diff --git a/o3d/command_buffer/client/cross/buffer_sync_proxy.h b/o3d/command_buffer/client/cross/buffer_sync_proxy.h deleted file mode 100644 index 341b935..0000000 --- a/o3d/command_buffer/client/cross/buffer_sync_proxy.h +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright 2009, Google Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - - -// This file defines the RPC glue for the Command Buffer Synchronous API, -// client side: a proxy implementation of BufferSyncInterface, forwarding calls -// to a RPC send interface. - -#ifndef O3D_COMMAND_BUFFER_CLIENT_CROSS_BUFFER_SYNC_PROXY_H_ -#define O3D_COMMAND_BUFFER_CLIENT_CROSS_BUFFER_SYNC_PROXY_H_ - -#include "command_buffer/common/cross/rpc.h" -#include "command_buffer/common/cross/buffer_sync_api.h" - -namespace o3d { -namespace command_buffer { - -// Class implementing the Command Buffer Synchronous API, forwarding all the -// calls to a RPC server, according to the (trivial) protocol defined in -// BufferRPCImpl. -class BufferSyncProxy : public BufferSyncInterface { - public: - explicit BufferSyncProxy(RPCSendInterface *server) : server_(server) {} - virtual ~BufferSyncProxy() {} - - // Implements the InitConnection call, forwarding it to the RPC server. - virtual void InitConnection(); - - // Implements the CloseConnection call, forwarding it to the RPC server. - virtual void CloseConnection(); - - // Implements the RegisterSharedMemory call, forwarding it to the RPC server. - virtual unsigned int RegisterSharedMemory(RPCShmHandle buffer, size_t size); - - // Implements the UnregisterSharedMemory call, forwarding it to the RPC - // server. - virtual void UnregisterSharedMemory(unsigned int shm_id); - - // Implements the SetCommandBuffer call, forwarding it to the RPC server. - virtual void SetCommandBuffer(unsigned int shm_id, - ptrdiff_t offset, - size_t size, - CommandBufferOffset start_get); - - // Implements the Put call, forwarding it to the RPC server. - virtual void Put(CommandBufferOffset offset); - - // Implements the Get call, forwarding it to the RPC server. - virtual CommandBufferOffset Get(); - - // Implements the GetToken call, forwarding it to the RPC server. - virtual unsigned int GetToken(); - - // Implements the WaitGetChanges call, forwarding it to the RPC server. - virtual CommandBufferOffset WaitGetChanges( - CommandBufferOffset current_value); - - // Implements the SignalGetChanges call, forwarding it to the RPC server. - virtual void SignalGetChanges(CommandBufferOffset current_value, - int rpc_message_id); - - // Implements the GetStatus call, forwarding it to the RPC server. - virtual ParserStatus GetStatus(); - - // Implements the GetParseError call, forwarding it to the RPC server. - virtual ParseError GetParseError(); - private: - RPCSendInterface *server_; -}; - -} // namespace command_buffer -} // namespace o3d - -#endif // O3D_COMMAND_BUFFER_CLIENT_CROSS_BUFFER_SYNC_PROXY_H_ diff --git a/o3d/command_buffer/client/cross/buffer_sync_proxy_test.cc b/o3d/command_buffer/client/cross/buffer_sync_proxy_test.cc deleted file mode 100644 index c5d473f..0000000 --- a/o3d/command_buffer/client/cross/buffer_sync_proxy_test.cc +++ /dev/null @@ -1,260 +0,0 @@ -/* - * Copyright 2009, Google Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - - -// Tests for the Command Buffer RPC glue, client side (proxy). - -#include "base/scoped_ptr.h" -#include "tests/common/win/testing_common.h" -#include "command_buffer/client/cross/buffer_sync_proxy.h" -#include "command_buffer/common/cross/mocks.h" -#include "command_buffer/service/cross/buffer_rpc.h" - -namespace o3d { -namespace command_buffer { - -using testing::Return; - -// Test fixture for BufferSyncProxy test - Creates a BufferSyncProxy, using a -// mock RPCSendInterface. -class BufferSyncProxyTest : public testing::Test { - protected: - virtual void SetUp() { - server_mock_.reset(new RPCSendInterfaceMock); - proxy_.reset(new BufferSyncProxy(server_mock_.get())); - } - virtual void TearDown() {} - - RPCSendInterfaceMock *server_mock() { return server_mock_.get(); } - BufferSyncProxy *proxy() { return proxy_.get(); } - private: - scoped_ptr<RPCSendInterfaceMock> server_mock_; - scoped_ptr<BufferSyncProxy> proxy_; -}; - -// Tests the implementation of InitConnection, checking that it sends the -// correct message. -TEST_F(BufferSyncProxyTest, TestInitConnection) { - RPCSendInterfaceMock::SendCallExpect expect; - expect._return = 0; - expect.message_id = BufferRPCImpl::INIT_CONNECTION; - expect.data = NULL; - expect.size = 0; - expect.handles = NULL; - expect.handle_count = 0; - server_mock()->AddSendCallExpect(expect); - - proxy()->InitConnection(); -} - -// Tests the implementation of CloseConnection, checking that it sends the -// correct message. -TEST_F(BufferSyncProxyTest, TestCloseConnection) { - RPCSendInterfaceMock::SendCallExpect expect; - expect._return = 0; - expect.message_id = BufferRPCImpl::CLOSE_CONNECTION; - expect.data = NULL; - expect.size = 0; - expect.handles = NULL; - expect.handle_count = 0; - server_mock()->AddSendCallExpect(expect); - - proxy()->CloseConnection(); -} - -// Tests the implementation of RegisterSharedMemory, checking that it sends the -// correct message and returns the correct value. -TEST_F(BufferSyncProxyTest, TestRegisterSharedMemory) { - RPCShmHandle shm = reinterpret_cast<RPCShmHandle>(456); - RPCHandle handles[1] = {shm}; - size_t size = 789; - RPCSendInterfaceMock::SendCallExpect expect; - expect._return = 123; - expect.message_id = BufferRPCImpl::REGISTER_SHARED_MEMORY; - expect.data = &size; - expect.size = sizeof(size); - expect.handles = handles; - expect.handle_count = 1; - server_mock()->AddSendCallExpect(expect); - - EXPECT_EQ(123u, proxy()->RegisterSharedMemory(shm, size)); -} - -// Tests the implementation of UnregisterSharedMemory, checking that it sends -// the correct message. -TEST_F(BufferSyncProxyTest, TestUnregisterSharedMemory) { - unsigned int shm_id = 456; - RPCSendInterfaceMock::SendCallExpect expect; - expect._return = 0; - expect.message_id = BufferRPCImpl::UNREGISTER_SHARED_MEMORY; - expect.data = &shm_id; - expect.size = sizeof(shm_id); - expect.handles = NULL; - expect.handle_count = 0; - server_mock()->AddSendCallExpect(expect); - - proxy()->UnregisterSharedMemory(456); -} - -// Tests the implementation of SetCommandBuffer, checking that it sends the -// correct message. -TEST_F(BufferSyncProxyTest, TestSetCommandBuffer) { - BufferRPCImpl::SetCommandBufferStruct params; - params.shm_id = 53; - params.offset = 1234; - params.size = 5678; - params.start_get = 42; - - RPCSendInterfaceMock::SendCallExpect expect; - expect._return = 0; - expect.message_id = BufferRPCImpl::SET_COMMAND_BUFFER; - expect.data = ¶ms; - expect.size = sizeof(params); - expect.handles = NULL; - expect.handle_count = 0; - server_mock()->AddSendCallExpect(expect); - - proxy()->SetCommandBuffer(53, 1234, 5678, 42); -} - -// Tests the implementation of Put, checking that it sends the correct message. -TEST_F(BufferSyncProxyTest, TestPut) { - RPCSendInterfaceMock::SendCallExpect expect; - expect._return = 0; - expect.message_id = BufferRPCImpl::PUT; - CommandBufferOffset value = 67; - expect.data = &value; - expect.size = sizeof(value); - expect.handles = NULL; - expect.handle_count = 0; - server_mock()->AddSendCallExpect(expect); - - proxy()->Put(67); -} - -// Tests the implementation of Get, checking that it sends the correct message -// and returns the correct value. -TEST_F(BufferSyncProxyTest, TestGet) { - RPCSendInterfaceMock::SendCallExpect expect; - expect._return = 72; - expect.message_id = BufferRPCImpl::GET; - expect.data = NULL; - expect.size = 0; - expect.handles = NULL; - expect.handle_count = 0; - server_mock()->AddSendCallExpect(expect); - - EXPECT_EQ(72u, proxy()->Get()); -} - -// Tests the implementation of GetToken, checking that it sends the correct -// message and returns the correct value. -TEST_F(BufferSyncProxyTest, TestGetToken) { - RPCSendInterfaceMock::SendCallExpect expect; - expect._return = 38; - expect.message_id = BufferRPCImpl::GET_TOKEN; - expect.data = NULL; - expect.size = 0; - expect.handles = NULL; - expect.handle_count = 0; - server_mock()->AddSendCallExpect(expect); - - EXPECT_EQ(38u, proxy()->GetToken()); -} - -// Tests the implementation of WaitGetChanges, checking that it sends the -// correct message and returns the correct value. -TEST_F(BufferSyncProxyTest, TestWaitGetChanges) { - RPCSendInterfaceMock::SendCallExpect expect; - expect._return = 53; - expect.message_id = BufferRPCImpl::WAIT_GET_CHANGES; - CommandBufferOffset value = 101; - expect.data = &value; - expect.size = sizeof(value); - expect.handles = NULL; - expect.handle_count = 0; - server_mock()->AddSendCallExpect(expect); - - EXPECT_EQ(53u, proxy()->WaitGetChanges(101)); -} - -// Tests the implementation of SignalGetChanges, checking that it sends the -// correct message. -TEST_F(BufferSyncProxyTest, TestSignalGetChanges) { - BufferRPCImpl::SignalGetChangesStruct params; - params.current_value = 3141; - params.rpc_message_id = 5926; - - RPCSendInterfaceMock::SendCallExpect expect; - expect._return = 0; - expect.message_id = BufferRPCImpl::SIGNAL_GET_CHANGES; - expect.data = ¶ms; - expect.size = sizeof(params); - expect.handles = NULL; - expect.handle_count = 0; - server_mock()->AddSendCallExpect(expect); - - proxy()->SignalGetChanges(3141, 5926); -} - -// Tests the implementation of GetStatus, checking that it sends the correct -// message and returns the correct value. -TEST_F(BufferSyncProxyTest, TestGetStatus) { - RPCSendInterfaceMock::SendCallExpect expect; - expect._return = BufferSyncInterface::kParsing; - expect.message_id = BufferRPCImpl::GET_STATUS; - expect.data = NULL; - expect.size = 0; - expect.handles = NULL; - expect.handle_count = 0; - server_mock()->AddSendCallExpect(expect); - - EXPECT_EQ(BufferSyncInterface::kParsing, proxy()->GetStatus()); -} - -// Tests the implementation of GetParseError, checking that it sends the correct -// message and returns the correct value. -TEST_F(BufferSyncProxyTest, TestGetParseError) { - RPCSendInterfaceMock::SendCallExpect expect; - expect._return = BufferSyncInterface::kParseUnknownCommand; - expect.message_id = BufferRPCImpl::GET_PARSE_ERROR; - expect.data = NULL; - expect.size = 0; - expect.handles = NULL; - expect.handle_count = 0; - server_mock()->AddSendCallExpect(expect); - - EXPECT_EQ(BufferSyncInterface::kParseUnknownCommand, - proxy()->GetParseError()); -} - -} // namespace command_buffer -} // namespace o3d diff --git a/o3d/command_buffer/client/cross/cmd_buffer_helper.cc b/o3d/command_buffer/client/cross/cmd_buffer_helper.cc index 10faddc..108f78e 100644 --- a/o3d/command_buffer/client/cross/cmd_buffer_helper.cc +++ b/o3d/command_buffer/client/cross/cmd_buffer_helper.cc @@ -33,72 +33,100 @@ // This file contains the implementation of the command buffer helper class. #include "command_buffer/client/cross/cmd_buffer_helper.h" +#include "o3d/gpu_plugin/np_utils/np_utils.h" namespace o3d { namespace command_buffer { -CommandBufferHelper::CommandBufferHelper(BufferSyncInterface *interface) - : interface_(interface), +using gpu_plugin::NPBrowser; +using gpu_plugin::NPInvoke; +using gpu_plugin::NPObjectPointer; + +CommandBufferHelper::CommandBufferHelper( + NPP npp, + const NPObjectPointer<NPObject>& command_buffer) + : npp_(npp), + command_buffer_(command_buffer), entries_(NULL), entry_count_(0), - token_(0) { - // The interface should be connected already. - DCHECK_NE(BufferSyncInterface::kNotConnected, interface_->GetStatus()); + token_(0), + last_token_read_(-1), + get_(0), + put_(0) { } -bool CommandBufferHelper::Init(unsigned int entry_count) { - if (entry_count == 0) +bool CommandBufferHelper::Initialize() { + // Get the ring buffer from the GPU process. + if (!NPInvoke(npp_, command_buffer_, "getRingBuffer", &ring_buffer_) || + !ring_buffer_.Get()) { + return false; + } + + // Map the ring buffer into this process. + size_t size_bytes; + entries_ = static_cast<CommandBufferEntry*>( + NPBrowser::get()->MapMemory(npp_, ring_buffer_.Get(), &size_bytes)); + + // Get the command buffer size. + if (!NPInvoke(npp_, command_buffer_, "getSize", &entry_count_)) { + return false; + } + + // Get the initial get offset. + if (!NPInvoke(npp_, command_buffer_, "getGetOffset", &get_)) { return false; - size_t size = entry_count * sizeof(CommandBufferEntry); // NOLINT - shm_handle_ = CreateShm(size); - if (shm_handle_ == kRPCInvalidHandle) + } + + // Get the initial put offset. + if (!NPInvoke(npp_, command_buffer_, "getPutOffset", &put_)) { return false; - void *address = MapShm(shm_handle_, size); - if (!address) { - DestroyShm(shm_handle_); - shm_handle_ = kRPCInvalidHandle; + } + + // Get the last token. + if (!NPInvoke(npp_, command_buffer_, "getToken", &last_token_read_)) { return false; } - entries_ = static_cast<CommandBufferEntry *>(address); - entry_count_ = entry_count; - shm_id_ = interface_->RegisterSharedMemory(shm_handle_, size); - interface_->SetCommandBuffer(shm_id_, 0, size, 0); - get_ = interface_->Get(); - put_ = get_; - last_token_read_ = interface_->GetToken(); + return true; } CommandBufferHelper::~CommandBufferHelper() { - if (entries_) { - interface_->UnregisterSharedMemory(shm_id_); - UnmapShm(entries_, entry_count_ * sizeof(CommandBufferEntry)); // NOLINT - DestroyShm(shm_handle_); - } +} + +bool CommandBufferHelper::Flush() { + // If this fails it means the command buffer reader has been shutdown. + return NPInvoke(npp_, command_buffer_, "syncOffsets", put_, &get_); } // Calls Flush() and then waits until the buffer is empty. Break early if the // error is set. -void CommandBufferHelper::Finish() { - Flush(); - while (put_ != get_) { - WaitForGetChange(); - } +bool CommandBufferHelper::Finish() { + do { + // Do not loop forever if the flush fails, meaning the command buffer reader + // has shutdown). + if (!Flush()) + return false; + } while (put_ != get_); + + return true; } // Inserts a new token into the command stream. It uses an increasing value // scheme so that we don't lose tokens (a token has passed if the current token // value is higher than that token). Calls Finish() if the token value wraps, // which will be rare. -unsigned int CommandBufferHelper::InsertToken() { - ++token_; +int32 CommandBufferHelper::InsertToken() { + // Increment token as 31-bit integer. Negative values are used to signal an + // error. + token_ = (token_ + 1) & 0x7FFFFFFF; CommandBufferEntry args; args.value_uint32 = token_; AddCommand(command_buffer::kSetToken, 1, &args); if (token_ == 0) { // we wrapped Finish(); - last_token_read_ = interface_->GetToken(); + if (!NPInvoke(npp_, command_buffer_, "getToken", &last_token_read_)) + return -1; DCHECK_EQ(token_, last_token_read_); } return token_; @@ -106,48 +134,27 @@ unsigned int CommandBufferHelper::InsertToken() { // Waits until the current token value is greater or equal to the value passed // in argument. -void CommandBufferHelper::WaitForToken(unsigned int token) { +void CommandBufferHelper::WaitForToken(int32 token) { + // Return immediately if corresponding InsertToken failed. + if (token < 0) + return; if (last_token_read_ >= token) return; // fast path. if (token > token_) return; // we wrapped Flush(); - last_token_read_ = interface_->GetToken(); + if (!NPInvoke(npp_, command_buffer_, "getToken", &last_token_read_)) + return; while (last_token_read_ < token) { if (get_ == put_) { LOG(FATAL) << "Empty command buffer while waiting on a token."; return; } - WaitForGetChange(); - last_token_read_ = interface_->GetToken(); - } -} - -// Waits for get to change. In case get doesn't change or becomes invalid, -// check for an error. -void CommandBufferHelper::WaitForGetChange() { - CommandBufferOffset new_get = interface_->WaitGetChanges(get_); - if (new_get == get_ || new_get == kInvalidCommandBufferOffset) { - // If get_ didn't change or is invalid, it means an error may have - // occured. Check that. - BufferSyncInterface::ParserStatus status = interface_->GetStatus(); - if (status != BufferSyncInterface::kParsing) { - switch (status) { - case BufferSyncInterface::kNotConnected: - LOG(FATAL) << "Service disconnected."; - return; - case BufferSyncInterface::kNoBuffer: - LOG(FATAL) << "Service doesn't have a buffer set."; - return; - case BufferSyncInterface::kParseError: { - BufferSyncInterface::ParseError error = interface_->GetParseError(); - LOG(WARNING) << "Parse error: " << error; - return; - } - case BufferSyncInterface::kParsing: - break; - } - } + // Do not loop forever if the flush fails, meaning the command buffer reader + // has shutdown. + if (!Flush()) + return; + if (!NPInvoke(npp_, command_buffer_, "getToken", &last_token_read_)) + return; } - get_ = new_get; } // Waits for available entries, basically waiting until get >= put + count + 1. @@ -155,17 +162,25 @@ void CommandBufferHelper::WaitForGetChange() { // around, adding noops. Thus this function may change the value of put_. // The function will return early if an error occurs, in which case the // available space may not be available. -void CommandBufferHelper::WaitForAvailableEntries(unsigned int count) { +void CommandBufferHelper::WaitForAvailableEntries(int32 count) { CHECK(count < entry_count_); if (put_ + count > entry_count_) { // There's not enough room between the current put and the end of the // buffer, so we need to wrap. We will add noops all the way to the end, // but we need to make sure get wraps first, actually that get is 1 or // more (since put will wrap to 0 after we add the noops). - DCHECK_LE(1U, put_); + DCHECK_LE(1, put_); Flush(); - while (get_ > put_ || get_ == 0) WaitForGetChange(); + while (get_ > put_ || get_ == 0) { + // Do not loop forever if the flush fails, meaning the command buffer + // reader has shutdown. + if (!Flush()) + return; + } // Add the noops. By convention, a noop is a command 0 with no args. + // TODO(apatrick): A noop can have a size. It would be better to add a + // single noop with a variable size. Watch out for size limit on + // individual commands. CommandHeader header; header.size = 1; header.command = 0; @@ -178,7 +193,12 @@ void CommandBufferHelper::WaitForAvailableEntries(unsigned int count) { if (count <= AvailableEntries()) return; // Otherwise flush, and wait until we do have enough room. Flush(); - while (AvailableEntries() < count) WaitForGetChange(); + while (AvailableEntries() < count) { + // Do not loop forever if the flush fails, meaning the command buffer reader + // has shutdown. + if (!Flush()) + return; + } } CommandBufferEntry* CommandBufferHelper::GetSpace(uint32 entries) { @@ -188,5 +208,11 @@ CommandBufferEntry* CommandBufferHelper::GetSpace(uint32 entries) { return space; } +parse_error::ParseError CommandBufferHelper::GetParseError() { + int32 parse_error; + DCHECK(NPInvoke(npp_, command_buffer_, "resetParseError", &parse_error)); + return static_cast<parse_error::ParseError>(parse_error); +} + } // namespace command_buffer } // namespace o3d diff --git a/o3d/command_buffer/client/cross/cmd_buffer_helper.h b/o3d/command_buffer/client/cross/cmd_buffer_helper.h index b00c8fc6..b42c5e0 100644 --- a/o3d/command_buffer/client/cross/cmd_buffer_helper.h +++ b/o3d/command_buffer/client/cross/cmd_buffer_helper.h @@ -36,8 +36,9 @@ #define O3D_COMMAND_BUFFER_CLIENT_CROSS_CMD_BUFFER_HELPER_H_ #include "command_buffer/common/cross/logging.h" -#include "command_buffer/common/cross/buffer_sync_api.h" +#include "command_buffer/common/cross/constants.h" #include "command_buffer/common/cross/cmd_buffer_format.h" +#include "o3d/gpu_plugin/np_utils/np_object_pointer.h" namespace o3d { namespace command_buffer { @@ -50,7 +51,7 @@ namespace command_buffer { // // helper.AddCommand(...); // helper.AddCommand(...); -// unsigned int token = helper.InsertToken(); +// int32 token = helper.InsertToken(); // helper.AddCommand(...); // helper.AddCommand(...); // [...] @@ -59,43 +60,38 @@ namespace command_buffer { // // commands have been executed. class CommandBufferHelper { public: - // Constructs a CommandBufferHelper object. The helper needs to be - // initialized by calling Init() before use. - // Parameters: - // interface: the buffer interface the helper sends commands to. - explicit CommandBufferHelper(BufferSyncInterface *interface); + explicit CommandBufferHelper( + NPP npp, + const gpu_plugin::NPObjectPointer<NPObject>& command_buffer); ~CommandBufferHelper(); - // Initializes the command buffer by allocating shared memory. - // Parameters: - // entry_count: the number of entries in the buffer. Note that commands - // sent through the buffer must use at most entry_count-2 arguments - // (entry_count-1 size). - // Returns: - // true if successful. - bool Init(unsigned int entry_count); + bool Initialize(); // Flushes the commands, setting the put pointer to let the buffer interface - // know that new commands have been added. - void Flush() { - interface_->Put(put_); - } - - // Waits until all the commands have been executed. - void Finish(); + // know that new commands have been added. After a flush returns, the command + // buffer service is aware of all pending commands and it is guaranteed to + // have made some progress in processing them. Returns whether the flush was + // successful. The flush will fail if the command buffer service has + // disconnected. + bool Flush(); + + // Waits until all the commands have been executed. Returns whether it + // was successful. The function will fail if the command buffer service has + // disconnected. + bool Finish(); // Waits until a given number of available entries are available. // Parameters: // count: number of entries needed. This value must be at most // the size of the buffer minus one. - void WaitForAvailableEntries(unsigned int count); + void WaitForAvailableEntries(int32 count); // Adds a command data to the command buffer. This may wait until sufficient // space is available. // Parameters: // entries: The command entries to add. // count: The number of entries. - void AddCommandData(const CommandBufferEntry* entries, unsigned int count) { + void AddCommandData(const CommandBufferEntry* entries, int32 count) { WaitForAvailableEntries(count); for (; count > 0; --count) { entries_[put_++] = *entries++; @@ -118,15 +114,15 @@ class CommandBufferHelper { // arg_count: the number of arguments for the command. // args: the arguments for the command (these are copied before the // function returns). - void AddCommand(unsigned int command, - unsigned int arg_count, + void AddCommand(int32 command, + int32 arg_count, const CommandBufferEntry *args) { CommandHeader header; header.size = arg_count + 1; header.command = command; WaitForAvailableEntries(header.size); entries_[put_++].value_header = header; - for (unsigned int i = 0; i < arg_count; ++i) { + for (int i = 0; i < arg_count; ++i) { entries_[put_++] = args[i]; } DCHECK_LE(put_, entry_count_); @@ -138,18 +134,16 @@ class CommandBufferHelper { // inserted tokens with that value have already passed through the command // stream. // Returns: - // the value of the new token. - unsigned int InsertToken(); + // the value of the new token or -1 if the command buffer reader has + // shutdown. + int32 InsertToken(); // Waits until the token of a particular value has passed through the command // stream (i.e. commands inserted before that token have been executed). // NOTE: This will call Flush if it needs to block. // Parameters: // the value of the token to wait for. - void WaitForToken(unsigned int token); - - // Returns the buffer interface used to send synchronous commands. - BufferSyncInterface *interface() { return interface_; } + void WaitForToken(int32 token); // Waits for a certain amount of space to be available. Returns address // of space. @@ -174,6 +168,8 @@ class CommandBufferHelper { return *reinterpret_cast<T*>(data); } + parse_error::ParseError GetParseError(); + // ------------------ Individual commands ---------------------- void Noop(uint32 skip_count) { @@ -765,20 +761,19 @@ class CommandBufferHelper { void WaitForGetChange(); // Returns the number of available entries (they may not be contiguous). - unsigned int AvailableEntries() { - return static_cast<unsigned int>( - (get_ - put_ - 1 + entry_count_) % entry_count_); + int32 AvailableEntries() { + return (get_ - put_ - 1 + entry_count_) % entry_count_; } - BufferSyncInterface *interface_; + NPP npp_; + gpu_plugin::NPObjectPointer<NPObject> command_buffer_; + gpu_plugin::NPObjectPointer<NPObject> ring_buffer_; CommandBufferEntry *entries_; - unsigned int entry_count_; - unsigned int token_; - unsigned int last_token_read_; - RPCShmHandle shm_handle_; - unsigned int shm_id_; - CommandBufferOffset get_; - CommandBufferOffset put_; + int32 entry_count_; + int32 token_; + int32 last_token_read_; + int32 get_; + int32 put_; friend class CommandBufferHelperTest; }; diff --git a/o3d/command_buffer/client/cross/cmd_buffer_helper_test.cc b/o3d/command_buffer/client/cross/cmd_buffer_helper_test.cc index d72d920..95d31d5 100644 --- a/o3d/command_buffer/client/cross/cmd_buffer_helper_test.cc +++ b/o3d/command_buffer/client/cross/cmd_buffer_helper_test.cc @@ -33,13 +33,22 @@ // Tests for the Command Buffer Helper. #include "tests/common/win/testing_common.h" +#include "base/message_loop.h" #include "command_buffer/client/cross/cmd_buffer_helper.h" -#include "command_buffer/service/cross/cmd_buffer_engine.h" #include "command_buffer/service/cross/mocks.h" +#include "gpu_plugin/command_buffer.h" +#include "gpu_plugin/gpu_processor.h" +#include "gpu_plugin/np_utils/np_object_pointer.h" +#include "gpu_plugin/system_services/shared_memory.h" namespace o3d { namespace command_buffer { +using gpu_plugin::CommandBuffer; +using gpu_plugin::GPUProcessor; +using gpu_plugin::NPCreateObject; +using gpu_plugin::NPObjectPointer; +using gpu_plugin::SharedMemory; using testing::Return; using testing::Mock; using testing::Truly; @@ -48,6 +57,9 @@ using testing::DoAll; using testing::Invoke; using testing::_; +const int32 kNumCommandEntries = 10; +const int32 kCommandBufferSizeBytes = kNumCommandEntries * sizeof(int32); + // Test fixture for CommandBufferHelper test - Creates a CommandBufferHelper, // using a CommandBufferEngine with a mock AsyncAPIInterface for its interface // (calling it directly, not through the RPC mechanism). @@ -58,28 +70,50 @@ class CommandBufferHelperTest : public testing::Test { // ignore noops in the mock - we don't want to inspect the internals of the // helper. EXPECT_CALL(*api_mock_, DoCommand(0, 0, _)) - .WillRepeatedly(Return(BufferSyncInterface::kParseNoError)); - engine_.reset(new CommandBufferEngine(api_mock_.get())); - api_mock_->set_engine(engine_.get()); + .WillRepeatedly(Return(parse_error::kParseNoError)); + + NPObjectPointer<SharedMemory> ring_buffer = + NPCreateObject<SharedMemory>(NULL); + ring_buffer->Initialize(kCommandBufferSizeBytes); + + size_t size_bytes; + void* buffer = NPN_MapMemory(NULL, ring_buffer.Get(), &size_bytes); + + command_buffer_ = NPCreateObject<CommandBuffer>(NULL); + command_buffer_->Initialize(ring_buffer); + + parser_ = new command_buffer::CommandParser(buffer, + kCommandBufferSizeBytes, + 0, + kCommandBufferSizeBytes, + 0, + api_mock_.get()); - engine_->InitConnection(); - helper_.reset(new CommandBufferHelper(engine_.get())); - helper_->Init(10); + scoped_refptr<GPUProcessor> gpu_processor(new GPUProcessor( + NULL, command_buffer_.Get(), NULL, NULL, parser_, 1)); + command_buffer_->SetPutOffsetChangeCallback(NewCallback( + gpu_processor.get(), &GPUProcessor::ProcessCommands)); + + api_mock_->set_engine(gpu_processor.get()); + + helper_.reset(new CommandBufferHelper(NULL, command_buffer_)); + helper_->Initialize(); } virtual void TearDown() { + // If the GPUProcessor posts any tasks, this forces them to run. + MessageLoop::current()->RunAllPending(); helper_.release(); - engine_->CloseConnection(); } // Adds a command to the buffer through the helper, while adding it as an // expected call on the API mock. - void AddCommandWithExpect(BufferSyncInterface::ParseError _return, + void AddCommandWithExpect(parse_error::ParseError _return, unsigned int command, unsigned int arg_count, CommandBufferEntry *args) { helper_->AddCommand(command, arg_count, args); - EXPECT_CALL(*api_mock(), DoCommand(command, arg_count, + EXPECT_CALL(*api_mock_, DoCommand(command, arg_count, Truly(AsyncAPIMock::IsArgs(arg_count, args)))) .InSequence(sequence_) .WillOnce(Return(_return)); @@ -87,8 +121,8 @@ class CommandBufferHelperTest : public testing::Test { // Checks that the buffer from put to put+size is free in the parser. void CheckFreeSpace(CommandBufferOffset put, unsigned int size) { - CommandBufferOffset parser_put = engine()->parser()->put(); - CommandBufferOffset parser_get = engine()->parser()->get(); + CommandBufferOffset parser_put = parser_->put(); + CommandBufferOffset parser_get = parser_->get(); CommandBufferOffset limit = put + size; if (parser_get > parser_put) { // "busy" buffer wraps, so "free" buffer is between put (inclusive) and @@ -100,7 +134,7 @@ class CommandBufferHelperTest : public testing::Test { // put to the limit) and the bottom side (from 0 to get). if (put >= parser_put) { // we're on the top side, check we are below the limit. - EXPECT_GE(10U, limit); + EXPECT_GE(kNumCommandEntries, limit); } else { // we're on the bottom side, check we are below get. EXPECT_GT(parser_get, limit); @@ -108,13 +142,11 @@ class CommandBufferHelperTest : public testing::Test { } } - CommandBufferHelper *helper() { return helper_.get(); } - CommandBufferEngine *engine() { return engine_.get(); } - AsyncAPIMock *api_mock() { return api_mock_.get(); } CommandBufferOffset get_helper_put() { return helper_->put_; } - private: + scoped_ptr<AsyncAPIMock> api_mock_; - scoped_ptr<CommandBufferEngine> engine_; + NPObjectPointer<CommandBuffer> command_buffer_; + command_buffer::CommandParser* parser_; scoped_ptr<CommandBufferHelper> helper_; Sequence sequence_; }; @@ -124,40 +156,39 @@ class CommandBufferHelperTest : public testing::Test { TEST_F(CommandBufferHelperTest, TestCommandProcessing) { // Check initial state of the engine - it should have been configured by the // helper. - EXPECT_TRUE(engine()->rpc_impl() != NULL); - EXPECT_TRUE(engine()->parser() != NULL); - EXPECT_EQ(BufferSyncInterface::kParsing, engine()->GetStatus()); - EXPECT_EQ(BufferSyncInterface::kParseNoError, engine()->GetParseError()); - EXPECT_EQ(0u, engine()->Get()); + EXPECT_TRUE(parser_ != NULL); + EXPECT_FALSE(command_buffer_->GetErrorStatus()); + EXPECT_EQ(parse_error::kParseNoError, command_buffer_->ResetParseError()); + EXPECT_EQ(0u, command_buffer_->GetGetOffset()); // Add 3 commands through the helper - AddCommandWithExpect(BufferSyncInterface::kParseNoError, 1, 0, NULL); + AddCommandWithExpect(parse_error::kParseNoError, 1, 0, NULL); CommandBufferEntry args1[2]; args1[0].value_uint32 = 3; args1[1].value_float = 4.f; - AddCommandWithExpect(BufferSyncInterface::kParseNoError, 2, 2, args1); + AddCommandWithExpect(parse_error::kParseNoError, 2, 2, args1); CommandBufferEntry args2[2]; args2[0].value_uint32 = 5; args2[1].value_float = 6.f; - AddCommandWithExpect(BufferSyncInterface::kParseNoError, 3, 2, args2); + AddCommandWithExpect(parse_error::kParseNoError, 3, 2, args2); - helper()->Flush(); + helper_->Flush(); // Check that the engine has work to do now. - EXPECT_FALSE(engine()->parser()->IsEmpty()); + EXPECT_FALSE(parser_->IsEmpty()); // Wait until it's done. - helper()->Finish(); + helper_->Finish(); // Check that the engine has no more work to do. - EXPECT_TRUE(engine()->parser()->IsEmpty()); + EXPECT_TRUE(parser_->IsEmpty()); // Check that the commands did happen. - Mock::VerifyAndClearExpectations(api_mock()); + Mock::VerifyAndClearExpectations(api_mock_.get()); // Check the error status. - ASSERT_EQ(BufferSyncInterface::kParsing, engine()->GetStatus()); - EXPECT_EQ(BufferSyncInterface::kParseNoError, engine()->GetParseError()); + EXPECT_FALSE(command_buffer_->GetErrorStatus()); + EXPECT_EQ(parse_error::kParseNoError, command_buffer_->ResetParseError()); } // Checks that commands in the buffer are properly executed when wrapping the @@ -169,16 +200,16 @@ TEST_F(CommandBufferHelperTest, TestCommandWrapping) { args1[1].value_float = 4.f; for (unsigned int i = 0; i < 5; ++i) { - AddCommandWithExpect(BufferSyncInterface::kParseNoError, i+1, 2, args1); + AddCommandWithExpect(parse_error::kParseNoError, i + 1, 2, args1); } - helper()->Finish(); + helper_->Finish(); // Check that the commands did happen. - Mock::VerifyAndClearExpectations(api_mock()); + Mock::VerifyAndClearExpectations(api_mock_.get()); // Check the error status. - ASSERT_EQ(BufferSyncInterface::kParsing, engine()->GetStatus()); - EXPECT_EQ(BufferSyncInterface::kParseNoError, engine()->GetParseError()); + EXPECT_FALSE(command_buffer_->GetErrorStatus()); + EXPECT_EQ(parse_error::kParseNoError, command_buffer_->ResetParseError()); } @@ -191,22 +222,20 @@ TEST_F(CommandBufferHelperTest, TestRecoverableError) { args[1].value_float = 4.f; // Create a command buffer with 3 commands, 2 of them generating errors - AddCommandWithExpect(BufferSyncInterface::kParseNoError, 1, 2, args); - AddCommandWithExpect(BufferSyncInterface::kParseUnknownCommand, 2, 2, args); - AddCommandWithExpect(BufferSyncInterface::kParseInvalidArguments, 3, 2, + AddCommandWithExpect(parse_error::kParseNoError, 1, 2, args); + AddCommandWithExpect(parse_error::kParseUnknownCommand, 2, 2, args); + AddCommandWithExpect(parse_error::kParseInvalidArguments, 3, 2, args); - helper()->Finish(); + helper_->Finish(); // Check that the commands did happen. - Mock::VerifyAndClearExpectations(api_mock()); + Mock::VerifyAndClearExpectations(api_mock_.get()); // Check that the error status was set to the first error. - EXPECT_EQ(BufferSyncInterface::kParseUnknownCommand, - engine()->GetParseError()); + EXPECT_EQ(parse_error::kParseUnknownCommand, + command_buffer_->ResetParseError()); // Check that the error status was reset after the query. - EXPECT_EQ(BufferSyncInterface::kParseNoError, engine()->GetParseError()); - - engine()->CloseConnection(); + EXPECT_EQ(parse_error::kParseNoError, command_buffer_->ResetParseError()); } // Checks that asking for available entries work, and that the parser @@ -217,29 +246,29 @@ TEST_F(CommandBufferHelperTest, TestAvailableEntries) { args[1].value_float = 4.f; // Add 2 commands through the helper - 8 entries - AddCommandWithExpect(BufferSyncInterface::kParseNoError, 1, 0, NULL); - AddCommandWithExpect(BufferSyncInterface::kParseNoError, 2, 0, NULL); - AddCommandWithExpect(BufferSyncInterface::kParseNoError, 3, 2, args); - AddCommandWithExpect(BufferSyncInterface::kParseNoError, 4, 2, args); + AddCommandWithExpect(parse_error::kParseNoError, 1, 0, NULL); + AddCommandWithExpect(parse_error::kParseNoError, 2, 0, NULL); + AddCommandWithExpect(parse_error::kParseNoError, 3, 2, args); + AddCommandWithExpect(parse_error::kParseNoError, 4, 2, args); // Ask for 5 entries. - helper()->WaitForAvailableEntries(5); + helper_->WaitForAvailableEntries(5); CommandBufferOffset put = get_helper_put(); CheckFreeSpace(put, 5); // Add more commands. - AddCommandWithExpect(BufferSyncInterface::kParseNoError, 5, 2, args); + AddCommandWithExpect(parse_error::kParseNoError, 5, 2, args); // Wait until everything is done done. - helper()->Finish(); + helper_->Finish(); // Check that the commands did happen. - Mock::VerifyAndClearExpectations(api_mock()); + Mock::VerifyAndClearExpectations(api_mock_.get()); // Check the error status. - ASSERT_EQ(BufferSyncInterface::kParsing, engine()->GetStatus()); - EXPECT_EQ(BufferSyncInterface::kParseNoError, engine()->GetParseError()); + EXPECT_FALSE(command_buffer_->GetErrorStatus()); + EXPECT_EQ(parse_error::kParseNoError, command_buffer_->ResetParseError()); } // Checks that the InsertToken/WaitForToken work. @@ -249,27 +278,27 @@ TEST_F(CommandBufferHelperTest, TestToken) { args[1].value_float = 4.f; // Add a first command. - AddCommandWithExpect(BufferSyncInterface::kParseNoError, 3, 2, args); + AddCommandWithExpect(parse_error::kParseNoError, 3, 2, args); // keep track of the buffer position. CommandBufferOffset command1_put = get_helper_put(); - unsigned int token = helper()->InsertToken(); + int32 token = helper_->InsertToken(); - EXPECT_CALL(*api_mock(), DoCommand(kSetToken, 1, _)) - .WillOnce(DoAll(Invoke(api_mock(), &AsyncAPIMock::SetToken), - Return(BufferSyncInterface::kParseNoError))); + EXPECT_CALL(*api_mock_.get(), DoCommand(kSetToken, 1, _)) + .WillOnce(DoAll(Invoke(api_mock_.get(), &AsyncAPIMock::SetToken), + Return(parse_error::kParseNoError))); // Add another command. - AddCommandWithExpect(BufferSyncInterface::kParseNoError, 4, 2, args); - helper()->WaitForToken(token); + AddCommandWithExpect(parse_error::kParseNoError, 4, 2, args); + helper_->WaitForToken(token); // check that the get pointer is beyond the first command. - EXPECT_LE(command1_put, engine()->Get()); - helper()->Finish(); + EXPECT_LE(command1_put, command_buffer_->GetGetOffset()); + helper_->Finish(); // Check that the commands did happen. - Mock::VerifyAndClearExpectations(api_mock()); + Mock::VerifyAndClearExpectations(api_mock_.get()); // Check the error status. - ASSERT_EQ(BufferSyncInterface::kParsing, engine()->GetStatus()); - EXPECT_EQ(BufferSyncInterface::kParseNoError, engine()->GetParseError()); + EXPECT_FALSE(command_buffer_->GetErrorStatus()); + EXPECT_EQ(parse_error::kParseNoError, command_buffer_->ResetParseError()); } } // namespace command_buffer diff --git a/o3d/command_buffer/client/cross/effect_helper.cc b/o3d/command_buffer/client/cross/effect_helper.cc index 3f2430b..2523892 100644 --- a/o3d/command_buffer/client/cross/effect_helper.cc +++ b/o3d/command_buffer/client/cross/effect_helper.cc @@ -58,8 +58,7 @@ bool EffectHelper::CreateEffectParameters(ResourceId effect_id, helper_->Finish(); // We could have failed if the effect_id is invalid. - if (helper_->interface()->GetParseError() != - BufferSyncInterface::kParseNoError) { + if (helper_->GetParseError() != parse_error::kParseNoError) { shm_allocator_->Free(retval); return false; } @@ -96,8 +95,7 @@ bool EffectHelper::CreateEffectParameters(ResourceId effect_id, } // Finish to get the results. helper_->Finish(); - DCHECK_EQ(helper_->interface()->GetParseError(), - BufferSyncInterface::kParseNoError); + DCHECK_EQ(helper_->GetParseError(), parse_error::kParseNoError); for (unsigned int j = 0 ; j < count; ++j) { EffectParamDesc *desc = &((*descs)[i + j]); Desc *raw_desc = raw_descs + j; @@ -132,8 +130,7 @@ bool EffectHelper::GetParamStrings(EffectParamDesc *desc) { helper_->Finish(); // We could have failed if the param ID is invalid. - if (helper_->interface()->GetParseError() != - BufferSyncInterface::kParseNoError) { + if (helper_->GetParseError() != parse_error::kParseNoError) { shm_allocator_->Free(raw_desc); return false; } @@ -156,8 +153,7 @@ bool EffectHelper::GetParamStrings(EffectParamDesc *desc) { shm_allocator_->GetOffset(raw_desc)); // Finish to get the results. helper_->Finish(); - DCHECK_EQ(helper_->interface()->GetParseError(), - BufferSyncInterface::kParseNoError); + DCHECK_EQ(helper_->GetParseError(), parse_error::kParseNoError); DCHECK_EQ(raw_desc->size, size); } @@ -211,8 +207,7 @@ bool EffectHelper::GetEffectStreams(ResourceId effect_id, helper_->Finish(); // We could have failed if the effect_id is invalid. - if (helper_->interface()->GetParseError() != - BufferSyncInterface::kParseNoError) { + if (helper_->GetParseError() != parse_error::kParseNoError) { shm_allocator_->Free(retval); return false; } @@ -242,8 +237,7 @@ bool EffectHelper::GetEffectStreams(ResourceId effect_id, } // Finish to get the results. helper_->Finish(); - DCHECK_EQ(helper_->interface()->GetParseError(), - BufferSyncInterface::kParseNoError); + DCHECK_EQ(helper_->GetParseError(), parse_error::kParseNoError); for (unsigned int j = 0 ; j < count; ++j) { EffectStreamDesc *desc = &((*descs)[i + j]); Desc *raw_desc = raw_descs + j; diff --git a/o3d/command_buffer/client/cross/fenced_allocator_test.cc b/o3d/command_buffer/client/cross/fenced_allocator_test.cc index 362254a..8c6ef1e 100644 --- a/o3d/command_buffer/client/cross/fenced_allocator_test.cc +++ b/o3d/command_buffer/client/cross/fenced_allocator_test.cc @@ -33,13 +33,24 @@ // This file contains the tests for the FencedAllocator class. #include "tests/common/win/testing_common.h" +#include "base/message_loop.h" #include "command_buffer/client/cross/cmd_buffer_helper.h" #include "command_buffer/client/cross/fenced_allocator.h" #include "command_buffer/service/cross/cmd_buffer_engine.h" #include "command_buffer/service/cross/mocks.h" +#include "gpu_plugin/command_buffer.h" +#include "gpu_plugin/gpu_processor.h" +#include "gpu_plugin/np_utils/np_object_pointer.h" +#include "gpu_plugin/system_services/shared_memory.h" namespace o3d { namespace command_buffer { + +using gpu_plugin::CommandBuffer; +using gpu_plugin::GPUProcessor; +using gpu_plugin::NPCreateObject; +using gpu_plugin::NPObjectPointer; +using gpu_plugin::SharedMemory; using testing::Return; using testing::Mock; using testing::Truly; @@ -48,78 +59,104 @@ using testing::DoAll; using testing::Invoke; using testing::_; -// Test fixture for FencedAllocator test - Creates a FencedAllocator, using a -// CommandBufferHelper with a mock AsyncAPIInterface for its interface (calling -// it directly, not through the RPC mechanism), making sure Noops are ignored -// and SetToken are properly forwarded to the engine. -class FencedAllocatorTest : public testing::Test { - public: +class BaseFencedAllocatorTest : public testing::Test { + protected: static const unsigned int kBufferSize = 1024; - protected: virtual void SetUp() { api_mock_.reset(new AsyncAPIMock); // ignore noops in the mock - we don't want to inspect the internals of the // helper. EXPECT_CALL(*api_mock_, DoCommand(kNoop, 0, _)) - .WillRepeatedly(Return(BufferSyncInterface::kParseNoError)); + .WillRepeatedly(Return(parse_error::kParseNoError)); // Forward the SetToken calls to the engine - EXPECT_CALL(*api_mock(), DoCommand(kSetToken, 1, _)) - .WillRepeatedly(DoAll(Invoke(api_mock(), &AsyncAPIMock::SetToken), - Return(BufferSyncInterface::kParseNoError))); - engine_.reset(new CommandBufferEngine(api_mock_.get())); - api_mock_->set_engine(engine_.get()); - - nacl::SocketAddress client_address = { "test-socket" }; - client_socket_ = nacl::BoundSocket(&client_address); - engine_->InitConnection(); - helper_.reset(new CommandBufferHelper(engine_.get())); - helper_->Init(100); + EXPECT_CALL(*api_mock_.get(), DoCommand(kSetToken, 1, _)) + .WillRepeatedly(DoAll(Invoke(api_mock_.get(), &AsyncAPIMock::SetToken), + Return(parse_error::kParseNoError))); - allocator_.reset(new FencedAllocator(kBufferSize, helper_.get())); + NPObjectPointer<SharedMemory> ring_buffer = + NPCreateObject<SharedMemory>(NULL); + ring_buffer->Initialize(1024); + + size_t size_bytes; + void* buffer = NPN_MapMemory(NULL, ring_buffer.Get(), &size_bytes); + + command_buffer_ = NPCreateObject<CommandBuffer>(NULL); + command_buffer_->Initialize(ring_buffer); + + parser_ = new command_buffer::CommandParser(buffer, + kBufferSize, + 0, + kBufferSize, + 0, + api_mock_.get()); + + scoped_refptr<GPUProcessor> gpu_processor(new GPUProcessor( + NULL, command_buffer_.Get(), NULL, NULL, parser_, INT_MAX)); + command_buffer_->SetPutOffsetChangeCallback(NewCallback( + gpu_processor.get(), &GPUProcessor::ProcessCommands)); + + api_mock_->set_engine(gpu_processor.get()); + + helper_.reset(new CommandBufferHelper(NULL, command_buffer_)); + helper_->Initialize(); } virtual void TearDown() { - EXPECT_TRUE(allocator_->CheckConsistency()); - allocator_.release(); helper_.release(); - engine_->CloseConnection(); - nacl::Close(client_socket_); } - CommandBufferHelper *helper() { return helper_.get(); } - CommandBufferEngine *engine() { return engine_.get(); } - AsyncAPIMock *api_mock() { return api_mock_.get(); } - FencedAllocator *allocator() { return allocator_.get(); } - private: scoped_ptr<AsyncAPIMock> api_mock_; - scoped_ptr<CommandBufferEngine> engine_; + NPObjectPointer<CommandBuffer> command_buffer_; + command_buffer::CommandParser* parser_; scoped_ptr<CommandBufferHelper> helper_; - scoped_ptr<FencedAllocator> allocator_; - nacl::Handle client_socket_; }; #ifndef COMPILER_MSVC -const unsigned int FencedAllocatorTest::kBufferSize; +const unsigned int BaseFencedAllocatorTest::kBufferSize; #endif +// Test fixture for FencedAllocator test - Creates a FencedAllocator, using a +// CommandBufferHelper with a mock AsyncAPIInterface for its interface (calling +// it directly, not through the RPC mechanism), making sure Noops are ignored +// and SetToken are properly forwarded to the engine. +class FencedAllocatorTest : public BaseFencedAllocatorTest { + protected: + virtual void SetUp() { + BaseFencedAllocatorTest::SetUp(); + allocator_.reset(new FencedAllocator(kBufferSize, helper_.get())); + } + + virtual void TearDown() { + // If the GPUProcessor posts any tasks, this forces them to run. + MessageLoop::current()->RunAllPending(); + + EXPECT_TRUE(allocator_->CheckConsistency()); + allocator_.release(); + + BaseFencedAllocatorTest::TearDown(); + } + + scoped_ptr<FencedAllocator> allocator_; +}; + // Checks basic alloc and free. TEST_F(FencedAllocatorTest, TestBasic) { - allocator()->CheckConsistency(); + allocator_->CheckConsistency(); const unsigned int kSize = 16; - FencedAllocator::Offset offset = allocator()->Alloc(kSize); + FencedAllocator::Offset offset = allocator_->Alloc(kSize); EXPECT_NE(FencedAllocator::kInvalidOffset, offset); EXPECT_GE(kBufferSize, offset+kSize); - EXPECT_TRUE(allocator()->CheckConsistency()); + EXPECT_TRUE(allocator_->CheckConsistency()); - allocator()->Free(offset); - EXPECT_TRUE(allocator()->CheckConsistency()); + allocator_->Free(offset); + EXPECT_TRUE(allocator_->CheckConsistency()); } // Checks out-of-memory condition. TEST_F(FencedAllocatorTest, TestOutOfMemory) { - EXPECT_TRUE(allocator()->CheckConsistency()); + EXPECT_TRUE(allocator_->CheckConsistency()); const unsigned int kSize = 16; const unsigned int kAllocCount = kBufferSize / kSize; @@ -128,40 +165,40 @@ TEST_F(FencedAllocatorTest, TestOutOfMemory) { // Allocate several buffers to fill in the memory. FencedAllocator::Offset offsets[kAllocCount]; for (unsigned int i = 0; i < kAllocCount; ++i) { - offsets[i] = allocator()->Alloc(kSize); + offsets[i] = allocator_->Alloc(kSize); EXPECT_NE(FencedAllocator::kInvalidOffset, offsets[i]); EXPECT_GE(kBufferSize, offsets[i]+kSize); - EXPECT_TRUE(allocator()->CheckConsistency()); + EXPECT_TRUE(allocator_->CheckConsistency()); } // This allocation should fail. - FencedAllocator::Offset offset_failed = allocator()->Alloc(kSize); + FencedAllocator::Offset offset_failed = allocator_->Alloc(kSize); EXPECT_EQ(FencedAllocator::kInvalidOffset, offset_failed); - EXPECT_TRUE(allocator()->CheckConsistency()); + EXPECT_TRUE(allocator_->CheckConsistency()); // Free one successful allocation, reallocate with half the size - allocator()->Free(offsets[0]); - EXPECT_TRUE(allocator()->CheckConsistency()); - offsets[0] = allocator()->Alloc(kSize/2); + allocator_->Free(offsets[0]); + EXPECT_TRUE(allocator_->CheckConsistency()); + offsets[0] = allocator_->Alloc(kSize/2); EXPECT_NE(FencedAllocator::kInvalidOffset, offsets[0]); EXPECT_GE(kBufferSize, offsets[0]+kSize); - EXPECT_TRUE(allocator()->CheckConsistency()); + EXPECT_TRUE(allocator_->CheckConsistency()); // This allocation should fail as well. - offset_failed = allocator()->Alloc(kSize); + offset_failed = allocator_->Alloc(kSize); EXPECT_EQ(FencedAllocator::kInvalidOffset, offset_failed); - EXPECT_TRUE(allocator()->CheckConsistency()); + EXPECT_TRUE(allocator_->CheckConsistency()); // Free up everything. for (unsigned int i = 0; i < kAllocCount; ++i) { - allocator()->Free(offsets[i]); - EXPECT_TRUE(allocator()->CheckConsistency()); + allocator_->Free(offsets[i]); + EXPECT_TRUE(allocator_->CheckConsistency()); } } // Checks the free-pending-token mechanism. TEST_F(FencedAllocatorTest, TestFreePendingToken) { - EXPECT_TRUE(allocator()->CheckConsistency()); + EXPECT_TRUE(allocator_->CheckConsistency()); const unsigned int kSize = 16; const unsigned int kAllocCount = kBufferSize / kSize; @@ -170,143 +207,143 @@ TEST_F(FencedAllocatorTest, TestFreePendingToken) { // Allocate several buffers to fill in the memory. FencedAllocator::Offset offsets[kAllocCount]; for (unsigned int i = 0; i < kAllocCount; ++i) { - offsets[i] = allocator()->Alloc(kSize); + offsets[i] = allocator_->Alloc(kSize); EXPECT_NE(FencedAllocator::kInvalidOffset, offsets[i]); EXPECT_GE(kBufferSize, offsets[i]+kSize); - EXPECT_TRUE(allocator()->CheckConsistency()); + EXPECT_TRUE(allocator_->CheckConsistency()); } // This allocation should fail. - FencedAllocator::Offset offset_failed = allocator()->Alloc(kSize); + FencedAllocator::Offset offset_failed = allocator_->Alloc(kSize); EXPECT_EQ(FencedAllocator::kInvalidOffset, offset_failed); - EXPECT_TRUE(allocator()->CheckConsistency()); + EXPECT_TRUE(allocator_->CheckConsistency()); // Free one successful allocation, pending fence. - unsigned int token = helper()->InsertToken(); - allocator()->FreePendingToken(offsets[0], token); - EXPECT_TRUE(allocator()->CheckConsistency()); + int32 token = helper_.get()->InsertToken(); + allocator_->FreePendingToken(offsets[0], token); + EXPECT_TRUE(allocator_->CheckConsistency()); // The way we hooked up the helper and engine, it won't process commands // until it has to wait for something. Which means the token shouldn't have // passed yet at this point. - EXPECT_GT(token, engine()->GetToken()); + EXPECT_GT(token, command_buffer_->GetToken()); // This allocation will need to reclaim the space freed above, so that should // process the commands until the token is passed. - offsets[0] = allocator()->Alloc(kSize); + offsets[0] = allocator_->Alloc(kSize); EXPECT_NE(FencedAllocator::kInvalidOffset, offsets[0]); EXPECT_GE(kBufferSize, offsets[0]+kSize); - EXPECT_TRUE(allocator()->CheckConsistency()); + EXPECT_TRUE(allocator_->CheckConsistency()); // Check that the token has indeed passed. - EXPECT_LE(token, engine()->GetToken()); + EXPECT_LE(token, command_buffer_->GetToken()); // Free up everything. for (unsigned int i = 0; i < kAllocCount; ++i) { - allocator()->Free(offsets[i]); - EXPECT_TRUE(allocator()->CheckConsistency()); + allocator_->Free(offsets[i]); + EXPECT_TRUE(allocator_->CheckConsistency()); } } // Tests GetLargestFreeSize TEST_F(FencedAllocatorTest, TestGetLargestFreeSize) { - EXPECT_TRUE(allocator()->CheckConsistency()); - EXPECT_EQ(kBufferSize, allocator()->GetLargestFreeSize()); + EXPECT_TRUE(allocator_->CheckConsistency()); + EXPECT_EQ(kBufferSize, allocator_->GetLargestFreeSize()); - FencedAllocator::Offset offset = allocator()->Alloc(kBufferSize); + FencedAllocator::Offset offset = allocator_->Alloc(kBufferSize); ASSERT_NE(FencedAllocator::kInvalidOffset, offset); - EXPECT_EQ(0u, allocator()->GetLargestFreeSize()); - allocator()->Free(offset); - EXPECT_EQ(kBufferSize, allocator()->GetLargestFreeSize()); + EXPECT_EQ(0u, allocator_->GetLargestFreeSize()); + allocator_->Free(offset); + EXPECT_EQ(kBufferSize, allocator_->GetLargestFreeSize()); const unsigned int kSize = 16; - offset = allocator()->Alloc(kSize); + offset = allocator_->Alloc(kSize); ASSERT_NE(FencedAllocator::kInvalidOffset, offset); // The following checks that the buffer is allocated "smartly" - which is // dependent on the implementation. But both first-fit or best-fit would // ensure that. - EXPECT_EQ(kBufferSize - kSize, allocator()->GetLargestFreeSize()); + EXPECT_EQ(kBufferSize - kSize, allocator_->GetLargestFreeSize()); // Allocate 2 more buffers (now 3), and then free the first two. This is to // ensure a hole. Note that this is dependent on the first-fit current // implementation. - FencedAllocator::Offset offset1 = allocator()->Alloc(kSize); + FencedAllocator::Offset offset1 = allocator_->Alloc(kSize); ASSERT_NE(FencedAllocator::kInvalidOffset, offset1); - FencedAllocator::Offset offset2 = allocator()->Alloc(kSize); + FencedAllocator::Offset offset2 = allocator_->Alloc(kSize); ASSERT_NE(FencedAllocator::kInvalidOffset, offset2); - allocator()->Free(offset); - allocator()->Free(offset1); - EXPECT_EQ(kBufferSize - 3 * kSize, allocator()->GetLargestFreeSize()); + allocator_->Free(offset); + allocator_->Free(offset1); + EXPECT_EQ(kBufferSize - 3 * kSize, allocator_->GetLargestFreeSize()); - offset = allocator()->Alloc(kBufferSize - 3 * kSize); + offset = allocator_->Alloc(kBufferSize - 3 * kSize); ASSERT_NE(FencedAllocator::kInvalidOffset, offset); - EXPECT_EQ(2 * kSize, allocator()->GetLargestFreeSize()); + EXPECT_EQ(2 * kSize, allocator_->GetLargestFreeSize()); - offset1 = allocator()->Alloc(2 * kSize); + offset1 = allocator_->Alloc(2 * kSize); ASSERT_NE(FencedAllocator::kInvalidOffset, offset1); - EXPECT_EQ(0u, allocator()->GetLargestFreeSize()); + EXPECT_EQ(0u, allocator_->GetLargestFreeSize()); - allocator()->Free(offset); - allocator()->Free(offset1); - allocator()->Free(offset2); + allocator_->Free(offset); + allocator_->Free(offset1); + allocator_->Free(offset2); } // Tests GetLargestFreeOrPendingSize TEST_F(FencedAllocatorTest, TestGetLargestFreeOrPendingSize) { - EXPECT_TRUE(allocator()->CheckConsistency()); - EXPECT_EQ(kBufferSize, allocator()->GetLargestFreeOrPendingSize()); + EXPECT_TRUE(allocator_->CheckConsistency()); + EXPECT_EQ(kBufferSize, allocator_->GetLargestFreeOrPendingSize()); - FencedAllocator::Offset offset = allocator()->Alloc(kBufferSize); + FencedAllocator::Offset offset = allocator_->Alloc(kBufferSize); ASSERT_NE(FencedAllocator::kInvalidOffset, offset); - EXPECT_EQ(0u, allocator()->GetLargestFreeOrPendingSize()); - allocator()->Free(offset); - EXPECT_EQ(kBufferSize, allocator()->GetLargestFreeOrPendingSize()); + EXPECT_EQ(0u, allocator_->GetLargestFreeOrPendingSize()); + allocator_->Free(offset); + EXPECT_EQ(kBufferSize, allocator_->GetLargestFreeOrPendingSize()); const unsigned int kSize = 16; - offset = allocator()->Alloc(kSize); + offset = allocator_->Alloc(kSize); ASSERT_NE(FencedAllocator::kInvalidOffset, offset); // The following checks that the buffer is allocates "smartly" - which is // dependent on the implementation. But both first-fit or best-fit would // ensure that. - EXPECT_EQ(kBufferSize - kSize, allocator()->GetLargestFreeOrPendingSize()); + EXPECT_EQ(kBufferSize - kSize, allocator_->GetLargestFreeOrPendingSize()); // Allocate 2 more buffers (now 3), and then free the first two. This is to // ensure a hole. Note that this is dependent on the first-fit current // implementation. - FencedAllocator::Offset offset1 = allocator()->Alloc(kSize); + FencedAllocator::Offset offset1 = allocator_->Alloc(kSize); ASSERT_NE(FencedAllocator::kInvalidOffset, offset1); - FencedAllocator::Offset offset2 = allocator()->Alloc(kSize); + FencedAllocator::Offset offset2 = allocator_->Alloc(kSize); ASSERT_NE(FencedAllocator::kInvalidOffset, offset2); - allocator()->Free(offset); - allocator()->Free(offset1); + allocator_->Free(offset); + allocator_->Free(offset1); EXPECT_EQ(kBufferSize - 3 * kSize, - allocator()->GetLargestFreeOrPendingSize()); + allocator_->GetLargestFreeOrPendingSize()); // Free the last one, pending a token. - unsigned int token = helper()->InsertToken(); - allocator()->FreePendingToken(offset2, token); + int32 token = helper_.get()->InsertToken(); + allocator_->FreePendingToken(offset2, token); // Now all the buffers have been freed... - EXPECT_EQ(kBufferSize, allocator()->GetLargestFreeOrPendingSize()); + EXPECT_EQ(kBufferSize, allocator_->GetLargestFreeOrPendingSize()); // .. but one is still waiting for the token. EXPECT_EQ(kBufferSize - 3 * kSize, - allocator()->GetLargestFreeSize()); + allocator_->GetLargestFreeSize()); // The way we hooked up the helper and engine, it won't process commands // until it has to wait for something. Which means the token shouldn't have // passed yet at this point. - EXPECT_GT(token, engine()->GetToken()); + EXPECT_GT(token, command_buffer_->GetToken()); // This allocation will need to reclaim the space freed above, so that should // process the commands until the token is passed, but it will succeed. - offset = allocator()->Alloc(kBufferSize); + offset = allocator_->Alloc(kBufferSize); ASSERT_NE(FencedAllocator::kInvalidOffset, offset); // Check that the token has indeed passed. - EXPECT_LE(token, engine()->GetToken()); - allocator()->Free(offset); + EXPECT_LE(token, command_buffer_->GetToken()); + allocator_->Free(offset); // Everything now has been freed... - EXPECT_EQ(kBufferSize, allocator()->GetLargestFreeOrPendingSize()); + EXPECT_EQ(kBufferSize, allocator_->GetLargestFreeOrPendingSize()); // ... for real. - EXPECT_EQ(kBufferSize, allocator()->GetLargestFreeSize()); + EXPECT_EQ(kBufferSize, allocator_->GetLargestFreeSize()); } // Test fixture for FencedAllocatorWrapper test - Creates a @@ -314,102 +351,71 @@ TEST_F(FencedAllocatorTest, TestGetLargestFreeOrPendingSize) { // AsyncAPIInterface for its interface (calling it directly, not through the // RPC mechanism), making sure Noops are ignored and SetToken are properly // forwarded to the engine. -class FencedAllocatorWrapperTest : public testing::Test { - public: - static const unsigned int kBufferSize = 1024; - +class FencedAllocatorWrapperTest : public BaseFencedAllocatorTest { protected: virtual void SetUp() { - api_mock_.reset(new AsyncAPIMock); - // ignore noops in the mock - we don't want to inspect the internals of the - // helper. - EXPECT_CALL(*api_mock_, DoCommand(kNoop, 0, _)) - .WillRepeatedly(Return(BufferSyncInterface::kParseNoError)); - // Forward the SetToken calls to the engine - EXPECT_CALL(*api_mock(), DoCommand(kSetToken, 1, _)) - .WillRepeatedly(DoAll(Invoke(api_mock(), &AsyncAPIMock::SetToken), - Return(BufferSyncInterface::kParseNoError))); - engine_.reset(new CommandBufferEngine(api_mock_.get())); - api_mock_->set_engine(engine_.get()); - - nacl::SocketAddress client_address = { "test-socket" }; - client_socket_ = nacl::BoundSocket(&client_address); - engine_->InitConnection(); - helper_.reset(new CommandBufferHelper(engine_.get())); - helper_->Init(100); + BaseFencedAllocatorTest::SetUp(); // Though allocating this buffer isn't strictly necessary, it makes // allocations point to valid addresses, so they could be used for // something. buffer_.reset(new char[kBufferSize]); allocator_.reset(new FencedAllocatorWrapper(kBufferSize, helper_.get(), - base())); + buffer_.get())); } virtual void TearDown() { + // If the GPUProcessor posts any tasks, this forces them to run. + MessageLoop::current()->RunAllPending(); + EXPECT_TRUE(allocator_->CheckConsistency()); allocator_.release(); buffer_.release(); - helper_.release(); - engine_->CloseConnection(); - nacl::Close(client_socket_); + + BaseFencedAllocatorTest::TearDown(); } - CommandBufferHelper *helper() { return helper_.get(); } - CommandBufferEngine *engine() { return engine_.get(); } - AsyncAPIMock *api_mock() { return api_mock_.get(); } - FencedAllocatorWrapper *allocator() { return allocator_.get(); } - char *base() { return buffer_.get(); } - private: - scoped_ptr<AsyncAPIMock> api_mock_; - scoped_ptr<CommandBufferEngine> engine_; - scoped_ptr<CommandBufferHelper> helper_; scoped_ptr<FencedAllocatorWrapper> allocator_; scoped_array<char> buffer_; - nacl::Handle client_socket_; }; -#ifndef COMPILER_MSVC -const unsigned int FencedAllocatorWrapperTest::kBufferSize; -#endif - // Checks basic alloc and free. TEST_F(FencedAllocatorWrapperTest, TestBasic) { - allocator()->CheckConsistency(); + allocator_->CheckConsistency(); const unsigned int kSize = 16; - void *pointer = allocator()->Alloc(kSize); + void *pointer = allocator_->Alloc(kSize); ASSERT_TRUE(pointer); - EXPECT_LE(base(), static_cast<char *>(pointer)); - EXPECT_GE(kBufferSize, static_cast<char *>(pointer) - base() + kSize); - EXPECT_TRUE(allocator()->CheckConsistency()); + EXPECT_LE(buffer_.get(), static_cast<char *>(pointer)); + EXPECT_GE(kBufferSize, static_cast<char *>(pointer) - buffer_.get() + kSize); + EXPECT_TRUE(allocator_->CheckConsistency()); - allocator()->Free(pointer); - EXPECT_TRUE(allocator()->CheckConsistency()); + allocator_->Free(pointer); + EXPECT_TRUE(allocator_->CheckConsistency()); - char *pointer_char = allocator()->AllocTyped<char>(kSize); + char *pointer_char = allocator_->AllocTyped<char>(kSize); ASSERT_TRUE(pointer_char); - EXPECT_LE(base(), pointer_char); - EXPECT_GE(base() + kBufferSize, pointer_char + kSize); - allocator()->Free(pointer_char); - EXPECT_TRUE(allocator()->CheckConsistency()); + EXPECT_LE(buffer_.get(), pointer_char); + EXPECT_GE(buffer_.get() + kBufferSize, pointer_char + kSize); + allocator_->Free(pointer_char); + EXPECT_TRUE(allocator_->CheckConsistency()); - unsigned int *pointer_uint = allocator()->AllocTyped<unsigned int>(kSize); + unsigned int *pointer_uint = allocator_->AllocTyped<unsigned int>(kSize); ASSERT_TRUE(pointer_uint); - EXPECT_LE(base(), reinterpret_cast<char *>(pointer_uint)); - EXPECT_GE(base() + kBufferSize, + EXPECT_LE(buffer_.get(), reinterpret_cast<char *>(pointer_uint)); + EXPECT_GE(buffer_.get() + kBufferSize, reinterpret_cast<char *>(pointer_uint + kSize)); // Check that it did allocate kSize * sizeof(unsigned int). We can't tell // directly, except from the remaining size. EXPECT_EQ(kBufferSize - kSize * sizeof(*pointer_uint), - allocator()->GetLargestFreeSize()); - allocator()->Free(pointer_uint); + allocator_->GetLargestFreeSize()); + allocator_->Free(pointer_uint); } // Checks out-of-memory condition. TEST_F(FencedAllocatorWrapperTest, TestOutOfMemory) { - allocator()->CheckConsistency(); + allocator_->CheckConsistency(); const unsigned int kSize = 16; const unsigned int kAllocCount = kBufferSize / kSize; @@ -418,38 +424,38 @@ TEST_F(FencedAllocatorWrapperTest, TestOutOfMemory) { // Allocate several buffers to fill in the memory. void *pointers[kAllocCount]; for (unsigned int i = 0; i < kAllocCount; ++i) { - pointers[i] = allocator()->Alloc(kSize); + pointers[i] = allocator_->Alloc(kSize); EXPECT_TRUE(pointers[i]); - EXPECT_TRUE(allocator()->CheckConsistency()); + EXPECT_TRUE(allocator_->CheckConsistency()); } // This allocation should fail. - void *pointer_failed = allocator()->Alloc(kSize); + void *pointer_failed = allocator_->Alloc(kSize); EXPECT_FALSE(pointer_failed); - EXPECT_TRUE(allocator()->CheckConsistency()); + EXPECT_TRUE(allocator_->CheckConsistency()); // Free one successful allocation, reallocate with half the size - allocator()->Free(pointers[0]); - EXPECT_TRUE(allocator()->CheckConsistency()); - pointers[0] = allocator()->Alloc(kSize/2); + allocator_->Free(pointers[0]); + EXPECT_TRUE(allocator_->CheckConsistency()); + pointers[0] = allocator_->Alloc(kSize/2); EXPECT_TRUE(pointers[0]); - EXPECT_TRUE(allocator()->CheckConsistency()); + EXPECT_TRUE(allocator_->CheckConsistency()); // This allocation should fail as well. - pointer_failed = allocator()->Alloc(kSize); + pointer_failed = allocator_->Alloc(kSize); EXPECT_FALSE(pointer_failed); - EXPECT_TRUE(allocator()->CheckConsistency()); + EXPECT_TRUE(allocator_->CheckConsistency()); // Free up everything. for (unsigned int i = 0; i < kAllocCount; ++i) { - allocator()->Free(pointers[i]); - EXPECT_TRUE(allocator()->CheckConsistency()); + allocator_->Free(pointers[i]); + EXPECT_TRUE(allocator_->CheckConsistency()); } } // Checks the free-pending-token mechanism. TEST_F(FencedAllocatorWrapperTest, TestFreePendingToken) { - allocator()->CheckConsistency(); + allocator_->CheckConsistency(); const unsigned int kSize = 16; const unsigned int kAllocCount = kBufferSize / kSize; @@ -458,38 +464,38 @@ TEST_F(FencedAllocatorWrapperTest, TestFreePendingToken) { // Allocate several buffers to fill in the memory. void *pointers[kAllocCount]; for (unsigned int i = 0; i < kAllocCount; ++i) { - pointers[i] = allocator()->Alloc(kSize); + pointers[i] = allocator_->Alloc(kSize); EXPECT_TRUE(pointers[i]); - EXPECT_TRUE(allocator()->CheckConsistency()); + EXPECT_TRUE(allocator_->CheckConsistency()); } // This allocation should fail. - void *pointer_failed = allocator()->Alloc(kSize); + void *pointer_failed = allocator_->Alloc(kSize); EXPECT_FALSE(pointer_failed); - EXPECT_TRUE(allocator()->CheckConsistency()); + EXPECT_TRUE(allocator_->CheckConsistency()); // Free one successful allocation, pending fence. - unsigned int token = helper()->InsertToken(); - allocator()->FreePendingToken(pointers[0], token); - EXPECT_TRUE(allocator()->CheckConsistency()); + int32 token = helper_.get()->InsertToken(); + allocator_->FreePendingToken(pointers[0], token); + EXPECT_TRUE(allocator_->CheckConsistency()); // The way we hooked up the helper and engine, it won't process commands // until it has to wait for something. Which means the token shouldn't have // passed yet at this point. - EXPECT_GT(token, engine()->GetToken()); + EXPECT_GT(token, command_buffer_->GetToken()); // This allocation will need to reclaim the space freed above, so that should // process the commands until the token is passed. - pointers[0] = allocator()->Alloc(kSize); + pointers[0] = allocator_->Alloc(kSize); EXPECT_TRUE(pointers[0]); - EXPECT_TRUE(allocator()->CheckConsistency()); + EXPECT_TRUE(allocator_->CheckConsistency()); // Check that the token has indeed passed. - EXPECT_LE(token, engine()->GetToken()); + EXPECT_LE(token, command_buffer_->GetToken()); // Free up everything. for (unsigned int i = 0; i < kAllocCount; ++i) { - allocator()->Free(pointers[i]); - EXPECT_TRUE(allocator()->CheckConsistency()); + allocator_->Free(pointers[i]); + EXPECT_TRUE(allocator_->CheckConsistency()); } } diff --git a/o3d/command_buffer/command_buffer.gyp b/o3d/command_buffer/command_buffer.gyp index d6978c3..9d63cd1 100644 --- a/o3d/command_buffer/command_buffer.gyp +++ b/o3d/command_buffer/command_buffer.gyp @@ -32,17 +32,13 @@ { 'target_name': 'command_buffer_common', 'type': 'static_library', - 'dependencies': [ - '../../native_client/src/shared/imc/imc.gyp:google_nacl_imc', - '../../native_client/src/shared/imc/imc.gyp:libgoogle_nacl_imc_c', - '../../native_client/src/shared/platform/platform.gyp:platform', - '../../native_client/src/trusted/desc/desc.gyp:nrd_xfer', - '../../native_client/src/trusted/service_runtime/service_runtime.gyp:gio', - ], + 'all_dependent_settings': { + 'include_dirs': [ + '..', + ], + }, # 'all_dependent_settings' 'sources': [ 'common/cross/bitfield_helpers.h', - 'common/cross/buffer_sync_api.cc', - 'common/cross/buffer_sync_api.h', 'common/cross/cmd_buffer_format.h', 'common/cross/cmd_buffer_format.cc', 'common/cross/gapi_interface.h', @@ -50,9 +46,6 @@ 'common/cross/mocks.h', 'common/cross/resource.cc', 'common/cross/resource.h', - 'common/cross/rpc.h', - 'common/cross/rpc_imc.cc', - 'common/cross/rpc_imc.h', 'common/cross/types.h', ], }, @@ -62,9 +55,6 @@ 'direct_dependent_settings': { 'sources': [ 'common/cross/bitfield_helpers_test.cc', - 'client/cross/cmd_buffer_helper_test.cc', - 'client/cross/fenced_allocator_test.cc', - 'client/cross/id_allocator_test.cc', ], }, }, @@ -73,10 +63,9 @@ 'type': 'static_library', 'dependencies': [ 'command_buffer_common', + '../gpu_plugin/gpu_plugin.gyp:np_utils', ], 'sources': [ - 'client/cross/buffer_sync_proxy.cc', - 'client/cross/buffer_sync_proxy.h', 'client/cross/cmd_buffer_helper.cc', 'client/cross/cmd_buffer_helper.h', 'client/cross/effect_helper.cc', @@ -92,7 +81,6 @@ 'type': 'none', 'direct_dependent_settings': { 'sources': [ - 'client/cross/buffer_sync_proxy_test.cc', 'client/cross/cmd_buffer_helper_test.cc', 'client/cross/fenced_allocator_test.cc', 'client/cross/id_allocator_test.cc', @@ -102,13 +90,15 @@ { 'target_name': 'command_buffer_service', 'type': 'static_library', + 'all_dependent_settings': { + 'include_dirs': [ + '..', + ], + }, # 'all_dependent_settings' 'dependencies': [ 'command_buffer_common', ], 'sources': [ - 'service/cross/buffer_rpc.cc', - 'service/cross/buffer_rpc.h', - 'service/cross/cmd_buffer_engine.cc', 'service/cross/cmd_buffer_engine.h', 'service/cross/cmd_parser.cc', 'service/cross/cmd_parser.h', @@ -155,6 +145,11 @@ 'include_dirs': [ '$(DXSDK_DIR)/Include', ], + 'all_dependent_settings': { + 'include_dirs': [ + '$(DXSDK_DIR)/Include', + ], + }, # 'all_dependent_settings' 'sources': [ 'service/win/d3d9/d3d9_utils.h', 'service/win/d3d9/effect_d3d9.cc', @@ -171,11 +166,6 @@ 'service/win/d3d9/texture_d3d9.cc', 'service/win/d3d9/texture_d3d9.h', ], # 'sources' - 'direct_dependent_settings': { - 'include_dirs': [ - '$(DXSDK_DIR)/Include', - ], - }, # 'direct_dependent_settings' }, ], ['cb_service == "gl"', @@ -200,20 +190,6 @@ ], # 'sources' }, ], - ['cb_service != "none"', - { - 'target_name': 'command_buffer_service_test', - 'type': 'none', - 'direct_dependent_settings': { - 'sources': [ - 'service/cross/buffer_rpc_test.cc', - 'service/cross/cmd_buffer_engine_test.cc', - 'service/cross/cmd_parser_test.cc', - 'service/cross/resource_test.cc', - ], - }, - }, - ], ['OS == "linux"', { 'sources': [ @@ -224,6 +200,16 @@ ], ], # 'conditions' }, + { + 'target_name': 'command_buffer_service_test', + 'type': 'none', + 'direct_dependent_settings': { + 'sources': [ + 'service/cross/cmd_parser_test.cc', + 'service/cross/resource_test.cc', + ], + }, + }, ], # 'targets' } diff --git a/o3d/command_buffer/common/build.scons b/o3d/command_buffer/common/build.scons deleted file mode 100644 index 93f96bb..0000000 --- a/o3d/command_buffer/common/build.scons +++ /dev/null @@ -1,41 +0,0 @@ -# Copyright 2009, Google Inc. -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: -# -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following disclaimer -# in the documentation and/or other materials provided with the -# distribution. -# * Neither the name of Google Inc. nor the names of its -# contributors may be used to endorse or promote products derived from -# this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - -Import('env') - -INPUTS = [ - 'cross/buffer_sync_api.cc', - 'cross/cmd_buffer_format.cc', - 'cross/resource.cc', - 'cross/rpc_imc.cc', -] - -# Create a target library from the sources called 'o3dCmdBuf_common' -o3dcmdbuf_lib = env.ComponentLibrary('o3dCmdBuf_common', INPUTS) diff --git a/o3d/command_buffer/common/cross/buffer_sync_api.h b/o3d/command_buffer/common/cross/buffer_sync_api.h deleted file mode 100644 index bd61b5e..0000000 --- a/o3d/command_buffer/common/cross/buffer_sync_api.h +++ /dev/null @@ -1,169 +0,0 @@ -/* - * Copyright 2009, Google Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - - -// This file defines the Command Buffer Synchronous API. - -#ifndef O3D_COMMAND_BUFFER_COMMON_CROSS_BUFFER_SYNC_API_H_ -#define O3D_COMMAND_BUFFER_COMMON_CROSS_BUFFER_SYNC_API_H_ - -#include "command_buffer/common/cross/rpc.h" - -namespace o3d { -namespace command_buffer { - -// Command buffer type. -typedef size_t CommandBufferOffset; -const CommandBufferOffset kInvalidCommandBufferOffset = ~0u; - -// Interface class for the Command Buffer Synchronous API. -// This is the part of the command buffer API that is accessible through the -// RPC mechanism, synchronously. -class BufferSyncInterface { - public: - // Status of the command buffer service. It does not process commands - // (meaning: get will not change) unless in kParsing state. - enum ParserStatus { - kNotConnected, // The service is not connected - initial state. - kNoBuffer, // The service is connected but no buffer was set. - kParsing, // The service is connected, and parsing commands from the - // buffer. - kParseError, // Parsing stopped because a parse error was found. - }; - - enum ParseError { - kParseNoError, - kParseInvalidSize, - kParseOutOfBounds, - kParseUnknownCommand, - kParseInvalidArguments, - }; - - // Invalid shared memory Id, returned by RegisterSharedMemory in case of - // failure. - static const unsigned int kInvalidSharedMemoryId = 0xffffffffU; - - BufferSyncInterface() {} - virtual ~BufferSyncInterface() {} - - // Initializes the connection with the client. - virtual void InitConnection() = 0; - - // Closes the connection with the client. - virtual void CloseConnection() = 0; - - // Registers a shared memory buffer. While a buffer is registered, it can be - // accessed by the service, including the underlying asynchronous API, - // through a single identifier. - // Parameters: - // buffer: the shared memory buffer handle. - // Returns: - // an identifier for the shared memory, or kInvalidSharedMemoryId in case - // of failure. - virtual unsigned int RegisterSharedMemory(RPCShmHandle buffer, - size_t size) = 0; - - // Unregisters a shared memory buffer. - // Parameters: - // shm_id: the identifier for the shared memory buffer. - virtual void UnregisterSharedMemory(unsigned int shm_id) = 0; - - // Initializes the command buffer. - // Parameters: - // shm_id: the registered memory buffer in which the command buffer - // resides. - // offset: the offset of the command buffer, relative to the memory - // buffer. - // size: the size of the command buffer. - // start_get: the inital value for the Get pointer, relative to the - // command buffer, where the parser will start interpreting - // commands. Put is also initialized to that value. - virtual void SetCommandBuffer(unsigned int shm_id, - ptrdiff_t offset, - size_t size, - CommandBufferOffset start_get) = 0; - - // Sets the value of the Put pointer. - // Parameters: - // offset: the new value of the Put pointer, as an offset into the command - // buffer. - virtual void Put(CommandBufferOffset offset) = 0; - - // Gets the value of the Get pointer. - // Returns: - // the current value of the Get pointer, as an offset into the command - // buffer. - virtual CommandBufferOffset Get() = 0; - - // Gets the current token value. - // Returns: - // the current token value. - virtual unsigned int GetToken() = 0; - - // Waits until Get changes from the currently known value. - // Parameters: - // current_value: the currently known value. This call will block until - // Get is different from that value (returning immediately - // if it is different). - // Returns: - // the current (changed) value of Get. - virtual CommandBufferOffset WaitGetChanges( - CommandBufferOffset current_value) = 0; - - // Asks the service to signal the client when Get changes from the currently - // known value. This is a non-blocking version of WaitGetChanges. - // Parameters: - // current_value: the currently known value of Get. - // rpc_message_id: the RPC message ID to call on the client when Get is - // different from current_value. That RPC is called - // immediately if Get is already different from - // current_value. - virtual void SignalGetChanges(CommandBufferOffset current_value, - int rpc_message_id) = 0; - - // Gets the status of the service. - // Returns: - // The status of the service. - virtual ParserStatus GetStatus() = 0; - - // Gets the current parse error. The current parse error is set when the - // service is in the PARSE_ERROR status. It may also be set while in the - // kParsing state, if a recoverable error (like PARSE_UNKNOWN_METHOD) was - // encountered. Getting the error resets it to kParseNoError. - // Returns: - // The current parse error. - virtual ParseError GetParseError() = 0; -}; - -} // namespace command_buffer -} // namespace o3d - -#endif // O3D_COMMAND_BUFFER_COMMON_CROSS_BUFFER_SYNC_API_H_ diff --git a/o3d/command_buffer/service/cross/big_test_helpers.h b/o3d/command_buffer/common/cross/constants.h index bb90564..f72c5a3 100644 --- a/o3d/command_buffer/service/cross/big_test_helpers.h +++ b/o3d/command_buffer/common/cross/constants.h @@ -30,41 +30,44 @@ */ -// This file contains a few helper functions for running big tests. +#ifndef O3D_COMMAND_BUFFER_COMMON_CROSS_CONSTANTS_H_ +#define O3D_COMMAND_BUFFER_COMMON_CROSS_CONSTANTS_H_ -#ifndef O3D_COMMAND_BUFFER_SERVICE_CROSS_BIG_TEST_HELPERS_H_ -#define O3D_COMMAND_BUFFER_SERVICE_CROSS_BIG_TEST_HELPERS_H_ - -#include <build/build_config.h> -#include "core/cross/types.h" -#include "command_buffer/common/cross/gapi_interface.h" +#include "base/basictypes.h" namespace o3d { namespace command_buffer { -extern String *g_program_path; -extern GAPIInterface *g_gapi; - -// very simple thread API (hides platform-specific implementations). -typedef void (* ThreadFunc)(void *param); -class Thread; +typedef int32 CommandBufferOffset; +const CommandBufferOffset kInvalidCommandBufferOffset = -1; -// Creates and starts a thread. -Thread *CreateThread(ThreadFunc func, void* param); +// Status of the command buffer service. It does not process commands +// (meaning: get will not change) unless in kParsing state. +namespace parser_status { + enum ParserStatus { + kNotConnected, // The service is not connected - initial state. + kNoBuffer, // The service is connected but no buffer was set. + kParsing, // The service is connected, and parsing commands from the + // buffer. + kParseError, // Parsing stopped because a parse error was found. + }; +} -// Joins (waits for) a thread, destroying it. -void JoinThread(Thread *thread); +namespace parse_error { + enum ParseError { + kParseNoError, + kParseInvalidSize, + kParseOutOfBounds, + kParseUnknownCommand, + kParseInvalidArguments, + }; +} -// Processes system messages. Should be called once a frame at least. -bool ProcessSystemMessages(); +// Invalid shared memory Id, returned by RegisterSharedMemory in case of +// failure. +const int32 kInvalidSharedMemoryId = -1; } // namespace command_buffer } // namespace o3d -#ifdef OS_WIN -int big_test_main(int argc, wchar_t **argv); -#else -int big_test_main(int argc, char **argv); -#endif - -#endif // O3D_COMMAND_BUFFER_SERVICE_CROSS_BIG_TEST_HELPERS_H_ +#endif // O3D_COMMAND_BUFFER_COMMON_CROSS_CONSTANTS_H_ diff --git a/o3d/command_buffer/common/cross/gapi_interface.h b/o3d/command_buffer/common/cross/gapi_interface.h index f72b858..a6f47a3 100644 --- a/o3d/command_buffer/common/cross/gapi_interface.h +++ b/o3d/command_buffer/common/cross/gapi_interface.h @@ -36,7 +36,7 @@ #ifndef O3D_COMMAND_BUFFER_COMMON_CROSS_GAPI_INTERFACE_H_ #define O3D_COMMAND_BUFFER_COMMON_CROSS_GAPI_INTERFACE_H_ -#include "command_buffer/common/cross/buffer_sync_api.h" +#include "command_buffer/common/cross/constants.h" #include "command_buffer/common/cross/resource.h" #include "command_buffer/common/cross/cmd_buffer_format.h" @@ -54,7 +54,7 @@ struct RGBA { // This class defines the low-level graphics API, as a pure interface class. class GAPIInterface { public: - typedef BufferSyncInterface::ParseError ParseError; + typedef parse_error::ParseError ParseError; GAPIInterface() {} virtual ~GAPIInterface() {} @@ -92,8 +92,8 @@ class GAPIInterface { // size: the size of the vertex buffer, in bytes. // flags: the vertex buffer flags, as a combination of vertex_buffer::Flags // Returns: - // BufferSyncInterface::kParseInvalidArguments if invalid arguments are - // passed, BufferSyncInterface::kParseNoError otherwise. + // parse_error::kParseInvalidArguments if invalid arguments are + // passed, parse_error::kParseNoError otherwise. virtual ParseError CreateVertexBuffer(ResourceId id, unsigned int size, unsigned int flags) = 0; @@ -102,8 +102,8 @@ class GAPIInterface { // Parameters: // id: the resource ID of the vertex buffer. // Returns: - // BufferSyncInterface::kParseInvalidArguments if an invalid vertex buffer - // ID was passed, BufferSyncInterface::kParseNoError otherwise. + // parse_error::kParseInvalidArguments if an invalid vertex buffer + // ID was passed, parse_error::kParseNoError otherwise. virtual ParseError DestroyVertexBuffer(ResourceId id) = 0; // Sets data into a vertex buffer. @@ -113,9 +113,9 @@ class GAPIInterface { // size: the size of the data. // data: the source data. // Returns: - // BufferSyncInterface::kParseInvalidArguments if invalid arguments were + // parse_error::kParseInvalidArguments if invalid arguments were // passed: invalid resource ID, or offset or size out of range. - // BufferSyncInterface::kParseNoError otherwise. + // parse_error::kParseNoError otherwise. virtual ParseError SetVertexBufferData(ResourceId id, unsigned int offset, unsigned int size, @@ -128,9 +128,9 @@ class GAPIInterface { // size: the size of the data. // data: the destination buffer. // Returns: - // BufferSyncInterface::kParseInvalidArguments if invalid arguments were + // parse_error::kParseInvalidArguments if invalid arguments were // passed: invalid resource ID, or offset or size out of range. - // BufferSyncInterface::kParseNoError otherwise. + // parse_error::kParseNoError otherwise. virtual ParseError GetVertexBufferData(ResourceId id, unsigned int offset, unsigned int size, @@ -144,8 +144,8 @@ class GAPIInterface { // Note that indices are 16 bits unless the index_buffer::INDEX_32BIT // flag is specified. // Returns: - // BufferSyncInterface::kParseInvalidArguments if invalid arguments are - // passed, BufferSyncInterface::kParseNoError otherwise. + // parse_error::kParseInvalidArguments if invalid arguments are + // passed, parse_error::kParseNoError otherwise. virtual ParseError CreateIndexBuffer(ResourceId id, unsigned int size, unsigned int flags) = 0; @@ -154,8 +154,8 @@ class GAPIInterface { // Parameters: // id: the resource ID of the index buffer. // Returns: - // BufferSyncInterface::kParseInvalidArguments if an invalid index buffer - // ID was passed, BufferSyncInterface::kParseNoError otherwise. + // parse_error::kParseInvalidArguments if an invalid index buffer + // ID was passed, parse_error::kParseNoError otherwise. virtual ParseError DestroyIndexBuffer(ResourceId id) = 0; // Sets data into an index buffer. @@ -165,9 +165,9 @@ class GAPIInterface { // size: the size of the data. // data: the source data. // Returns: - // BufferSyncInterface::kParseInvalidArguments if invalid arguments were + // parse_error::kParseInvalidArguments if invalid arguments were // passed: invalid resource ID, or offset or size out of range. - // BufferSyncInterface::kParseNoError otherwise. + // parse_error::kParseNoError otherwise. virtual ParseError SetIndexBufferData(ResourceId id, unsigned int offset, unsigned int size, @@ -180,9 +180,9 @@ class GAPIInterface { // size: the size of the data. // data: the destination buffer. // Returns: - // BufferSyncInterface::kParseInvalidArguments if invalid arguments were + // parse_error::kParseInvalidArguments if invalid arguments were // passed: invalid resource ID, or offset or size out of range. - // BufferSyncInterface::kParseNoError otherwise. + // parse_error::kParseNoError otherwise. virtual ParseError GetIndexBufferData(ResourceId id, unsigned int offset, unsigned int size, @@ -194,8 +194,8 @@ class GAPIInterface { // id: the resource ID of the vertex struct. // input_count: the number of input vertex attributes. // returns: - // BufferSyncInterface::kParseInvalidArguments if invalid arguments are - // passed, BufferSyncInterface::kParseNoError otherwise. + // parse_error::kParseInvalidArguments if invalid arguments are + // passed, parse_error::kParseNoError otherwise. virtual ParseError CreateVertexStruct(ResourceId id, unsigned int input_count) = 0; @@ -203,8 +203,8 @@ class GAPIInterface { // Parameters: // id: the resource ID of the vertex struct. // Returns: - // BufferSyncInterface::kParseInvalidArguments if an invalid vertex struct - // ID was passed, BufferSyncInterface::kParseNoError otherwise. + // parse_error::kParseInvalidArguments if an invalid vertex struct + // ID was passed, parse_error::kParseNoError otherwise. virtual ParseError DestroyVertexStruct(ResourceId id) = 0; // Sets an input into a vertex struct. @@ -219,8 +219,8 @@ class GAPIInterface { // semantic: the semantic of the input. // semantic_index: the semantic index of the input. // Returns: - // BufferSyncInterface::kParseInvalidArguments if invalid arguments are - // passed, BufferSyncInterface::kParseNoError otherwise. + // parse_error::kParseInvalidArguments if invalid arguments are + // passed, parse_error::kParseNoError otherwise. virtual ParseError SetVertexInput(ResourceId vertex_struct_id, unsigned int input_index, ResourceId vertex_buffer_id, @@ -234,8 +234,8 @@ class GAPIInterface { // Parameters: // id: the resource ID of the vertex struct. // Returns: - // BufferSyncInterface::kParseInvalidArguments if invalid arguments are - // passed (invalid vertex struct), BufferSyncInterface::kParseNoError + // parse_error::kParseInvalidArguments if invalid arguments are + // passed (invalid vertex struct), parse_error::kParseNoError // otherwise. virtual ParseError SetVertexStruct(ResourceId id) = 0; @@ -245,8 +245,8 @@ class GAPIInterface { // first: the index of the first vertex. // count: the number of primitives to draw. // Returns: - // BufferSyncInterface::kParseInvalidArguments if invalid arguments are - // passed, BufferSyncInterface::kParseNoError otherwise. + // parse_error::kParseInvalidArguments if invalid arguments are + // passed, parse_error::kParseNoError otherwise. virtual ParseError Draw(PrimitiveType primitive_type, unsigned int first, unsigned int count) = 0; @@ -261,8 +261,8 @@ class GAPIInterface { // min_index: the lowest index being drawn. // max_index: the highest index being drawn. // Returns: - // BufferSyncInterface::kParseInvalidArguments if invalid arguments are - // passed, BufferSyncInterface::kParseNoError otherwise. + // parse_error::kParseInvalidArguments if invalid arguments are + // passed, parse_error::kParseNoError otherwise. virtual ParseError DrawIndexed(PrimitiveType primitive_type, ResourceId index_buffer_id, unsigned int first, @@ -276,9 +276,9 @@ class GAPIInterface { // size: the size of data. // data: the source code for the effect. // Returns: - // BufferSyncInterface::kParseInvalidArguments if invalid arguments are + // parse_error::kParseInvalidArguments if invalid arguments are // passed or the effect failed to compile, - // BufferSyncInterface::kParseNoError otherwise. + // parse_error::kParseNoError otherwise. virtual ParseError CreateEffect(ResourceId id, unsigned int size, const void *data) = 0; @@ -287,16 +287,16 @@ class GAPIInterface { // Parameters: // id: the resource ID of the effect. // Returns: - // BufferSyncInterface::kParseInvalidArguments if an invalid effect ID - // was passed, BufferSyncInterface::kParseNoError otherwise. + // parse_error::kParseInvalidArguments if an invalid effect ID + // was passed, parse_error::kParseNoError otherwise. virtual ParseError DestroyEffect(ResourceId id) = 0; // Sets the active effect for drawing. // Parameters: // id: the resource ID of the effect. // Returns: - // BufferSyncInterface::kParseInvalidArguments if invalid arguments are - // passed, BufferSyncInterface::kParseNoError otherwise. + // parse_error::kParseInvalidArguments if invalid arguments are + // passed, parse_error::kParseNoError otherwise. virtual ParseError SetEffect(ResourceId id) = 0; // Gets the number of parameters in an effect, returning it in a memory @@ -307,8 +307,8 @@ class GAPIInterface { // Uint32). // data: the buffer receiving the data. // Returns: - // BufferSyncInterface::kParseInvalidArguments if invalid arguments are - // passed, BufferSyncInterface::kParseNoError otherwise. + // parse_error::kParseInvalidArguments if invalid arguments are + // passed, parse_error::kParseNoError otherwise. virtual ParseError GetParamCount(ResourceId id, unsigned int size, void *data) = 0; @@ -321,9 +321,9 @@ class GAPIInterface { // the effect source. // index: the index of the parameter. // Returns: - // BufferSyncInterface::kParseInvalidArguments if invalid arguments are + // parse_error::kParseInvalidArguments if invalid arguments are // passed, such as invalid effect ID, unmatching data type or invalid - // index, BufferSyncInterface::kParseNoError otherwise. + // index, parse_error::kParseNoError otherwise. virtual ParseError CreateParam(ResourceId param_id, ResourceId effect_id, unsigned int index) = 0; @@ -338,9 +338,9 @@ class GAPIInterface { // name: the parameter name, as an array of char. Doesn't have to be // nul-terminated (though nul will terminate the string). // Returns: - // BufferSyncInterface::kParseInvalidArguments if invalid arguments are + // parse_error::kParseInvalidArguments if invalid arguments are // passed, such as invalid effect ID, unmatching data type or no parameter - // was found with this name, BufferSyncInterface::kParseNoError otherwise. + // was found with this name, parse_error::kParseNoError otherwise. virtual ParseError CreateParamByName(ResourceId param_id, ResourceId effect_id, unsigned int size, @@ -350,8 +350,8 @@ class GAPIInterface { // Parameters: // id: the resource ID of the parameter. // Returns: - // BufferSyncInterface::kParseInvalidArguments if an invalid parameter ID - // was passed, BufferSyncInterface::kParseNoError otherwise. + // parse_error::kParseInvalidArguments if an invalid parameter ID + // was passed, parse_error::kParseNoError otherwise. virtual ParseError DestroyParam(ResourceId id) = 0; // Sets the effect parameter data. @@ -360,9 +360,9 @@ class GAPIInterface { // size: the size of the data. Must be at least the size of the parameter // as described by its type. // data: the parameter data. - // BufferSyncInterface::kParseInvalidArguments if invalid arguments are + // parse_error::kParseInvalidArguments if invalid arguments are // passed, such as invalid parameter ID, or unmatching data size, - // BufferSyncInterface::kParseNoError otherwise. + // parse_error::kParseNoError otherwise. virtual ParseError SetParamData(ResourceId id, unsigned int size, const void *data) = 0; @@ -382,10 +382,10 @@ class GAPIInterface { // description. Must be at least sizeof(effect_param::Desc). // data: the memory buffer. // Returns: - // BufferSyncInterface::kParseInvalidArguments if invalid arguments are + // parse_error::kParseInvalidArguments if invalid arguments are // passed, such as invalid parameter ID, or unsufficient data size, - // BufferSyncInterface::kParseNoError otherwise. Note that - // BufferSyncInterface::kParseNoError will be returned if the structure + // parse_error::kParseNoError otherwise. Note that + // parse_error::kParseNoError will be returned if the structure // itself fits, not necessarily the names. To make sure all the information // is available, the caller should compare the returned size member of the // effect_param::Desc structure to the size parameter passed in. @@ -401,8 +401,8 @@ class GAPIInterface { // Uint32). // data: the buffer receiving the data. // Returns: - // BufferSyncInterface::kParseInvalidArguments if invalid arguments are - // passed, BufferSyncInterface::kParseNoError otherwise. + // parse_error::kParseInvalidArguments if invalid arguments are + // passed, parse_error::kParseNoError otherwise. virtual ParseError GetStreamCount(ResourceId id, unsigned int size, void *data) = 0; @@ -432,8 +432,8 @@ class GAPIInterface { // flags: the texture flags, as a combination of texture::Flags. // enable_render_surfaces: bool for whether to enable render surfaces // Returns: - // BufferSyncInterface::kParseInvalidArguments if invalid arguments are - // passed, BufferSyncInterface::kParseNoError otherwise. + // parse_error::kParseInvalidArguments if invalid arguments are + // passed, parse_error::kParseNoError otherwise. virtual ParseError CreateTexture2D(ResourceId id, unsigned int width, unsigned int height, @@ -454,8 +454,8 @@ class GAPIInterface { // flags: the texture flags, as a combination of texture::Flags. // enable_render_surfaces: bool for whether to enable render surfaces // Returns: - // BufferSyncInterface::kParseInvalidArguments if invalid arguments are - // passed, BufferSyncInterface::kParseNoError otherwise. + // parse_error::kParseInvalidArguments if invalid arguments are + // passed, parse_error::kParseNoError otherwise. virtual ParseError CreateTexture3D(ResourceId id, unsigned int width, unsigned int height, @@ -475,8 +475,8 @@ class GAPIInterface { // flags: the texture flags, as a combination of texture::Flags. // enable_render_surfaces: bool for whether to enable render surfaces // Returns: - // BufferSyncInterface::kParseInvalidArguments if invalid arguments are - // passed, BufferSyncInterface::kParseNoError otherwise. + // parse_error::kParseInvalidArguments if invalid arguments are + // passed, parse_error::kParseNoError otherwise. virtual ParseError CreateTextureCube(ResourceId id, unsigned int side, unsigned int levels, @@ -511,9 +511,9 @@ class GAPIInterface { // size: the size of the data. // data: the texel data. // Returns: - // BufferSyncInterface::kParseInvalidArguments if invalid arguments are + // parse_error::kParseInvalidArguments if invalid arguments are // passed, for example invalid size, or out-of-bounds rectangle/volume, - // BufferSyncInterface::kParseNoError otherwise. + // parse_error::kParseNoError otherwise. virtual ParseError SetTextureData(ResourceId id, unsigned int x, unsigned int y, @@ -555,9 +555,9 @@ class GAPIInterface { // size: the size of the data. // data: the destination buffer. // Returns: - // BufferSyncInterface::kParseInvalidArguments if invalid arguments are + // parse_error::kParseInvalidArguments if invalid arguments are // passed, for example invalid size, or out-of-bounds rectangle/volume, - // BufferSyncInterface::kParseNoError otherwise. + // parse_error::kParseNoError otherwise. virtual ParseError GetTextureData(ResourceId id, unsigned int x, unsigned int y, @@ -576,23 +576,23 @@ class GAPIInterface { // Parameters: // id: the resource ID of the texture. // Returns: - // BufferSyncInterface::kParseInvalidArguments if an invalid texture - // resource ID was passed, BufferSyncInterface::kParseNoError otherwise. + // parse_error::kParseInvalidArguments if an invalid texture + // resource ID was passed, parse_error::kParseNoError otherwise. virtual ParseError DestroyTexture(ResourceId id) = 0; // Creates a sampler resource. // Parameters: // id: the resource ID of the sampler. // Returns: - // BufferSyncInterface::kParseNoError. + // parse_error::kParseNoError. virtual ParseError CreateSampler(ResourceId id) = 0; // Destroys a sampler resource. // Parameters: // id: the resource ID of the sampler. // Returns: - // BufferSyncInterface::kParseInvalidArguments if an invalid sampler - // resource ID was passed, BufferSyncInterface::kParseNoError otherwise. + // parse_error::kParseInvalidArguments if an invalid sampler + // resource ID was passed, parse_error::kParseNoError otherwise. virtual ParseError DestroySampler(ResourceId id) = 0; // Sets the states in a sampler resource. @@ -606,8 +606,8 @@ class GAPIInterface { // mip_filter: the filtering mode for mip-map interpolation textures. // max_anisotropy: the maximum anisotropy. // Returns: - // BufferSyncInterface::kParseInvalidArguments if an invalid sampler - // resource ID was passed, BufferSyncInterface::kParseNoError otherwise. + // parse_error::kParseInvalidArguments if an invalid sampler + // resource ID was passed, parse_error::kParseNoError otherwise. virtual ParseError SetSamplerStates(ResourceId id, sampler::AddressingMode addressing_u, sampler::AddressingMode addressing_v, @@ -622,8 +622,8 @@ class GAPIInterface { // id: the resource ID of the sampler. // color: the border color. // Returns: - // BufferSyncInterface::kParseInvalidArguments if an invalid sampler - // resource ID was passed, BufferSyncInterface::kParseNoError otherwise. + // parse_error::kParseInvalidArguments if an invalid sampler + // resource ID was passed, parse_error::kParseNoError otherwise. virtual ParseError SetSamplerBorderColor(ResourceId id, const RGBA &color) = 0; @@ -632,8 +632,8 @@ class GAPIInterface { // id: the resource ID of the sampler. // texture_id: the resource id of the texture. // Returns: - // BufferSyncInterface::kParseInvalidArguments if an invalid sampler - // resource ID was passed, BufferSyncInterface::kParseNoError otherwise. + // parse_error::kParseInvalidArguments if an invalid sampler + // resource ID was passed, parse_error::kParseNoError otherwise. virtual ParseError SetSamplerTexture(ResourceId id, ResourceId texture_id) = 0; @@ -772,8 +772,8 @@ class GAPIInterface { // height: the texture height. Must be positive. // texture_id: the resource id of the texture. // Returns: - // BufferSyncInterface::kParseInvalidArguments if invalid arguments are - // passed, BufferSyncInterface::kParseNoError otherwise. + // parse_error::kParseInvalidArguments if invalid arguments are + // passed, parse_error::kParseNoError otherwise. virtual ParseError CreateRenderSurface(ResourceId id, unsigned int width, unsigned int height,
@@ -785,9 +785,9 @@ class GAPIInterface { // Parameters: // id: the resource ID of the render surface. // Returns: - // BufferSyncInterface::kParseInvalidArguments if an invalid render + // parse_error::kParseInvalidArguments if an invalid render // surface - // resource ID was passed, BufferSyncInterface::kParseNoError otherwise. + // resource ID was passed, parse_error::kParseNoError otherwise. virtual ParseError DestroyRenderSurface(ResourceId id) = 0; // Creates a depth stencil surface resource. @@ -796,8 +796,8 @@ class GAPIInterface { // width: the texture width. Must be positive. // height: the texture height. Must be positive. // Returns: - // BufferSyncInterface::kParseInvalidArguments if invalid arguments are - // passed, BufferSyncInterface::kParseNoError otherwise. + // parse_error::kParseInvalidArguments if invalid arguments are + // passed, parse_error::kParseNoError otherwise. virtual ParseError CreateDepthSurface(ResourceId id, unsigned int width, unsigned int height) = 0; @@ -806,9 +806,9 @@ class GAPIInterface { // Parameters: // id: the resource ID of the depth stencil surface. // Returns: - // BufferSyncInterface::kParseInvalidArguments if an invalid render + // parse_error::kParseInvalidArguments if an invalid render // surface - // resource ID was passed, BufferSyncInterface::kParseNoError otherwise. + // resource ID was passed, parse_error::kParseNoError otherwise. virtual ParseError DestroyDepthSurface(ResourceId id) = 0; // Switches the render surface and depth stencil surface to those @@ -817,8 +817,8 @@ class GAPIInterface { // render_surface_id: the resource ID of the render surface. // depth_stencil_id: the resource ID of the render depth stencil surface. // Returns: - // BufferSyncInterface::kParseInvalidArguments if invalid arguments are - // passed, BufferSyncInterface::kParseNoError otherwise. + // parse_error::kParseInvalidArguments if invalid arguments are + // passed, parse_error::kParseNoError otherwise. virtual ParseError SetRenderSurface(ResourceId render_surface_id, ResourceId depth_stencil_id) = 0; diff --git a/o3d/command_buffer/common/cross/mocks.h b/o3d/command_buffer/common/cross/mocks.h deleted file mode 100644 index 7ee8fd6..0000000 --- a/o3d/command_buffer/common/cross/mocks.h +++ /dev/null @@ -1,148 +0,0 @@ -/* - * Copyright 2009, Google Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - - -// This file contains definitions for mock objects, used for testing. - -// TODO: This file "manually" defines some mock objects. Using gMock -// would be definitely preferable, unfortunately it doesn't work on Windows -// yet. - -#ifndef O3D_COMMAND_BUFFER_COMMON_CROSS_MOCKS_H_ -#define O3D_COMMAND_BUFFER_COMMON_CROSS_MOCKS_H_ - -#include <vector> -#include "gmock/gmock.h" -#include "command_buffer/common/cross/rpc.h" -#include "command_buffer/common/cross/buffer_sync_api.h" - -namespace o3d { -namespace command_buffer { - -// Mocks a RPC send interface. This class only mocks SendCall currently. -// Set call expectations with AddSendCallExpect: one for each call with exact -// parameters, and desired return value, then run the test. -class RPCSendInterfaceMock : public RPCSendInterface { - public: - RPCSendInterfaceMock() : called_(0) {} - virtual ~RPCSendInterfaceMock() { Check(); } - - // Checks that the expected number of calls actually happened. - void Check() { - EXPECT_EQ(expects_.size(), called_); - } - - // Struct describing a SendCall call expectation, with the desired return - // value. - struct SendCallExpect { - RPCImplInterface::ReturnValue _return; - int message_id; - const void * data; - size_t size; - RPCHandle * handles; - size_t handle_count; - }; - - // Adds an expectation for a SendCall call. - void AddSendCallExpect(const SendCallExpect &expect) { - expects_.push_back(expect); - } - - // Mock SendCall implementation. This will check the arguments against the - // expected values (the values pointed by 'data' are compared, not the - // pointer), and return the desired return value. - virtual RPCImplInterface::ReturnValue SendCall(int message_id, - const void * data, - size_t size, - RPCHandle const *handles, - size_t handle_count) { - if (called_ < expects_.size()) { - const SendCallExpect &expect = expects_[called_]; - ++called_; - EXPECT_EQ(expect.message_id, message_id); - EXPECT_EQ(expect.size, size); - if (expect.size != size) return 0; - EXPECT_EQ(expect.handle_count, handle_count); - if (expect.handle_count != handle_count) return 0; - if (size > 0) { - EXPECT_EQ(0, memcmp(expect.data, data, size)); - } else { - EXPECT_FALSE(data); - } - if (handle_count > 0) { - for (unsigned int i = 0; i < handle_count; ++i) { - EXPECT_TRUE(expect.handles[i] == handles[i]); - } - } else { - EXPECT_FALSE(handles); - } - return expect._return; - } else { - ++called_; - // This is really an EXPECT_FALSE, but we get to display useful values. - EXPECT_GE(expects_.size(), called_); - // We need to return something but we don't know what, we don't have any - // expectation for this call. 0 will do. - return 0; - } - } - private: - size_t called_; - std::vector<SendCallExpect> expects_; -}; - -// Mocks a BufferSyncInterface, using GMock. -class BufferSyncMock : public BufferSyncInterface { - public: - MOCK_METHOD0(InitConnection, void()); - MOCK_METHOD0(CloseConnection, void()); - MOCK_METHOD2(RegisterSharedMemory, unsigned int(RPCShmHandle buffer, - size_t size)); - MOCK_METHOD1(UnregisterSharedMemory, void(unsigned int shm_id)); - MOCK_METHOD4(SetCommandBuffer, void(unsigned int shm_id, - ptrdiff_t offset, - size_t size, - CommandBufferOffset start_get)); - MOCK_METHOD1(Put, void(CommandBufferOffset offset)); - MOCK_METHOD0(Get, CommandBufferOffset()); - MOCK_METHOD0(GetToken, unsigned int()); - MOCK_METHOD1(WaitGetChanges, - CommandBufferOffset(CommandBufferOffset current_value)); - MOCK_METHOD2(SignalGetChanges, void(CommandBufferOffset current_value, - int rpc_message_id)); - MOCK_METHOD0(GetStatus, ParserStatus()); - MOCK_METHOD0(GetParseError, ParseError()); -}; - -} // namespace command_buffer -} // namespace o3d - -#endif // O3D_COMMAND_BUFFER_COMMON_CROSS_MOCKS_H_ diff --git a/o3d/command_buffer/common/cross/rpc.h b/o3d/command_buffer/common/cross/rpc.h deleted file mode 100644 index 6e95ee2..0000000 --- a/o3d/command_buffer/common/cross/rpc.h +++ /dev/null @@ -1,160 +0,0 @@ -/* - * Copyright 2009, Google Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - - -#ifndef O3D_COMMAND_BUFFER_COMMON_CROSS_RPC_H_ -#define O3D_COMMAND_BUFFER_COMMON_CROSS_RPC_H_ - -#include "base/basictypes.h" - -#include "native_client/src/shared/imc/nacl_htp.h" - -namespace o3d { -namespace command_buffer { - -// Pre-defined message IDs. -enum { - POISONED_MESSAGE_ID, // sent to kill the RPC server. - RESPONSE_ID, // sent as a response to a RPC call. -}; - -typedef nacl::HtpHandle RPCHandle; -typedef RPCHandle RPCShmHandle; -typedef RPCHandle RPCSocketHandle; -static const RPCHandle kRPCInvalidHandle = nacl::kInvalidHtpHandle; - -// Interface for a RPC implementation. This class defines the calls a RPC -// service needs to implement. -class RPCImplInterface { - public: - // The type of return values for RPC calls. The RPC model is an arbitrary - // set of parameters, but a single return value. - typedef unsigned int ReturnValue; - - RPCImplInterface() {} - virtual ~RPCImplInterface() {} - - // De-multiplexes a RPC call. This function takes the message ID and the data - // to deduce a proper function to call, with its arguments, returning a - // single value. Most protocols will select the function from the message ID, - // and take the arguments from the data. - // Parameters: - // message_id: the RPC message ID. - // data: the RPC message payload. - // size: the size of the data. - // Returns: - // a single return value from the function called. - virtual ReturnValue DoCall(int message_id, - const void * data, - size_t size, - RPCHandle const *handles, - size_t handle_count) = 0; - - private: - DISALLOW_COPY_AND_ASSIGN(RPCImplInterface); -}; - -class RPCSendInterface { - public: - virtual ~RPCSendInterface() {} - // Sends a call to the server thread. This call will be dispatched by the - // server thread to the RPC implementation. This call will block until the - // call is processed and the return value is sent back. - // Parameters: - // message_id: the RPC message ID. - // data: the RPC message payload. - // size: the size of the data. - // handles: an array of RPC handles to transmit - // handle_count: the number of RPC handles in the array - // Returns: - // the return value of the RPC call. - virtual RPCImplInterface::ReturnValue SendCall(int message_id, - const void * data, - size_t size, - RPCHandle const *handles, - size_t handle_count) = 0; -}; - -class RPCProcessInterface { - public: - virtual ~RPCProcessInterface() {} - // Processes one message, blocking if necessary until a message is available - // or the server is killed. This will dispatch the received message to the - // RPC implementation, and send back a response message with the return - // value to the client. - // Returns: - // false if the server was killed. - virtual bool ProcessMessage() = 0; - - // Checks whether a message is available for processing - allowing to test if - // ProcessMessage will block. - // Returns: - // true if a message is available. - virtual bool HasMessage() = 0; -}; - -// Creates a RPCSendInterface from a RPCSocketHandle. -RPCSendInterface *MakeSendInterface(RPCSocketHandle handle); - -// Creates a shared memory buffer. -// Parameters: -// size: the size of the buffer. -// Returns: -// the handle to the shared memory buffer. -RPCShmHandle CreateShm(size_t size); - -// Destroys a shared memory buffer. -// Parameters: -// handle: the handle to the shared memory buffer. -void DestroyShm(RPCShmHandle handle); - -// Maps a shared memory buffer into the address space. -// Parameters: -// handle: the handle to the shared memory buffer. -// size: the size of the region to map in the memory buffer. May be smaller -// than the shared memory region, but the underlying implementation -// will round it up to the page size or the whole shared memory. -// Returns: -// the address of the mapped region, or NULL if failure. -void *MapShm(RPCShmHandle handle, size_t size); - -// Unmaps a previously mapped memory buffer. -// Parameters: -// address: the address of the mapped region. -// size: the size of the region to un-map. It can be a subset of the -// previously mapped region, but the underlying implementation will -// round it up to the page size. -void UnmapShm(void *address, size_t size); - -} // namespace command_buffer -} // namespace o3d - -#endif // O3D_COMMAND_BUFFER_COMMON_CROSS_RPC_H_ diff --git a/o3d/command_buffer/common/cross/rpc_fake.cc b/o3d/command_buffer/common/cross/rpc_fake.cc deleted file mode 100644 index 028c753..0000000 --- a/o3d/command_buffer/common/cross/rpc_fake.cc +++ /dev/null @@ -1,226 +0,0 @@ -/* - * Copyright 2009, Google Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - - -#include <windows.h> -#include "command_buffer/common/cross/rpc_fake.h" - -namespace o3d { -namespace command_buffer { - -// Create the queue, initializing the synchronization structures: a mutex for -// the queue itself, and an event to signal the consumers. -RPCQueue::RPCQueue() { - event_ = ::CreateEvent(NULL, FALSE, FALSE, NULL); - ::InitializeCriticalSection(&mutex_); -} - -RPCQueue::~RPCQueue() { - ::DeleteCriticalSection(&mutex_); - ::CloseHandle(event_); -} - -// Adds a message into the queue. Signal waiting threads that a new message is -// available. -void RPCQueue::AddMessage(const RPCMessage &call) { - ::EnterCriticalSection(&mutex_); - queue_.push(call); - ::SetEvent(event_); - ::LeaveCriticalSection(&mutex_); -} - -// Checks whether the queue is empty. -bool RPCQueue::IsEmpty() { - ::EnterCriticalSection(&mutex_); - bool result = queue_.empty(); - ::LeaveCriticalSection(&mutex_); - return result; -} - -// Gets a message, waiting for one if the queue is empty. -void RPCQueue::GetMessage(RPCMessage *message) { - ::EnterCriticalSection(&mutex_); - while (queue_.empty()) { - ::LeaveCriticalSection(&mutex_); - ::WaitForSingleObject(event_, INFINITE); - ::EnterCriticalSection(&mutex_); - } - *message = queue_.front(); - queue_.pop(); - ::LeaveCriticalSection(&mutex_); -} - -// Tries to gets a message, returning immediately if the queue is empty. -bool RPCQueue::TryGetMessage(RPCMessage *message) { - ::EnterCriticalSection(&mutex_); - bool result = !queue_.empty(); - if (result) { - *message = queue_.front(); - queue_.pop(); - } - ::LeaveCriticalSection(&mutex_); - return result; -} - -// Creates the RPC server. The RPC server uses 2 RPC Queues, one for "incoming" -// calls (in_queue_), and one for "outgoing" return values (out_queue_). -RPCServer::RPCServer(RPCImplInterface * impl) { - sender_.reset(new Sender(&in_queue_, &out_queue_)); - processor_.reset(new Processor(&in_queue_, &out_queue_, impl)); -} - -RPCServer::~RPCServer() {} - -// Allocates the data for a message, if needed. Initializes the RPCMessage -// structure. -void RPCServer::AllocMessage(int message_id, - const void *data, - size_t size, - RPCHandle const *handles, - size_t handle_count, - RPCMessage *message) { - message->message_id = message_id; - message->size = size; - message->handle_count = handle_count; - if (data) { - message->data = malloc(size); - memcpy(message->data, data, size); - } else { - DCHECK(size == 0); - message->data = NULL; - } - if (handles) { - DCHECK(handle_count > 0); - message->handles = new RPCHandle[handle_count]; - for (unsigned int i = 0; i < handle_count; ++i) - message->handles[i] = handles[i]; - } else { - DCHECK(handle_count == 0); - message->handles = NULL; - } -} - -// Destroys the message data if needed. -void RPCServer::DestroyMessage(RPCMessage *message) { - if (message->data) free(message->data); - if (message->handles) delete [] message->handles; -} - -// Processes one message, getting one from the incoming queue (blocking), -// dispatching it to the implementation (if not the "poisoned" message), and -// adding the return value to the outgoing queue. -bool RPCServer::Processor::ProcessMessage() { - RPCMessage input; - in_queue_->GetMessage(&input); - RPCImplInterface::ReturnValue result = 0; - bool continue_processing = true; - if (input.message_id == POISONED_MESSAGE_ID) { - continue_processing = false; - } else { - result = impl_->DoCall(input.message_id, input.data, input.size, - input.handles, input.handle_count); - } - DestroyMessage(&input); - - RPCMessage output; - AllocMessage(RESPONSE_ID, &result, sizeof(result), NULL, 0, &output); - out_queue_->AddMessage(output); - return continue_processing; -} - -// Checks if the incoming queue is empty. -bool RPCServer::Processor::HasMessage() { - return !in_queue_->IsEmpty(); -} - -// Processes all messages until the server is killed. -void RPCServer::MessageLoop() { - do {} while (processor_->ProcessMessage()); -} - -// Sends a "poisoned" call to the server thread, making it exit the processing -// loop. -void RPCServer::KillServer() { - sender_->SendCall(POISONED_MESSAGE_ID, NULL, 0, NULL, 0); -} - -// Sends a call to the server thread. This puts a message into the "incoming" -// queue, and waits for the return message on the "outgoing" queue. -RPCImplInterface::ReturnValue RPCServer::Sender::SendCall( - int message_id, - const void * data, - size_t size, - RPCHandle const *handles, - size_t handle_count) { - RPCMessage input; - AllocMessage(message_id, data, size, handles, handle_count, &input); - in_queue_->AddMessage(input); - - RPCMessage output; - out_queue_->GetMessage(&output); - DCHECK(output.message_id == RESPONSE_ID); - DCHECK(output.size == sizeof(RPCImplInterface::ReturnValue)); - RPCImplInterface::ReturnValue result = - *(reinterpret_cast<RPCImplInterface::ReturnValue *>(output.data)); - DestroyMessage(&output); - return result; -} - -class RPCSendProxy : public RPCSendInterface { - public: - explicit RPCSendProxy(RPCSendInterface *interface) : interface_(interface) {} - virtual ~RPCSendProxy() {} - virtual RPCImplInterface::ReturnValue SendCall(int message_id, - const void * data, - size_t size, - RPCHandle const *handles, - size_t handle_count) { - return interface_->SendCall(message_id, data, size, handles, handle_count); - } - private: - RPCSendInterface *interface_; -}; - -// Create a proxy so that it can be managed as a separate object, to have the -// same semantics as the IMC implementation. -RPCSendInterface *MakeSendInterface(RPCSocketHandle handle) { - return new RPCSendProxy(handle->GetSendInterface()); -} - -void *MapShm(RPCShmHandle handle, size_t size) { - return (size <= handle->size) ? return handle->address : NULL; -} - -void UnmapShm(void * address, size_t size) { -} - -} // namespace command_buffer -} // namespace o3d diff --git a/o3d/command_buffer/common/cross/rpc_fake.h b/o3d/command_buffer/common/cross/rpc_fake.h deleted file mode 100644 index 11eb258..0000000 --- a/o3d/command_buffer/common/cross/rpc_fake.h +++ /dev/null @@ -1,206 +0,0 @@ -/* - * Copyright 2009, Google Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - - -// This file defines classes faking the NativeClient RPC mechanism. This is -// intended as a temporary replacement of NativeClient until it is ready. It -// assumes the various clients and services run in separate threads of the same -// process. - -#ifndef O3D_COMMAND_BUFFER_COMMON_CROSS_RPC_FAKE_H_ -#define O3D_COMMAND_BUFFER_COMMON_CROSS_RPC_FAKE_H_ - -#include <windows.h> -#include <queue> -#include "base/scoped_ptr.h" -#include "core/cross/types.h" -#include "command_buffer/common/cross/rpc.h" - -namespace o3d { -namespace command_buffer { - -typedef CRITICAL_SECTION Mutex; -typedef HANDLE Event; - -// Struct describing a RPC message, as a message ID and a data payload. -// It "owns" the data pointer. -struct RPCMessage { - int message_id; - size_t size; - void *data; - RPCHandle *handles; - size_t handle_count; -}; - -// Implementation of a (thread-safe) RPC message queue (FIFO). It allows simply -// to enqueue and dequeue messages, in a blocking or non-blocking fashion. -class RPCQueue { - public: - RPCQueue(); - ~RPCQueue(); - - // Adds a message into the back of the queue. - // Parameters: - // message: the message to enqueue. Ownership of the message data is taken - // by the queue. - void AddMessage(const RPCMessage &message); - - // Tests whether or not the queue is empty. - // Returns: - // true if the queue is empty. - bool IsEmpty(); - - // Gets a message from the front of the queue. This call blocks until a - // message is available in the queue. - // Parameters: - // message: a pointer to a RPCMessage structure receiving the message. - // That structure takes ownership of the message data. - void GetMessage(RPCMessage *message); - - // Try to get a message from the front of the queue, if any. This call will - // not block if the queue is empty. - // Parameters: - // message: a pointer to a RPCMessage structure receiving the message, if - // any. That structure takes ownership of the message data. If no - // message is available, that structure is unchanged. - // Returns: - // true if a message was available. - bool TryGetMessage(RPCMessage *message); - - private: - std::queue<RPCMessage> queue_; - Mutex mutex_; - Event event_; - - DISALLOW_COPY_AND_ASSIGN(RPCQueue); -}; - -// Implements a fake RPC server interface. This class is intended to be used -// across different threads (it is thread safe): -// - one server thread, that processes messages (using MessageLoop() or -// ProcessMessage()), to execute the RPC calls. -// - one or several client threads, that can send RPC calls to it. -// -// One of the client threads can "kill" the server so that it exits its -// processing loop. -class RPCServer { - public: - explicit RPCServer(RPCImplInterface *impl); - ~RPCServer(); - - // Server thread functions - - // Processes all messages, until the server is killed. - void MessageLoop(); - RPCProcessInterface *GetProcessInterface() { return processor_.get(); } - - // client thread functions - RPCSendInterface *GetSendInterface() { return sender_.get(); } - - // Kills the server thread, making it exit its processing loop. This call - // will block until the server has finished processing all the previous - // messages. - void KillServer(); - - private: - static void AllocMessage(int message_id, - const void * data, - size_t size, - RPCHandle const *handles, - size_t handle_count, - RPCMessage *message); - static void DestroyMessage(RPCMessage *message); - - class Sender : public RPCSendInterface { - public: - Sender(RPCQueue *in_queue, RPCQueue *out_queue) - : in_queue_(in_queue), - out_queue_(out_queue) {} - // Sends a call to the server thread. This call will be dispatched by the - // server thread to the RPC implementation. This call will block until the - // call is processed and the return value is sent back. - // Parameters: - // message_id: the RPC message ID. - // data: the RPC message payload. - // size: the size of the data. - // handles: an array of RPC handles to transmit - // handle_count: the number of RPC handles in the array - // Returns: - // the return value of the RPC call. - virtual RPCImplInterface::ReturnValue SendCall(int message_id, - const void * data, - size_t size, - RPCHandle const *handles, - size_t handle_count); - private: - RPCQueue *in_queue_; - RPCQueue *out_queue_; - DISALLOW_COPY_AND_ASSIGN(Sender); - }; - - class Processor : public RPCProcessInterface { - public: - Processor(RPCQueue *in_queue, RPCQueue *out_queue, RPCImplInterface *impl) - : in_queue_(in_queue), - out_queue_(out_queue), - impl_(impl) {} - virtual ~Processor() {} - // Processes one message, blocking if necessary until a message is available - // or the server is killed. This will dispatch the received message to the - // RPC implementation, and send back a response message with the return - // value to the client. - // Returns: - // false if the server was killed. - virtual bool ProcessMessage(); - - // Checks whether a message is available for processing - allowing to test - // if ProcessMessage will block. - // Returns: - // true if a message is available. - virtual bool HasMessage(); - private: - RPCQueue *in_queue_; - RPCQueue *out_queue_; - RPCImplInterface *impl_; - DISALLOW_COPY_AND_ASSIGN(Processor); - }; - - RPCQueue in_queue_; - RPCQueue out_queue_; - scoped_ptr<Sender> sender_; - scoped_ptr<Processor> processor_; - DISALLOW_COPY_AND_ASSIGN(RPCServer); -}; - -} // namespace command_buffer -} // namespace o3d - -#endif // O3D_COMMAND_BUFFER_COMMON_CROSS_RPC_FAKE_H_ diff --git a/o3d/command_buffer/common/cross/rpc_imc.cc b/o3d/command_buffer/common/cross/rpc_imc.cc deleted file mode 100644 index 391f139..0000000 --- a/o3d/command_buffer/common/cross/rpc_imc.cc +++ /dev/null @@ -1,231 +0,0 @@ -/* - * Copyright 2009, Google Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - - -#include <algorithm> -#include "command_buffer/common/cross/logging.h" -#include "command_buffer/common/cross/rpc_imc.h" -#include "native_client/src/shared/imc/nacl_htp.h" - -namespace o3d { -namespace command_buffer { - -int NaclSendData(nacl::HtpHandle channel, - const void *data, - size_t size, - int flags) { - nacl::HtpHeader msg; - nacl::IOVec vec; - vec.base = const_cast<void *>(data); - vec.length = size; - msg.iov = &vec; - msg.iov_length = 1; - msg.handles = NULL; - msg.handle_count = 0; - msg.flags = 0; - return nacl::SendDatagram(channel, &msg, flags); -} - -int NaclSendHandles(nacl::HtpHandle channel, - const nacl::HtpHandle *handles, - size_t count, - int flags) { - nacl::HtpHeader msg; - msg.iov = NULL; - msg.iov_length = 0; - msg.handles = const_cast<nacl::HtpHandle *>(handles); - msg.handle_count = count; - msg.flags = 0; - return nacl::SendDatagram(channel, &msg, flags); -} - -int NaclReceiveData(nacl::HtpHandle channel, - void *data, - size_t size, - int flags) { - nacl::HtpHeader msg; - nacl::IOVec vec[1]; - vec[0].base = data; - vec[0].length = size; - msg.iov = vec; - msg.iov_length = 1; - msg.handles = NULL; - msg.handle_count = 0; - msg.flags = 0; - int result = nacl::ReceiveDatagram(channel, &msg, flags); - return result; -} - -int NaclReceiveHandles(nacl::HtpHandle channel, - nacl::HtpHandle *handles, - size_t count, - int flags) { - nacl::HtpHeader msg; - msg.iov = NULL; - msg.iov_length = 0; - msg.handles = handles; - msg.handle_count = count; - msg.flags = 0; - return nacl::ReceiveDatagram(channel, &msg, flags); -} - -struct RPCMessageHeader { - int message_id; - size_t size; - size_t handle_count; -}; - -RPCImplInterface::ReturnValue IMCSender::SendCall( - int message_id, - const void * data, - size_t size, - RPCHandle const *handles, - size_t handle_count) { - // Send 3 messages: first contains message id, and data size, second - // contains data and third handles. - // The reason for that is to have the size first so that we can allocate the - // data buffer on the receiving side. - RPCMessageHeader msg = {message_id, size, handle_count}; - int result = NaclSendData(handle_, &msg, sizeof(msg), 0); - DCHECK_NE(-1, result); - if (size > 0) { - result = NaclSendData(handle_, data, size, 0); - DCHECK_NE(-1, result); - } - if (handle_count > 0) { - result = NaclSendHandles(handle_, handles, handle_count, 0); - DCHECK_NE(-1, result); - } - - RPCImplInterface::ReturnValue ret; - result = NaclReceiveData(handle_, &ret, sizeof(ret), 0); - DCHECK_EQ(sizeof(ret), static_cast<size_t>(result)); - return ret; -} - -bool IMCMessageProcessor::GetMessageIDSize(bool wait) { - if (has_message_) return true; - RPCMessageHeader msg = {0}; - int result = NaclReceiveData(handle_, &msg, sizeof(msg), - wait ? 0 : nacl::kDontWait); - if (result != sizeof(msg)) { - if (result >=0 || wait || !nacl::WouldBlock()) return false; - has_message_ = false; - } else { - incoming_message_id_ = msg.message_id; - incoming_message_size_ = msg.size; - incoming_message_handles_ = msg.handle_count; - has_message_ = true; - } - return true; -} - -bool IMCMessageProcessor::ProcessMessage() { - if (!GetMessageIDSize(true)) return false; - if (incoming_message_size_ > 0) { - if (incoming_message_size_ > data_size_) { - data_size_ = incoming_message_size_; - data_.reset(new char[incoming_message_size_]); - } - int result = NaclReceiveData(handle_, data_.get(), incoming_message_size_, - 0); - if (result < 0) return false; - } - if (incoming_message_handles_ > 0) { - if (incoming_message_handles_ > handle_count_) { - handle_count_ = incoming_message_handles_; - handles_.reset(new nacl::HtpHandle[incoming_message_handles_]); - } - int result = NaclReceiveHandles(handle_, handles_.get(), - incoming_message_handles_, 0); - if (result < 0) return false; - } - has_message_ = false; - RPCImplInterface::ReturnValue retval = 0; - bool continue_processing = true; - if (incoming_message_id_ == POISONED_MESSAGE_ID) { - continue_processing = false; - } else { - retval = impl_->DoCall(incoming_message_id_, data_.get(), - incoming_message_size_, handles_.get(), - incoming_message_handles_); - // Note: the handles that got received are a "copy" of the original handle, - // so they need to be closed eventually. It's hard to impose an - // "ownership" policy onto the RPCImplInterface, because it makes the API - // very clunky. Currently, we only pass handles across for - // RegisterSharedMemory, and so we can safely close the handle immediately - // (the memory will stay mapped). - // TODO: Fix this. Possibly using a global registration mechanism - // and ref-counting would make it work nicely. - for (unsigned int i = 0; i < incoming_message_handles_; ++i) { - nacl::Close(handles_[i]); - } - } - - int result = NaclSendData(handle_, &retval, sizeof(retval), 0); - if (result < 0) return false; - return continue_processing; -} - -bool IMCMessageProcessor::HasMessage() { - GetMessageIDSize(false); - return has_message_; -} - -RPCSendInterface *MakeSendInterface(RPCSocketHandle handle) { - return new IMCSender(handle); -} - -RPCShmHandle CreateShm(size_t size) { - size = (size + nacl::kMapPageSize - 1) & ~(nacl::kMapPageSize - 1); - nacl::Handle nacl_handle = nacl::CreateMemoryObject(size); - return nacl_handle == nacl::kInvalidHandle ? kRPCInvalidHandle : - nacl::CreateShmDesc(nacl_handle, size); -} - -void DestroyShm(RPCShmHandle handle) { - nacl::Close(handle); -} - -void *MapShm(RPCShmHandle handle, size_t size) { - size = (size + nacl::kMapPageSize - 1) & ~(nacl::kMapPageSize - 1); - void *address = nacl::Map(NULL, size, nacl::kProtRead | nacl::kProtWrite, - nacl::kMapShared, handle, 0); - return address == nacl::kMapFailed ? NULL : address; -} - -void UnmapShm(void *address, size_t size) { - size = (size + nacl::kMapPageSize - 1) & ~(nacl::kMapPageSize - 1); - nacl::Unmap(address, size); -} - -} // namespace command_buffer -} // namespace o3d diff --git a/o3d/command_buffer/common/cross/rpc_imc.h b/o3d/command_buffer/common/cross/rpc_imc.h deleted file mode 100644 index 097fb1c..0000000 --- a/o3d/command_buffer/common/cross/rpc_imc.h +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Copyright 2009, Google Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - - -#ifndef O3D_COMMAND_BUFFER_COMMON_CROSS_RPC_IMC_H_ -#define O3D_COMMAND_BUFFER_COMMON_CROSS_RPC_IMC_H_ - -#include "native_client/src/shared/imc/nacl_imc.h" -#include "base/scoped_ptr.h" -#include "command_buffer/common/cross/rpc.h" - -namespace o3d { -namespace command_buffer { - -class IMCSender : public RPCSendInterface { - public: - explicit IMCSender(nacl::HtpHandle handle) : handle_(handle) {} - virtual ~IMCSender() {} - // Sends a call to the server thread. This call will be dispatched by the - // server thread to the RPC implementation. This call will block until the - // call is processed and the return value is sent back. - // Parameters: - // message_id: the RPC message ID. - // data: the RPC message payload. - // size: the size of the data. - // handles: an array of RPC handles to transmit - // handle_count: the number of RPC handles in the array - // Returns: - // the return value of the RPC call. - virtual RPCImplInterface::ReturnValue SendCall(int message_id, - const void * data, - size_t size, - RPCHandle const *handles, - size_t handle_count); - private: - nacl::HtpHandle handle_; -}; - -class IMCMessageProcessor : public RPCProcessInterface { - public: - IMCMessageProcessor(nacl::HtpHandle handle, RPCImplInterface *impl) - : handle_(handle), - impl_(impl), - has_message_(false), - incoming_message_id_(0), - incoming_message_size_(0), - incoming_message_handles_(0), - data_size_(0), - handle_count_(0) {} - virtual ~IMCMessageProcessor() {} - // Processes one message, blocking if necessary until a message is available - // or the server is killed. This will dispatch the received message to the - // RPC implementation, and send back a response message with the return - // value to the client. - // Returns: - // false if the server was killed. - virtual bool ProcessMessage(); - - // Checks whether a message is available for processing - allowing to test if - // ProcessMessage will block. - // Returns: - // true if a message is available. - virtual bool HasMessage(); - private: - bool GetMessageIDSize(bool wait); - nacl::HtpHandle handle_; - RPCImplInterface *impl_; - bool has_message_; - int incoming_message_id_; - size_t incoming_message_size_; - size_t incoming_message_handles_; - size_t data_size_; - scoped_array<char> data_; - size_t handle_count_; - scoped_array<RPCHandle> handles_; -}; - -} // namespace command_buffer -} // namespace o3d - -#endif // O3D_COMMAND_BUFFER_COMMON_CROSS_RPC_IMC_H_ diff --git a/o3d/command_buffer/samples/build.scons b/o3d/command_buffer/samples/build.scons deleted file mode 100644 index 414ee95..0000000 --- a/o3d/command_buffer/samples/build.scons +++ /dev/null @@ -1,55 +0,0 @@ -# Copyright 2009, Google Inc. -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: -# -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following disclaimer -# in the documentation and/or other materials provided with the -# distribution. -# * Neither the name of Google Inc. nor the names of its -# contributors may be used to endorse or promote products derived from -# this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - -Import('env') - -env.Append( - LIBS = [ - 'o3dCmdBuf_client', - 'o3dCmdBuf_common', - 'google_nacl_npruntime', - ] + env['NACL_HTP_LIBS'], - LIBPATH = ['$NACL_LIB_DIR'], - CPPPATH = ['$NPAPI_DIR', '$NPAPI_DIR/include'], -) - -if env['TARGET_PLATFORM'] == 'NACL': - env.Append(LIBS=['m', 'pthread'], - CCFLAGS=['-O3', '-mfpmath=sse', '-msse', '-fomit-frame-pointer']) - -BUBBLE_INPUTS = [ - 'bubble/bubble_module.cc', - 'bubble/cubemap.cc', - 'bubble/iridescence_texture.cc', - 'bubble/perlin_noise.cc', -] -bubble_sample = env.Program('bubble_module.nexe', BUBBLE_INPUTS) -artifacts = [bubble_sample, 'bubble/bubble.html'] -env.Replicate('$ARTIFACTS_DIR/samples/bubble', artifacts) diff --git a/o3d/command_buffer/service/build.scons b/o3d/command_buffer/service/build.scons deleted file mode 100644 index 3a0a199..0000000 --- a/o3d/command_buffer/service/build.scons +++ /dev/null @@ -1,146 +0,0 @@ -# Copyright 2009, Google Inc. -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: -# -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following disclaimer -# in the documentation and/or other materials provided with the -# distribution. -# * Neither the name of Google Inc. nor the names of its -# contributors may be used to endorse or promote products derived from -# this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - -Import('env') - -INPUTS = [ - 'cross/buffer_rpc.cc', - 'cross/cmd_parser.cc', - 'cross/cmd_buffer_engine.cc', - 'cross/effect_utils.cc', - 'cross/gapi_decoder.cc', - 'cross/resource.cc', - 'cross/texture_utils.cc', -] - -# Add a precompiled header declaration to the Windows environment. -if env['TARGET_PLATFORM'] == 'WINDOWS': - env.Append( - CCFLAGS = [ - '/Ylcommand_buffer', - '/FIcommand_buffer/service/cross/precompile.h', - ], - ) - pch, pch_obj = env.PCH('cross/precompile.cc') - env['PCH'] = pch - env['PCHSTOP'] = 'command_buffer/service/cross/precompile.h' -else: - pch_obj = 'cross/precompile.cc' - env.Append(CCFLAGS = [['-include', - 'command_buffer/service/cross/precompile.h']]) - -# Build the big tests -BIG_TEST_SERVER = [ - 'cross/big_test.cc', -] - -# Add some flags and libraries to the build environment for the unit tests -env.Append( - LIBPATH = [ - '$NACL_LIB_DIR', - ], - LIBS = [ - 'o3dCmdBuf_service', - 'o3dCmdBuf_common', - 'o3d_base', - ] + env['NACL_HTP_LIBS'] + env['ICU_LIBS'], -) - -if env['TARGET_PLATFORM'] == 'WINDOWS': - if 'CB_SERVICE_D3D9' in env['CPPDEFINES']: - env.Append(CCFLAGS = [], - LIBS = [# System libs. - 'd3d9', - # TODO: remove link-time dependency on d3dx9, using - # dynamic loading instead. - 'd3dx9', - 'dxerr', - 'shell32'], - LINKFLAGS=['/SUBSYSTEM:CONSOLE']) - INPUTS += ['win/d3d9/effect_d3d9.cc', - 'win/d3d9/gapi_d3d9.cc', - 'win/d3d9/geometry_d3d9.cc', - 'win/d3d9/render_surface_d3d9.cc', - 'win/d3d9/sampler_d3d9.cc', - 'win/d3d9/states_d3d9.cc', - 'win/d3d9/texture_d3d9.cc'] - elif 'CB_SERVICE_GL' in env['CPPDEFINES']: - env.Append(CCFLAGS = [], - LIBS = ['OpenGL32', 'glew32', 'cg', 'cgGL'], - LIBPATH = ['$CG_DIR/lib', '$GLEW_DIR/lib'], - CPPPATH = ['$CG_DIR/include', '$GLEW_DIR/include'], - LINKFLAGS=['/SUBSYSTEM:CONSOLE']) - INPUTS += ['cross/gl/effect_gl.cc', - 'cross/gl/gapi_gl.cc', - 'cross/gl/geometry_gl.cc', - 'cross/gl/render_surface_gl.cc', - 'cross/gl/sampler_gl.cc', - 'cross/gl/states_gl.cc', - 'cross/gl/texture_gl.cc'] - BIG_TEST_SERVER += ['win/big_test_main.cc'] -elif env['TARGET_PLATFORM'] == 'LINUX': - env.Append(LIBS = ['GL', 'GLEW', 'Cg', 'CgGL'], - CPPPATH = ['$CG_DIR/include']) - INPUTS += ['cross/gl/effect_gl.cc', - 'cross/gl/gapi_gl.cc', - 'cross/gl/geometry_gl.cc', - 'cross/gl/render_surface_gl.cc', - 'cross/gl/sampler_gl.cc', - 'cross/gl/states_gl.cc', - 'cross/gl/texture_gl.cc', - 'linux/x_utils.cc'] - BIG_TEST_SERVER += ['linux/big_test_main.cc'] - -# Create a target library from the sources called 'o3dCmdBuf' -o3dcmdbuf_lib = env.ComponentLibrary('o3dCmdBuf_service', INPUTS) - -# TODO: why can't these be ComponentTestProgram? - -# Create a target executable program called 'o3dCmdBuf_bigtest_server' from the -# list of big test server files. -big_test_server = env.Program('o3dCmdBuf_bigtest_server', BIG_TEST_SERVER) - -# Copy the resulting executable to the Artifacts directory. -env.Replicate('$ARTIFACTS_DIR', big_test_server) - -plugin_env = env.Clone(); -plugin_env.Append(CPPPATH = ['$NPAPI_DIR/include']) - -PLUGIN_INPUTS = [ - 'cross/plugin.cc', - plugin_env.SharedObject( - 'npn_api', - '$NIXYSA_DIR/static_glue/npapi/npn_api.cc'), -] -if env['TARGET_PLATFORM'] == 'WINDOWS': - PLUGIN_INPUTS += ['win/plugin.def', - env.RES('win/plugin.rc')] -plugin = plugin_env.SharedLibrary('npo3d_cb_plugin', PLUGIN_INPUTS) -plugin_env.Replicate('$ARTIFACTS_DIR', plugin) diff --git a/o3d/command_buffer/service/cross/big_test.cc b/o3d/command_buffer/service/cross/big_test.cc deleted file mode 100644 index 0c92508..0000000 --- a/o3d/command_buffer/service/cross/big_test.cc +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Copyright 2009, Google Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - - -// This file contains a "big" test of the whole command buffer service, making -// sure all the pieces fit together. -// -// Currently this checks that the RPC mechanism properly forwards call to the -// service thread. - -#include <build/build_config.h> -#include "command_buffer/common/cross/rpc_imc.h" -#include "command_buffer/service/cross/big_test_helpers.h" -#include "command_buffer/service/cross/buffer_rpc.h" -#include "command_buffer/service/cross/cmd_buffer_engine.h" -#include "command_buffer/service/cross/gapi_decoder.h" -#include "third_party/native_client/googleclient/native_client/src/trusted/desc/nrd_all_modules.h" - -namespace o3d { -namespace command_buffer { - -nacl::SocketAddress g_address = { "command-buffer" }; - -// Main function. Creates a socket, and waits for an incoming connection on it. -// Then run the engine main loop. -void BigTest() { - NaClNrdAllModulesInit(); - GAPIDecoder decoder(g_gapi); - CommandBufferEngine engine(&decoder); - decoder.set_engine(&engine); - nacl::Handle server_socket = nacl::BoundSocket(&g_address); - nacl::Handle handles[1]; - nacl::MessageHeader msg; - msg.iov = NULL; - msg.iov_length = 0; - msg.handles = handles; - msg.handle_count = 1; - int r = nacl::ReceiveDatagram(server_socket, &msg, 0); - DCHECK_NE(r, -1); - nacl::Close(server_socket); - - nacl::HtpHandle htp_handle = nacl::CreateImcDesc(handles[0]); - IMCMessageProcessor processor(htp_handle, engine.rpc_impl()); - engine.set_process_interface(&processor); - IMCSender sender(htp_handle); - engine.set_client_rpc(&sender); - - bool result = g_gapi->Initialize(); - DCHECK(result); - - bool running = true; - while (running) { - running = ProcessSystemMessages(); - if (!running) break; - // DoWork() will block if there is nothing to be done, meaning we are only - // going to handle message after commands are sent. It should happen at - // least once a frame, so it's "good enough". - // TODO: figure out a way to wait on the socket OR messages with - // MsgWaitForMultipleObjects. Asynchronous ("overlapped") read on the - // socket may let us do that on windows. - running = engine.DoWork(); - } - g_gapi->Destroy(); - nacl::Close(htp_handle); - NaClNrdAllModulesFini(); -} - -} // namespace command_buffer -} // namespace o3d - -#ifdef OS_WIN -int big_test_main(int argc, wchar_t **argv) { -#else -int big_test_main(int argc, char **argv) { -#endif - o3d::command_buffer::BigTest(); - return 0; -} diff --git a/o3d/command_buffer/service/cross/buffer_rpc.cc b/o3d/command_buffer/service/cross/buffer_rpc.cc deleted file mode 100644 index 668cc32..0000000 --- a/o3d/command_buffer/service/cross/buffer_rpc.cc +++ /dev/null @@ -1,136 +0,0 @@ -/* - * Copyright 2009, Google Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - - -// This file has the implementation of the Command Buffer Synchronous API RPC -// glue. - -#include "command_buffer/common/cross/logging.h" -#include "command_buffer/service/cross/buffer_rpc.h" - -namespace o3d { -namespace command_buffer { - -// Implements the dispatch function, deciding on which function to call based -// on the message ID, taking the arguments trivially serialized in the data -// payload. -BufferRPCImpl::ReturnValue BufferRPCImpl::DoCall(int message_id, - const void *data, - size_t size, - RPCHandle const *handles, - size_t handle_count) { - switch (message_id) { - case INIT_CONNECTION: { - DCHECK_EQ(0u, size); - DCHECK_EQ(0u, handle_count); - handler_->InitConnection(); - return 0; - } - case CLOSE_CONNECTION: - DCHECK_EQ(0u, size); - DCHECK_EQ(0u, handle_count); - handler_->CloseConnection(); - return 0; - case REGISTER_SHARED_MEMORY: { - DCHECK_EQ(sizeof(size_t), size); // NOLINT - DCHECK_EQ(1u, handle_count); - RPCShmHandle buffer = static_cast<RPCShmHandle>(handles[0]); - return handler_->RegisterSharedMemory(buffer, - *static_cast<const size_t *>(data)); - } - case UNREGISTER_SHARED_MEMORY: { - DCHECK_EQ(sizeof(unsigned int), size); // NOLINT - DCHECK_EQ(0u, handle_count); - unsigned int shm_id = *(static_cast<const unsigned int *>(data)); - handler_->UnregisterSharedMemory(shm_id); - return 0; - } - case SET_COMMAND_BUFFER: { - DCHECK_EQ(sizeof(SetCommandBufferStruct), size); - DCHECK_EQ(0u, handle_count); - const SetCommandBufferStruct *params = - static_cast<const SetCommandBufferStruct *>(data); - handler_->SetCommandBuffer(params->shm_id, - params->offset, - params->size, - params->start_get); - return 0; - } - case PUT: { - DCHECK_EQ(sizeof(CommandBufferOffset), size); - DCHECK_EQ(0u, handle_count); - CommandBufferOffset offset = - *(static_cast<const CommandBufferOffset *>(data)); - handler_->Put(offset); - return 0; - } - case GET: - DCHECK_EQ(0u, size); - DCHECK_EQ(0u, handle_count); - return handler_->Get(); - case GET_TOKEN: - DCHECK_EQ(0u, size); - DCHECK_EQ(0u, handle_count); - return handler_->GetToken(); - case WAIT_GET_CHANGES: { - DCHECK_EQ(sizeof(CommandBufferOffset), size); - DCHECK_EQ(0u, handle_count); - CommandBufferOffset current_value = - *(static_cast<const CommandBufferOffset *>(data)); - return handler_->WaitGetChanges(current_value); - } - case SIGNAL_GET_CHANGES: { - DCHECK_EQ(sizeof(SignalGetChangesStruct), size); - DCHECK_EQ(0u, handle_count); - const SignalGetChangesStruct *params = - static_cast<const SignalGetChangesStruct *>(data); - handler_->SignalGetChanges(params->current_value, - params->rpc_message_id); - return 0; - } - case GET_STATUS: { - DCHECK_EQ(0u, size); - DCHECK_EQ(0u, handle_count); - return handler_->GetStatus(); - } - case GET_PARSE_ERROR: { - DCHECK_EQ(0u, size); - DCHECK_EQ(0u, handle_count); - return handler_->GetParseError(); - } - default: - LOG(FATAL) << "unsupported RPC"; - return 0; - } -} - -} // namespace command_buffer -} // namespace o3d diff --git a/o3d/command_buffer/service/cross/buffer_rpc.h b/o3d/command_buffer/service/cross/buffer_rpc.h deleted file mode 100644 index 952e9b8..0000000 --- a/o3d/command_buffer/service/cross/buffer_rpc.h +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright 2009, Google Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - - -// This file defines the RPC glue for the Command Buffer Synchronous API, -// service side: an implementation of a RPC service, forwarding calls to -// a Command Buffer API implemention (RPC -> API). - -#ifndef O3D_COMMAND_BUFFER_SERVICE_CROSS_BUFFER_RPC_H_ -#define O3D_COMMAND_BUFFER_SERVICE_CROSS_BUFFER_RPC_H_ - -#include "command_buffer/common/cross/buffer_sync_api.h" -#include "command_buffer/common/cross/rpc.h" - -namespace o3d { -namespace command_buffer { - -// RPC service implementation, implementing the Command Buffer Synchronous API -// RPC glue. This class is temporary, and will be replaced when the -// NativeClient RPC mechanism will be available. -// -// The API exposed through the RPC mechanism maps 1-to-1 to BufferSyncInterface, -// trivially serializing arguments. -class BufferRPCImpl: public RPCImplInterface { - public: - explicit BufferRPCImpl(BufferSyncInterface *handler) : handler_(handler) {} - virtual ~BufferRPCImpl() {} - - enum MessageId { - INIT_CONNECTION = RESPONSE_ID + 1, - CLOSE_CONNECTION, - REGISTER_SHARED_MEMORY, - UNREGISTER_SHARED_MEMORY, - SET_COMMAND_BUFFER, - PUT, - GET, - GET_TOKEN, - WAIT_GET_CHANGES, - SIGNAL_GET_CHANGES, - GET_STATUS, - GET_PARSE_ERROR, - }; - - // Structure describing the arguments for the SET_COMMAND_BUFFER RPC. - struct SetCommandBufferStruct { - unsigned int shm_id; - ptrdiff_t offset; - size_t size; - CommandBufferOffset start_get; - }; - - // Structure describing the arguments for the SIGNAL_GET_CHANGES RPC. - struct SignalGetChangesStruct { - CommandBufferOffset current_value; - int rpc_message_id; - }; - - // Implements the DoCall interface, interpreting the message with the - // parameters, and passing the calls with arguments to the handler. - virtual ReturnValue DoCall(int message_id, - const void * data, - size_t size, - RPCHandle const *handles, - size_t handle_count); - - private: - BufferSyncInterface *handler_; -}; - -} // namespace command_buffer -} // namespace o3d - -#endif // O3D_COMMAND_BUFFER_SERVICE_CROSS_BUFFER_RPC_H_ diff --git a/o3d/command_buffer/service/cross/buffer_rpc_test.cc b/o3d/command_buffer/service/cross/buffer_rpc_test.cc deleted file mode 100644 index 721b20b..0000000 --- a/o3d/command_buffer/service/cross/buffer_rpc_test.cc +++ /dev/null @@ -1,173 +0,0 @@ -/* - * Copyright 2009, Google Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - - -// Tests for the Command Buffer RPC glue. - -#include "tests/common/win/testing_common.h" -#include "command_buffer/common/cross/mocks.h" -#include "command_buffer/service/cross/buffer_rpc.h" -#include "command_buffer/service/cross/mocks.h" - -namespace o3d { -namespace command_buffer { - -using testing::Return; - -// Test fixture for BufferRPCImpl test. Creates a BufferSyncMock and a -// BufferRPCImpl that uses it. -class BufferRPCImplTest : public testing::Test { - protected: - virtual void SetUp() { - buffer_sync_mock_.reset(new BufferSyncMock); - buffer_rpc_impl_.reset(new BufferRPCImpl(buffer_sync_mock_.get())); - } - virtual void TearDown() {} - - BufferSyncMock &buffer_sync_mock() { return *buffer_sync_mock_.get(); } - BufferRPCImpl *buffer_rpc_impl() { return buffer_rpc_impl_.get(); } - private: - scoped_ptr<BufferSyncMock> buffer_sync_mock_; - scoped_ptr<BufferRPCImpl> buffer_rpc_impl_; -}; - -// Checks that the INIT_CONNECTION RPC is properly parsed. -TEST_F(BufferRPCImplTest, TestInitConnection) { - EXPECT_CALL(buffer_sync_mock(), InitConnection()); - buffer_rpc_impl()->DoCall(BufferRPCImpl::INIT_CONNECTION, NULL, 0, NULL, 0); -} - -// Checks that the CLOSE_CONNECTION RPC is properly parsed. -TEST_F(BufferRPCImplTest, TestCloseConnection) { - EXPECT_CALL(buffer_sync_mock(), CloseConnection()); - buffer_rpc_impl()->DoCall(BufferRPCImpl::CLOSE_CONNECTION, NULL, 0, NULL, 0); -} - -// Checks that the REGISTER_SHARED_MEMORY RPC is properly parsed and that the -// return value is properly forwarded. -TEST_F(BufferRPCImplTest, TestRegisterSharedMemory) { - RPCShmHandle shm = reinterpret_cast<RPCShmHandle>(456); - size_t size = 789; - EXPECT_CALL(buffer_sync_mock(), RegisterSharedMemory(shm, size)) - .WillOnce(Return(1234)); - RPCHandle handles[1] = {shm}; - EXPECT_EQ(1234u, buffer_rpc_impl()->DoCall( - BufferRPCImpl::REGISTER_SHARED_MEMORY, &size, sizeof(size), handles, 1)); -} - -// Checks that the UNREGISTER_SHARED_MEMORY RPC is properly parsed. -TEST_F(BufferRPCImplTest, TestUnregisterSharedMemory) { - unsigned int shm_id = 385; - EXPECT_CALL(buffer_sync_mock(), UnregisterSharedMemory(shm_id)); - buffer_rpc_impl()->DoCall(BufferRPCImpl::UNREGISTER_SHARED_MEMORY, &shm_id, - sizeof(shm_id), NULL, 0); -} - -// Checks that the SET_COMMAND_BUFFER RPC is properly parsed. -TEST_F(BufferRPCImplTest, TestSetCommandBuffer) { - EXPECT_CALL(buffer_sync_mock(), SetCommandBuffer(93, 7878, 3434, 5151)); - BufferRPCImpl::SetCommandBufferStruct param; - param.shm_id = 93; - param.offset = 7878; - param.size = 3434; - param.start_get = 5151; - buffer_rpc_impl()->DoCall(BufferRPCImpl::SET_COMMAND_BUFFER, ¶m, - sizeof(param), NULL, 0); -} - -// Checks that the PUT RPC is properly parsed. -TEST_F(BufferRPCImplTest, TestPut) { - CommandBufferOffset offset = 8765; - EXPECT_CALL(buffer_sync_mock(), Put(offset)); - buffer_rpc_impl()->DoCall(BufferRPCImpl::PUT, &offset, sizeof(offset), NULL, - 0); -} - -// Checks that the GET RPC is properly parsed and that the return value is -// properly forwarded. -TEST_F(BufferRPCImplTest, TestGet) { - EXPECT_CALL(buffer_sync_mock(), Get()).WillOnce(Return(9375)); - EXPECT_EQ(9375u, buffer_rpc_impl()->DoCall(BufferRPCImpl::GET, NULL, 0, NULL, - 0)); -} - -// Checks that the GET_TOKEN RPC is properly parsed and that the return value is -// properly forwarded. -TEST_F(BufferRPCImplTest, TestGetToken) { - EXPECT_CALL(buffer_sync_mock(), GetToken()).WillOnce(Return(1618)); - EXPECT_EQ(1618u, buffer_rpc_impl()->DoCall(BufferRPCImpl::GET_TOKEN, NULL, 0, - NULL, 0)); -} - -// Checks that the WAIT_GET_CHANGES RPC is properly parsed and that the return -// value is properly forwarded. -TEST_F(BufferRPCImplTest, TestWaitGetChanges) { - CommandBufferOffset value = 339; - EXPECT_CALL(buffer_sync_mock(), WaitGetChanges(value)) - .WillOnce(Return(16180)); - EXPECT_EQ(16180u, buffer_rpc_impl()->DoCall(BufferRPCImpl::WAIT_GET_CHANGES, - &value, sizeof(value), NULL, 0)); -} - -// Checks that the SIGNAL_GET_CHANGES RPC is properly parsed. -TEST_F(BufferRPCImplTest, TestSignalGetChanges) { - EXPECT_CALL(buffer_sync_mock(), SignalGetChanges(34, 21)); - BufferRPCImpl::SignalGetChangesStruct param; - param.current_value = 34; - param.rpc_message_id = 21; - buffer_rpc_impl()->DoCall(BufferRPCImpl::SIGNAL_GET_CHANGES, ¶m, - sizeof(param), NULL, 0); -} - -// Checks that the GET_STATUS RPC is properly parsed and that the return value -// is properly forwarded. -TEST_F(BufferRPCImplTest, TestGetStatus) { - EXPECT_CALL(buffer_sync_mock(), GetStatus()) - .WillOnce(Return(BufferSyncInterface::kParseError)); - EXPECT_EQ(static_cast<BufferRPCImpl::ReturnValue>( - BufferSyncInterface::kParseError), - buffer_rpc_impl()->DoCall(BufferRPCImpl::GET_STATUS, NULL, 0, NULL, - 0)); -} - -// Checks that the GET_STATUS RPC is properly parsed and that the return value -// is properly forwarded. -TEST_F(BufferRPCImplTest, TestGetParseError) { - EXPECT_CALL(buffer_sync_mock(), GetParseError()) - .WillOnce(Return(BufferSyncInterface::kParseOutOfBounds)); - EXPECT_EQ(static_cast<BufferRPCImpl::ReturnValue>( - BufferSyncInterface::kParseOutOfBounds), - buffer_rpc_impl()->DoCall(BufferRPCImpl::GET_PARSE_ERROR, NULL, 0, - NULL, 0)); -} - -} // namespace command_buffer -} // namespace o3d diff --git a/o3d/command_buffer/service/cross/cmd_buffer_engine.cc b/o3d/command_buffer/service/cross/cmd_buffer_engine.cc deleted file mode 100644 index 9637206..0000000 --- a/o3d/command_buffer/service/cross/cmd_buffer_engine.cc +++ /dev/null @@ -1,293 +0,0 @@ -/* - * Copyright 2009, Google Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - - -// This file contains the implementation of the command buffer engine. - -#include "command_buffer/service/cross/buffer_rpc.h" -#include "command_buffer/service/cross/cmd_buffer_engine.h" - -namespace o3d { -namespace command_buffer { - -// Creates a RPC implementation using 'this' as the handler, and a RPC server -// for it. -CommandBufferEngine::CommandBufferEngine(AsyncAPIInterface *handler) - : buffer_rpc_impl_(), - process_interface_(NULL), - parser_(), - handler_(handler), - client_rpc_(NULL), - token_(0), - status_(kNotConnected), - signal_change_(false), - signal_rpc_message_id_(0), - parse_error_(kParseNoError) { - buffer_rpc_impl_.reset(new BufferRPCImpl(this)); -} - -CommandBufferEngine::~CommandBufferEngine() {} - -// Inits the connection. Registers the client RPC service. -void CommandBufferEngine::InitConnection() { - status_ = kNoBuffer; -} - -// Closes the connection. Executes all remaining commands. -void CommandBufferEngine::CloseConnection() { - FinishParsing(); - status_ = kNotConnected; - parser_.reset(NULL); -} - -// Adds the shared memory buffer somewhere into the list, return the index in -// the list as the handle. Either find a hole in the list, or add it at the -// end. We don't want to invalidate exiting indices. -unsigned int CommandBufferEngine::RegisterSharedMemory( - RPCShmHandle handle, - size_t size) { - void *address = MapShm(handle, size); - if (!address) return kInvalidSharedMemoryId; - MemoryMapping mapping = {address, size}; - for (unsigned int i = 0; i < shared_memory_buffers_.size(); ++i) { - if (shared_memory_buffers_[i].address == NULL) { - shared_memory_buffers_[i] = mapping; - return i; - } - } - shared_memory_buffers_.push_back(mapping); - return static_cast<unsigned int>(shared_memory_buffers_.size() - 1); -} - -// Sets the list entry for the shared memory buffer to NULL. Don't erase() the -// entry, We don't want to invalidate exiting indices. -void CommandBufferEngine::UnregisterSharedMemory(unsigned int shm_id) { - if ((shm_id >= shared_memory_buffers_.size()) || - !shared_memory_buffers_[shm_id].size) { - LOG(ERROR) << "Trying to unregister a non-registered shared memory"; - return; - } - MemoryMapping &mapping = shared_memory_buffers_[shm_id]; - UnmapShm(mapping.address, mapping.size); - mapping.address = NULL; - mapping.size = 0; -} - -// Sets the command buffer. Executes all remaining commands in the old buffer -// (if any) and creates a new command parser. -void CommandBufferEngine::SetCommandBuffer(unsigned int shm_id, - ptrdiff_t offset, - size_t size, - CommandBufferOffset start_get) { - if ((shm_id >= shared_memory_buffers_.size()) || - !shared_memory_buffers_[shm_id].size) { - LOG(ERROR) << "Trying to set the command buffer from a non-registered " - << "shared memory"; - return; - } - if (status_ == kNotConnected) return; - FinishParsing(); - parser_.reset(new CommandParser(shared_memory_buffers_[shm_id].address, - shared_memory_buffers_[shm_id].size, offset, - size, start_get, handler_)); - status_ = kParsing; - parse_error_ = kParseNoError; -} - -// Changes the put value. -void CommandBufferEngine::Put(CommandBufferOffset offset) { - if (parser_.get()) { - parser_->set_put(offset); - } -} - -// Retrieves the get value. This returns kInvalidCommandBufferOffset -// if there is no current parser. -CommandBufferOffset CommandBufferEngine::Get() { - if (parser_.get()) { - return parser_->get(); - } else { - return kInvalidCommandBufferOffset; - } -} - -// Retrieves the current token value. -unsigned int CommandBufferEngine::GetToken() { - return token_; -} - -// Executes commands until get is different from the value passed -// in. It will return immediately if the get value is already -// different, or if the engine is not in the kParsing status, or if -// the buffer is empty. It will return kInvalidCommandBufferOffset -// if there is no current buffer. -CommandBufferOffset CommandBufferEngine::WaitGetChanges( - CommandBufferOffset current_value) { - if (parser_.get()) { - while (status_ == kParsing && - parser_->get() == current_value && - !parser_->IsEmpty()) { - ProcessOneCommand(); - } - return parser_->get(); - } else { - return kInvalidCommandBufferOffset; - } -} - -// Signals the client when get gets different from the value passed in. If get -// is already different, or if the engine is not in the kParsing status, that -// will happen immediately, otherwise it will happen when commands get -// executed, moving the get pointer. -void CommandBufferEngine::SignalGetChanges(CommandBufferOffset current_value, - int rpc_message_id) { - if (status_ != kParsing || parser_->get() != current_value) { - DoSignalChangedGet(rpc_message_id); - } else { - signal_change_ = true; - signal_rpc_message_id_ = rpc_message_id; - } -} - -// Gets the memory address from the list entry. -void *CommandBufferEngine::GetSharedMemoryAddress(unsigned int shm_id) { - if ((shm_id >= shared_memory_buffers_.size()) || - !shared_memory_buffers_[shm_id].size) { - LOG(ERROR) << "Trying to get the address of a non-registered shared memory"; - return NULL; - } - return shared_memory_buffers_[shm_id].address; -} - -// Gets the memory size from the list entry. -size_t CommandBufferEngine::GetSharedMemorySize(unsigned int shm_id) { - if ((shm_id >= shared_memory_buffers_.size()) || - !shared_memory_buffers_[shm_id].size) { - LOG(ERROR) << "Trying to get the size of a non-registered shared memory"; - return 0; - } - return shared_memory_buffers_[shm_id].size; -} - -// Gets the status. -BufferSyncInterface::ParserStatus CommandBufferEngine::GetStatus() { - return status_; -} - -// Gets the current parse error, reset it to kParseNoError. -BufferSyncInterface::ParseError CommandBufferEngine::GetParseError() { - ParseError error = parse_error_; - parse_error_ = kParseNoError; - return error; -} - -// Finishes parsing, executing all the commands until the buffer is empty, or a -// parsing error occurs. -void CommandBufferEngine::FinishParsing() { - // terminates current parsing, that is, execute all the commands - // NOTE: status_ == kParsing implies parser_ != NULL - while (status_ == kParsing && !parser_->IsEmpty()) { - ProcessOneCommand(); - } -} - -// Processes one command from the command buffer. This must only be called when -// in the kParsing status. -// This will update the status_ and the parse_error_ fields if an error occurs. -void CommandBufferEngine::ProcessOneCommand() { - DCHECK_EQ(kParsing, status_); - DCHECK(parser_.get()); - ParseError result = parser_->ProcessCommand(); - switch (result) { - case kParseNoError: - break; - case kParseOutOfBounds: - case kParseInvalidSize: - status_ = kParseError; - // Always override the error, to properly signal the stopping condition. - parse_error_ = result; - break; - case kParseInvalidArguments: - case kParseUnknownCommand: - // Only set the error if it is not set already. - if (parse_error_ == kParseNoError) { - parse_error_ = result; - } - break; - } - // get has changed, signal the client if needed. - if (signal_change_) { - DoSignalChangedGet(signal_rpc_message_id_); - signal_change_ = false; - } -} - -// Executes the main loop. While there are commands in the buffer, processes -// them one by one, checking for RPC messages between each of them (executing -// all of them). If the buffer is empty, block until a RPC message comes. -void CommandBufferEngine::DoMainLoop() { - while (DoWork()) { } - // Clean up if needed: execute all pending commands, then close the - // connection. - if (status_ != kNotConnected) CloseConnection(); -} - -bool CommandBufferEngine::HasWork() { - return (status_ == kParsing && !parser_->IsEmpty()) || - process_interface_->HasMessage(); -} - -bool CommandBufferEngine::DoWork() { - if (status_ == kParsing && !parser_->IsEmpty()) { - bool running = true; - // process as many messages as available but do not block. - while (process_interface_->HasMessage()) { - running = process_interface_->ProcessMessage(); - } - if (running) ProcessOneCommand(); - return running; - } else { - // call ProcessMessage, always blocking. We have nothing else to do. - return process_interface_->ProcessMessage(); - } -} - -// Signals that get has changed, sending a RPC message back to the client. It -// will send kInvalidCommandBufferOffset if there is no current buffer. -void CommandBufferEngine::DoSignalChangedGet(int rpc_message_id) { - DCHECK(client_rpc_); - CommandBufferOffset get = parser_.get() ? parser_->get() : - kInvalidCommandBufferOffset; - client_rpc_->SendCall(rpc_message_id, &get, sizeof(get), NULL, 0); -} - -} // namespace command_buffer -} // namespace o3d diff --git a/o3d/command_buffer/service/cross/cmd_buffer_engine.h b/o3d/command_buffer/service/cross/cmd_buffer_engine.h index 479c267..20b3143 100644 --- a/o3d/command_buffer/service/cross/cmd_buffer_engine.h +++ b/o3d/command_buffer/service/cross/cmd_buffer_engine.h @@ -36,202 +36,34 @@ #ifndef O3D_COMMAND_BUFFER_SERVICE_CROSS_CMD_BUFFER_ENGINE_H_ #define O3D_COMMAND_BUFFER_SERVICE_CROSS_CMD_BUFFER_ENGINE_H_ -#include <vector> -#include "base/scoped_ptr.h" -#include "command_buffer/common/cross/buffer_sync_api.h" -#include "command_buffer/service/cross/cmd_parser.h" +#include "base/basictypes.h" namespace o3d { namespace command_buffer { -class BufferRPCImpl; - -class CommandBufferUpcallInterface { +class CommandBufferEngine { public: - CommandBufferUpcallInterface() { + CommandBufferEngine() { } - virtual ~CommandBufferUpcallInterface() { + virtual ~CommandBufferEngine() { } // Gets the base address of a registered shared memory buffer. // Parameters: // shm_id: the identifier for the shared memory buffer. - virtual void *GetSharedMemoryAddress(unsigned int shm_id) = 0; + virtual void *GetSharedMemoryAddress(int32 shm_id) = 0; // Gets the size of a registered shared memory buffer. // Parameters: // shm_id: the identifier for the shared memory buffer. - virtual size_t GetSharedMemorySize(unsigned int shm_id) = 0; + virtual size_t GetSharedMemorySize(int32 shm_id) = 0; // Sets the token value. - virtual void set_token(unsigned int token) = 0; + virtual void set_token(int32 token) = 0; private: - DISALLOW_COPY_AND_ASSIGN(CommandBufferUpcallInterface); -}; - -class CommandBufferEngine : public BufferSyncInterface, - public CommandBufferUpcallInterface { - public: - explicit CommandBufferEngine(AsyncAPIInterface *handler); - virtual ~CommandBufferEngine(); - - // Initializes the connection with the client. - virtual void InitConnection(); - - // Closes the connection with the client. - virtual void CloseConnection(); - - // Registers a shared memory buffer. While a buffer is registered, it can be - // accessed by the service, including the underlying asynchronous API, - // through a single identifier. - // Parameters: - // buffer: the shared memory buffer handle. - // Returns: - // an identifier for the shared memory. - virtual unsigned int RegisterSharedMemory(RPCShmHandle buffer, size_t size); - - // Unregisters a shared memory buffer. - // Parameters: - // shm_id: the identifier for the shared memory buffer. - virtual void UnregisterSharedMemory(unsigned int shm_id); - - // Initializes the command buffer. - // Parameters: - // buffer: the memory buffer descriptor in which the command buffer - // resides. - // offset: the offset of the command buffer, relative to the memory - // buffer. - // size: the size of the command buffer. - // start_get: the inital value for the Get pointer, relative to the - // command buffer, where the parser will start interpreting - // commands. Put is also initialized to that value. - virtual void SetCommandBuffer(unsigned int shm_id, - ptrdiff_t offset, - size_t size, - CommandBufferOffset start_get); - - // Sets the value of the Put pointer. - // Parameters: - // offset: the new value of the Put pointer, as an offset into the command - // buffer. - virtual void Put(CommandBufferOffset offset); - - // Gets the value of the Get pointer. - // Returns: - // the current value of the Get pointer, as an offset into the command - // buffer. - virtual CommandBufferOffset Get(); - - // Gets the current token value. - // Returns: - // the current token value. - virtual unsigned int GetToken(); - - // Waits until Get changes from the currently known value. - // Parameters: - // current_value: the currently known value. This call will block until - // Get is different from that value (returning immediately - // if it is already different). - // Returns: - // the current (changed) value of Get. - virtual CommandBufferOffset WaitGetChanges( - CommandBufferOffset current_value); - - // Asks the service to signal the client when Get changes from the currently - // known value. This is a non-blocking version of WaitGetChanges. - // Parameters: - // current_value: the currently known value of Get. - // rpc_message_id: the RPC message ID to call on the client when Get is - // different from current_value. That RPC is called - // immediately if Get is already different from - // current_value. - virtual void SignalGetChanges(CommandBufferOffset current_value, - int rpc_message_id); - - // Gets the status of the service. - // Returns: - // The status of the service. - virtual ParserStatus GetStatus(); - - // Gets the current parse error. The current parse error is set when the - // service is in the PARSE_ERROR status. It may also be set while in the - // kParsing state, if a recoverable error (like PARSE_UNKNOWN_METHOD) was - // encountered. Getting the error resets it to kParseNoError. - // Returns: - // The current parse error. - virtual ParseError GetParseError(); - - // Gets the base address of a registered shared memory buffer. - // Parameters: - // shm_id: the identifier for the shared memory buffer. - void *GetSharedMemoryAddress(unsigned int shm_id); - - // Gets the size of a registered shared memory buffer. - // Parameters: - // shm_id: the identifier for the shared memory buffer. - size_t GetSharedMemorySize(unsigned int shm_id); - - // Executes the main loop: parse commands and execute RPC calls until the - // server is killed. - void DoMainLoop(); - - // Returns whether or not the engine has work to do (process synchronous or - // asynchronous commands). - bool HasWork(); - - // Does some work (process synchronous or asynchronous commands). It will not - // block if HasWork() returns true. - // Returns: - // true if the engine should keep running, false if it has been sent a - // command to terminate. - bool DoWork(); - - // Gets the RPC server. - BufferRPCImpl *rpc_impl() const { return buffer_rpc_impl_.get(); } - - // Sets the RPC processing interface. - void set_process_interface(RPCProcessInterface *iface) { - process_interface_ = iface; - } - - // Sets the RPC processing interface. - void set_client_rpc(RPCSendInterface *iface) { - client_rpc_ = iface; - } - - // Gets the command parser. - CommandParser *parser() const { return parser_.get(); } - - // Sets the token value. - void set_token(unsigned int token) { token_ = token; } - private: - - // Processes one command from the command buffer. - void ProcessOneCommand(); - - // Sends the signal that get has changed to the client. - void DoSignalChangedGet(int rpc_message_id); - - // Finish parsing and executing all the commands in the buffer. - void FinishParsing(); - - scoped_ptr<BufferRPCImpl> buffer_rpc_impl_; - RPCProcessInterface *process_interface_; - scoped_ptr<CommandParser> parser_; - AsyncAPIInterface *handler_; - RPCSendInterface *client_rpc_; - unsigned int token_; - ParserStatus status_; - bool signal_change_; - int signal_rpc_message_id_; - ParseError parse_error_; - struct MemoryMapping { - void *address; - size_t size; - }; - std::vector<MemoryMapping> shared_memory_buffers_; + DISALLOW_COPY_AND_ASSIGN(CommandBufferEngine); }; } // namespace command_buffer diff --git a/o3d/command_buffer/service/cross/cmd_buffer_engine_test.cc b/o3d/command_buffer/service/cross/cmd_buffer_engine_test.cc deleted file mode 100644 index 7f32b3a..0000000 --- a/o3d/command_buffer/service/cross/cmd_buffer_engine_test.cc +++ /dev/null @@ -1,625 +0,0 @@ -/* - * Copyright 2009, Google Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - - -// Tests for the Command Buffer Engine. - -#include "tests/common/win/testing_common.h" -#include "command_buffer/service/cross/cmd_buffer_engine.h" -#include "command_buffer/service/cross/mocks.h" - -namespace o3d { -namespace command_buffer { - -using testing::AnyNumber; -using testing::Return; -using testing::Mock; -using testing::Truly; -using testing::Sequence; -using testing::_; - -// Test fixture for CommandBufferEngine test - Creates a CommandBufferEngine, -// using a mock AsyncAPIInterface. -class CommandBufferEngineTest : public testing::Test { - protected: - CommandBufferEngineTest() - : shm_(kRPCInvalidHandle), - shm_id_(BufferSyncInterface::kInvalidSharedMemoryId) {} - - virtual void SetUp() { - api_mock_.reset(new AsyncAPIMock); - engine_.reset(new CommandBufferEngine(api_mock_.get())); - process_mock_.reset(new RPCProcessMock()); - engine_->set_process_interface(process_mock_.get()); - } - virtual void TearDown() { - } - - // Creates a shared memory buffer for the command buffer, and pass it to the - // engine. - CommandBufferEntry *InitCommandBuffer(size_t entries, unsigned int start) { - CHECK(shm_ == kRPCInvalidHandle); - CHECK(shm_id_ == BufferSyncInterface::kInvalidSharedMemoryId); - const size_t kShmSize = entries * sizeof(CommandBufferEntry); // NOLINT - shm_ = CreateShm(kShmSize); - EXPECT_NE(kRPCInvalidHandle, shm_); - if (kRPCInvalidHandle == shm_) return NULL; - shm_id_ = engine()->RegisterSharedMemory(shm_, kShmSize); - EXPECT_NE(BufferSyncInterface::kInvalidSharedMemoryId, shm_id_); - if (shm_id_ == BufferSyncInterface::kInvalidSharedMemoryId) { - DestroyShm(shm_); - shm_ = kRPCInvalidHandle; - return NULL; - } - engine()->SetCommandBuffer(shm_id_, 0, kShmSize, start); - return static_cast<CommandBufferEntry *>( - engine()->GetSharedMemoryAddress(shm_id_)); - } - - // Destroys the command buffer. - void DestroyCommandBuffer() { - engine()->UnregisterSharedMemory(shm_id_); - shm_id_ = BufferSyncInterface::kInvalidSharedMemoryId; - DestroyShm(shm_); - shm_ = kRPCInvalidHandle; - } - - // Adds a command to the buffer, while adding it as an expected call on the - // API mock. - unsigned int AddCommandWithExpect(CommandBufferEntry *buffer, - BufferSyncInterface::ParseError _return, - unsigned int command, - unsigned int arg_count, - CommandBufferEntry *args) { - unsigned int put = 0; - CommandHeader header; - header.size = arg_count + 1; - header.command = command; - buffer[put++].value_header = header; - for (unsigned int i = 0; i < arg_count; ++i) { - buffer[put++].value_uint32 = args[i].value_uint32; - } - EXPECT_CALL(*api_mock(), DoCommand(command, arg_count, - Truly(AsyncAPIMock::IsArgs(arg_count, args)))) - .InSequence(sequence_) - .WillOnce(Return(_return)); - return put; - } - - CommandBufferEngine *engine() { return engine_.get(); } - RPCProcessMock *process_mock() { return process_mock_.get(); } - AsyncAPIMock *api_mock() { return api_mock_.get(); } - private: - scoped_ptr<AsyncAPIMock> api_mock_; - scoped_ptr<CommandBufferEngine> engine_; - scoped_ptr<RPCProcessMock> process_mock_; - // handles for the command buffer. - RPCShmHandle shm_; - unsigned int shm_id_; - Sequence sequence_; -}; - -// Tests the initialization/termination sequence, checking that it sets the -// engine in the correct states. -TEST_F(CommandBufferEngineTest, TestInitialization) { - // Check initial state - EXPECT_TRUE(engine()->rpc_impl() != NULL); - EXPECT_TRUE(engine()->parser() == NULL); - EXPECT_EQ(BufferSyncInterface::kNotConnected, engine()->GetStatus()); - EXPECT_EQ(BufferSyncInterface::kParseNoError, engine()->GetParseError()); - EXPECT_EQ(kInvalidCommandBufferOffset, engine()->Get()); - EXPECT_EQ(0u, engine()->GetToken()); - - engine()->InitConnection(); - EXPECT_EQ(BufferSyncInterface::kNoBuffer, engine()->GetStatus()); - EXPECT_EQ(BufferSyncInterface::kParseNoError, engine()->GetParseError()); - EXPECT_EQ(kInvalidCommandBufferOffset, engine()->Get()); - - CommandBufferEntry *entries = InitCommandBuffer(25, 5); - ASSERT_TRUE(entries != NULL); - - EXPECT_EQ(BufferSyncInterface::kParsing, engine()->GetStatus()); - EXPECT_EQ(BufferSyncInterface::kParseNoError, engine()->GetParseError()); - EXPECT_EQ(5u, engine()->Get()); - EXPECT_TRUE(engine()->parser() != NULL); - - engine()->set_token(5678); - EXPECT_EQ(5678u, engine()->GetToken()); - - engine()->CloseConnection(); - DestroyCommandBuffer(); - - EXPECT_EQ(BufferSyncInterface::kNotConnected, engine()->GetStatus()); - EXPECT_EQ(BufferSyncInterface::kParseNoError, engine()->GetParseError()); - EXPECT_EQ(kInvalidCommandBufferOffset, engine()->Get()); - EXPECT_TRUE(engine()->parser() == NULL); -} - -// Checks that shared memory registration works. -TEST_F(CommandBufferEngineTest, TestSharedMemoryRegistration) { - // Create and register a first shared memory buffer. - const size_t kShmSize1 = 10; - RPCShmHandle shm1 = CreateShm(kShmSize1); - ASSERT_NE(kRPCInvalidHandle, shm1); - unsigned int shm_id1 = engine()->RegisterSharedMemory(shm1, kShmSize1); - EXPECT_NE(BufferSyncInterface::kInvalidSharedMemoryId, shm_id1); - EXPECT_TRUE(engine()->GetSharedMemoryAddress(shm_id1) != NULL); - EXPECT_EQ(kShmSize1, engine()->GetSharedMemorySize(shm_id1)); - - // Create and register a second shared memory buffer, check that it has a - // different memory location than the first one. - const size_t kShmSize2 = 25; - RPCShmHandle shm2 = CreateShm(kShmSize2); - ASSERT_NE(kRPCInvalidHandle, shm2); - unsigned int shm_id2 = engine()->RegisterSharedMemory(shm2, kShmSize2); - EXPECT_NE(BufferSyncInterface::kInvalidSharedMemoryId, shm_id2); - EXPECT_TRUE(engine()->GetSharedMemoryAddress(shm_id2) != NULL); - EXPECT_EQ(kShmSize2, engine()->GetSharedMemorySize(shm_id2)); - EXPECT_NE(shm_id1, shm_id2); - EXPECT_NE(engine()->GetSharedMemoryAddress(shm_id1), - engine()->GetSharedMemoryAddress(shm_id2)); - - // Create and register a third shared memory buffer, check that it has a - // different memory location than the first and second ones. - const size_t kShmSize3 = 33; - RPCShmHandle shm3 = CreateShm(kShmSize3); - ASSERT_NE(kRPCInvalidHandle, shm3); - unsigned int shm_id3 = engine()->RegisterSharedMemory(shm3, kShmSize3); - EXPECT_NE(BufferSyncInterface::kInvalidSharedMemoryId, shm_id3); - EXPECT_TRUE(engine()->GetSharedMemoryAddress(shm_id3) != NULL); - EXPECT_EQ(kShmSize3, engine()->GetSharedMemorySize(shm_id3)); - EXPECT_NE(shm_id1, shm_id3); - EXPECT_NE(shm_id2, shm_id3); - EXPECT_NE(engine()->GetSharedMemoryAddress(shm_id1), - engine()->GetSharedMemoryAddress(shm_id3)); - EXPECT_NE(engine()->GetSharedMemoryAddress(shm_id2), - engine()->GetSharedMemoryAddress(shm_id3)); - - engine()->UnregisterSharedMemory(shm_id1); - EXPECT_EQ(NULL, engine()->GetSharedMemoryAddress(shm_id1)); - EXPECT_EQ(0UL, engine()->GetSharedMemorySize(shm_id1)); - DestroyShm(shm1); - - engine()->UnregisterSharedMemory(shm_id2); - EXPECT_EQ(NULL, engine()->GetSharedMemoryAddress(shm_id2)); - EXPECT_EQ(0UL, engine()->GetSharedMemorySize(shm_id2)); - DestroyShm(shm2); - - engine()->UnregisterSharedMemory(shm_id3); - EXPECT_EQ(NULL, engine()->GetSharedMemoryAddress(shm_id2)); - EXPECT_EQ(0UL, engine()->GetSharedMemorySize(shm_id2)); - DestroyShm(shm3); -} - -// Checks that commands in the buffer are properly executed, and that the -// status/error stay valid. -TEST_F(CommandBufferEngineTest, TestCommandProcessing) { - engine()->InitConnection(); - CommandBufferEntry *entries = InitCommandBuffer(10, 0); - ASSERT_TRUE(entries != NULL); - - CommandBufferOffset get = engine()->Get(); - CommandBufferOffset put = get; - - // Create a command buffer with 3 commands - put += AddCommandWithExpect(entries + put, - BufferSyncInterface::kParseNoError, - 0, - 0, - NULL); - - CommandBufferEntry args1[2]; - args1[0].value_uint32 = 3; - args1[1].value_float = 4.f; - put += AddCommandWithExpect(entries + put, - BufferSyncInterface::kParseNoError, - 1, - 2, - args1); - - CommandBufferEntry args2[2]; - args2[0].value_uint32 = 5; - args2[1].value_float = 6.f; - put += AddCommandWithExpect(entries + put, - BufferSyncInterface::kParseNoError, - 2, - 2, - args2); - - engine()->Put(put); - while (get != put) { - // Check that the parsing progresses, and that no error occurs. - CommandBufferOffset new_get = engine()->WaitGetChanges(get); - EXPECT_NE(get, new_get); - ASSERT_EQ(BufferSyncInterface::kParsing, engine()->GetStatus()); - EXPECT_EQ(BufferSyncInterface::kParseNoError, engine()->GetParseError()); - EXPECT_EQ(new_get, engine()->Get()); - get = new_get; - } - // Check that the commands did happen. - Mock::VerifyAndClearExpectations(api_mock()); - - engine()->CloseConnection(); - DestroyCommandBuffer(); -} - -// Checks that commands in the buffer are properly executed when wrapping the -// buffer, and that the status/error stay valid. -TEST_F(CommandBufferEngineTest, TestCommandWrapping) { - engine()->InitConnection(); - CommandBufferEntry *entries = InitCommandBuffer(10, 6); - ASSERT_TRUE(entries != NULL); - - CommandBufferOffset get = engine()->Get(); - CommandBufferOffset put = get; - - // Create a command buffer with 3 commands - put += AddCommandWithExpect(entries + put, - BufferSyncInterface::kParseNoError, - 0, - 0, - NULL); - - CommandBufferEntry args1[2]; - args1[0].value_uint32 = 3; - args1[1].value_float = 4.f; - put += AddCommandWithExpect(entries + put, - BufferSyncInterface::kParseNoError, - 1, - 2, - args1); - DCHECK_EQ(10u, put); - put = 0; - - CommandBufferEntry args2[2]; - args2[0].value_uint32 = 5; - args2[1].value_float = 6.f; - put += AddCommandWithExpect(entries + put, - BufferSyncInterface::kParseNoError, - 2, - 2, - args2); - - engine()->Put(put); - while (get != put) { - // Check that the parsing progresses, and that no error occurs. - CommandBufferOffset new_get = engine()->WaitGetChanges(get); - EXPECT_NE(get, new_get); - ASSERT_EQ(BufferSyncInterface::kParsing, engine()->GetStatus()); - EXPECT_EQ(BufferSyncInterface::kParseNoError, engine()->GetParseError()); - EXPECT_EQ(new_get, engine()->Get()); - get = new_get; - } - // Check that the commands did happen. - Mock::VerifyAndClearExpectations(api_mock()); - - engine()->CloseConnection(); - DestroyCommandBuffer(); -} - -// Checks that commands in the buffer are properly executed when we change the -// buffer, and when we close the connection. -TEST_F(CommandBufferEngineTest, TestSetBufferAndClose) { - engine()->InitConnection(); - CommandBufferEntry *entries = InitCommandBuffer(10, 0); - ASSERT_TRUE(entries != NULL); - - CommandBufferOffset get = engine()->Get(); - CommandBufferOffset put = get; - - // Create a command buffer with 3 commands - put += AddCommandWithExpect(entries + put, - BufferSyncInterface::kParseNoError, - 0, - 0, - NULL); - - CommandBufferEntry args1[2]; - args1[0].value_uint32 = 3; - args1[1].value_float = 4.f; - put += AddCommandWithExpect(entries + put, - BufferSyncInterface::kParseNoError, - 1, - 2, - args1); - - CommandBufferEntry args2[2]; - args2[0].value_uint32 = 5; - args2[1].value_float = 6.f; - put += AddCommandWithExpect(entries + put, - BufferSyncInterface::kParseNoError, - 2, - 2, - args2); - - engine()->Put(put); - - // Setup a new buffer. - const size_t kShmSize = 10 * sizeof(CommandBufferEntry); // NOLINT - RPCShmHandle shm = CreateShm(kShmSize); - ASSERT_NE(kRPCInvalidHandle, shm); - unsigned int shm_id = engine()->RegisterSharedMemory(shm, kShmSize); - ASSERT_NE(BufferSyncInterface::kInvalidSharedMemoryId, shm_id); - CommandBufferEntry *entries2 = static_cast<CommandBufferEntry *>( - engine()->GetSharedMemoryAddress(shm_id)); - engine()->SetCommandBuffer(shm_id, 0, kShmSize, 0); - EXPECT_EQ(BufferSyncInterface::kParsing, engine()->GetStatus()); - EXPECT_EQ(BufferSyncInterface::kParseNoError, engine()->GetParseError()); - EXPECT_EQ(0u, engine()->Get()); - - // Destroy the old command buffer. - DestroyCommandBuffer(); - - get = engine()->Get(); - put = get; - put += AddCommandWithExpect(entries2 + put, - BufferSyncInterface::kParseNoError, - 1, - 2, - args1); - - engine()->Put(put); - - engine()->CloseConnection(); - // Check that all the commands did happen. - Mock::VerifyAndClearExpectations(api_mock()); - - engine()->UnregisterSharedMemory(shm_id); - DestroyShm(shm); -} - -// Checks that commands in the buffer are properly executed, even if they -// generate a recoverable error. Check that the error status is properly set, -// and reset when queried. -TEST_F(CommandBufferEngineTest, TestRecoverableError) { - engine()->InitConnection(); - CommandBufferEntry *entries = InitCommandBuffer(10, 0); - ASSERT_TRUE(entries != NULL); - - CommandBufferOffset get = engine()->Get(); - CommandBufferOffset put = get; - - // Create a command buffer with 3 commands, 2 of them generating errors - put += AddCommandWithExpect(entries + put, - BufferSyncInterface::kParseNoError, - 0, - 0, - NULL); - - CommandBufferEntry args1[2]; - args1[0].value_uint32 = 3; - args1[1].value_float = 4.f; - put += AddCommandWithExpect(entries + put, - BufferSyncInterface::kParseInvalidArguments, - 1, - 2, - args1); - - CommandBufferEntry args2[2]; - args2[0].value_uint32 = 5; - args2[1].value_float = 6.f; - put += AddCommandWithExpect(entries + put, - BufferSyncInterface::kParseUnknownCommand, - 2, - 2, - args2); - - engine()->Put(put); - while (get != put) { - // Check that the parsing progresses, and that no error occurs. - CommandBufferOffset new_get = engine()->WaitGetChanges(get); - EXPECT_NE(get, new_get); - ASSERT_EQ(BufferSyncInterface::kParsing, engine()->GetStatus()); - EXPECT_EQ(new_get, engine()->Get()); - get = new_get; - } - // Check that the commands did happen. - Mock::VerifyAndClearExpectations(api_mock()); - - // Check that the error status was set to the first error. - EXPECT_EQ(BufferSyncInterface::kParseInvalidArguments, - engine()->GetParseError()); - // Check that the error status was reset after the query. - EXPECT_EQ(BufferSyncInterface::kParseNoError, engine()->GetParseError()); - - engine()->CloseConnection(); - DestroyCommandBuffer(); -} - -// Checks that commands in the buffer are properly executed up to the point -// where a parsing error happened. Check that at that point the status and -// error are properly set. -TEST_F(CommandBufferEngineTest, TestNonRecoverableError) { - engine()->InitConnection(); - // Create a buffer with 6 entries, starting at entry 1, but allocate enough - // memory so that we can add commands that cross over the limit. - const size_t kShmSize = 10 * sizeof(CommandBufferEntry); // NOLINT - RPCShmHandle shm = CreateShm(kShmSize); - ASSERT_NE(kRPCInvalidHandle, shm); - unsigned int shm_id = engine()->RegisterSharedMemory(shm, kShmSize); - ASSERT_NE(BufferSyncInterface::kInvalidSharedMemoryId, shm_id); - CommandBufferEntry *entries = static_cast<CommandBufferEntry *>( - engine()->GetSharedMemoryAddress(shm_id)); - ASSERT_TRUE(entries != NULL); - engine()->SetCommandBuffer(shm_id, 0, 6 * sizeof(CommandBufferEntry), 1); - - CommandBufferOffset get = engine()->Get(); - CommandBufferOffset put = get; - - // Create a command buffer with 3 commands, the last one overlapping the end - // of the buffer. - put += AddCommandWithExpect(entries + put, - BufferSyncInterface::kParseNoError, - 0, - 0, - NULL); - - CommandBufferEntry args1[2]; - args1[0].value_uint32 = 3; - args1[1].value_float = 4.f; - put += AddCommandWithExpect(entries + put, - BufferSyncInterface::kParseNoError, - 1, - 2, - args1); - - CommandHeader header; - header.size = 3; - header.command = 4; - entries[put++].value_header = header; - entries[put++].value_uint32 = 5; - entries[put++].value_uint32 = 6; - - // we should be beyond the end of the buffer now. - DCHECK_LT(6U, put); - put = 0; - - engine()->Put(put); - while (get != put) { - // When the parsing stop progressing, break. - CommandBufferOffset new_get = engine()->WaitGetChanges(get); - if (new_get == get) { - EXPECT_EQ(new_get, engine()->Get()); - break; - } - get = new_get; - } - // We should be in an error case now. - EXPECT_EQ(BufferSyncInterface::kParseError, engine()->GetStatus()); - // Check that the error status was set to the first error. - EXPECT_EQ(BufferSyncInterface::kParseOutOfBounds, - engine()->GetParseError()); - // Check that the error status was reset after the query. - EXPECT_EQ(BufferSyncInterface::kParseNoError, engine()->GetParseError()); - - // Check that the valid commands did happen. - Mock::VerifyAndClearExpectations(api_mock()); - - engine()->CloseConnection(); - engine()->UnregisterSharedMemory(shm_id); - DestroyShm(shm); -} - -// Checks that HasWork() and DoWork() have the correct semantics. If there is -// work to do, DoWork should never block. -TEST_F(CommandBufferEngineTest, TestDoWork) { - engine()->InitConnection(); - CommandBufferEntry *entries = InitCommandBuffer(10, 0); - ASSERT_TRUE(entries != NULL); - - CommandBufferOffset get = engine()->Get(); - CommandBufferOffset put = get; - - // Test that if we have no message and no command we will block. - process_mock()->Reset(); - EXPECT_CALL(*process_mock(), HasMessage()).Times(AnyNumber()); - EXPECT_FALSE(engine()->HasWork()); - EXPECT_CALL(*process_mock(), ProcessMessage()); - EXPECT_TRUE(engine()->DoWork()); - - EXPECT_TRUE(process_mock()->would_have_blocked()); - Mock::VerifyAndClearExpectations(process_mock()); - - // Tests that messages get processed without blocking. - process_mock()->Reset(); - EXPECT_CALL(*process_mock(), HasMessage()).Times(AnyNumber()); - process_mock()->set_message_count(3); - EXPECT_TRUE(engine()->HasWork()); - - EXPECT_CALL(*process_mock(), ProcessMessage()).Times(3); - while (engine()->HasWork()) { - EXPECT_TRUE(engine()->DoWork()); - } - EXPECT_EQ(0u, process_mock()->message_count()); - EXPECT_FALSE(process_mock()->would_have_blocked()); - Mock::VerifyAndClearExpectations(process_mock()); - - // Test that if we have commands, we will process them without blocking. - // Create a command buffer with 3 commands - process_mock()->Reset(); - EXPECT_CALL(*process_mock(), HasMessage()).Times(AnyNumber()); - put += AddCommandWithExpect(entries + put, - BufferSyncInterface::kParseNoError, - 0, - 0, - NULL); - - CommandBufferEntry args1[2]; - args1[0].value_uint32 = 3; - args1[1].value_float = 4.f; - put += AddCommandWithExpect(entries + put, - BufferSyncInterface::kParseNoError, - 1, - 2, - args1); - - CommandBufferEntry args2[2]; - args2[0].value_uint32 = 5u; - args2[1].value_float = 6.f; - put += AddCommandWithExpect(entries + put, - BufferSyncInterface::kParseNoError, - 2, - 2, - args2); - - EXPECT_FALSE(engine()->HasWork()); // No work yet, until we change put - - engine()->Put(put); - EXPECT_TRUE(engine()->HasWork()); - - EXPECT_CALL(*process_mock(), ProcessMessage()).Times(0); - while (engine()->HasWork()) { - EXPECT_TRUE(engine()->DoWork()); - } - EXPECT_FALSE(process_mock()->would_have_blocked()); - get = engine()->Get(); - EXPECT_EQ(put, get); // once we're done, we should have executed everything. - ASSERT_EQ(BufferSyncInterface::kParsing, engine()->GetStatus()); - EXPECT_EQ(BufferSyncInterface::kParseNoError, engine()->GetParseError()); - Mock::VerifyAndClearExpectations(process_mock()); - Mock::VerifyAndClearExpectations(api_mock()); - - // Test that the engine stops if we send it a "kill" message. - process_mock()->Reset(); - EXPECT_CALL(*process_mock(), HasMessage()).Times(AnyNumber()); - process_mock()->set_message_count(1); - EXPECT_TRUE(engine()->HasWork()); - - EXPECT_CALL(*process_mock(), ProcessMessage()).WillOnce(Return(false)); - EXPECT_FALSE(engine()->DoWork()); - Mock::VerifyAndClearExpectations(process_mock()); - - engine()->CloseConnection(); - DestroyCommandBuffer(); -} - -} // namespace command_buffer -} // namespace o3d diff --git a/o3d/command_buffer/service/cross/cmd_parser.cc b/o3d/command_buffer/service/cross/cmd_parser.cc index 0d450268..d17ab99 100644 --- a/o3d/command_buffer/service/cross/cmd_parser.cc +++ b/o3d/command_buffer/service/cross/cmd_parser.cc @@ -64,20 +64,27 @@ CommandParser::CommandParser(void *shm_address, // conditions). This function only validates the header, leaving the arguments // validation to the handler, so it can pass a reference to them. // - get_ is modified *after* the command has been executed. -BufferSyncInterface::ParseError CommandParser::ProcessCommand() { +parse_error::ParseError CommandParser::ProcessCommand() { CommandBufferOffset get = get_; - if (get == put_) return BufferSyncInterface::kParseNoError; + if (get == put_) return parse_error::kParseNoError; CommandHeader header = buffer_[get].value_header; - if (header.size == 0) return BufferSyncInterface::kParseInvalidSize; - if (header.size + get > entry_count_) - return BufferSyncInterface::kParseOutOfBounds; - BufferSyncInterface::ParseError result = handler_->DoCommand( + if (header.size == 0) { + DLOG(INFO) << "Error: zero sized command in command buffer"; + return parse_error::kParseInvalidSize; + } + + if (header.size + get > entry_count_) { + DLOG(INFO) << "Error: get offset out of bounds"; + return parse_error::kParseOutOfBounds; + } + + parse_error::ParseError result = handler_->DoCommand( header.command, header.size - 1, buffer_ + get); // TODO(gman): If you want to log errors this is the best place to catch them. // It seems like we need an official way to turn on a debug mode and // get these errors. - if (result != BufferSyncInterface::kParseNoError) { + if (result != parse_error::kParseNoError) { DLOG(INFO) << "Error: " << result << " for Command " << GetCommandName(static_cast<CommandId>(header.command)); } @@ -87,12 +94,12 @@ BufferSyncInterface::ParseError CommandParser::ProcessCommand() { // Processes all the commands, while the buffer is not empty. Stop if an error // is encountered. -BufferSyncInterface::ParseError CommandParser::ProcessAllCommands() { +parse_error::ParseError CommandParser::ProcessAllCommands() { while (!IsEmpty()) { - BufferSyncInterface::ParseError error = ProcessCommand(); + parse_error::ParseError error = ProcessCommand(); if (error) return error; } - return BufferSyncInterface::kParseNoError; + return parse_error::kParseNoError; } } // namespace command_buffer diff --git a/o3d/command_buffer/service/cross/cmd_parser.h b/o3d/command_buffer/service/cross/cmd_parser.h index 425e8d9..89b8269 100644 --- a/o3d/command_buffer/service/cross/cmd_parser.h +++ b/o3d/command_buffer/service/cross/cmd_parser.h @@ -36,8 +36,7 @@ #define O3D_COMMAND_BUFFER_SERVICE_CROSS_CMD_PARSER_H_ #include "core/cross/types.h" -#include "command_buffer/common/cross/rpc.h" -#include "command_buffer/common/cross/buffer_sync_api.h" +#include "command_buffer/common/cross/constants.h" #include "command_buffer/common/cross/cmd_buffer_format.h" namespace o3d { @@ -73,10 +72,10 @@ class CommandParser { // Processes one command, updating the get pointer. This will return an error // if there are no commands in the buffer. - BufferSyncInterface::ParseError ProcessCommand(); + parse_error::ParseError ProcessCommand(); // Processes all commands until get == put. - BufferSyncInterface::ParseError ProcessAllCommands(); + parse_error::ParseError ProcessAllCommands(); private: CommandBufferOffset get_; @@ -99,9 +98,9 @@ class AsyncAPIInterface { // arg_count: the number of CommandBufferEntry arguments. // cmd_data: the command data. // Returns: - // BufferSyncInterface::NO_ERROR if no error was found, one of - // BufferSyncInterface::ParseError otherwise. - virtual BufferSyncInterface::ParseError DoCommand( + // parse_error::NO_ERROR if no error was found, one of + // parse_error::ParseError otherwise. + virtual parse_error::ParseError DoCommand( unsigned int command, unsigned int arg_count, const void* cmd_data) = 0; diff --git a/o3d/command_buffer/service/cross/cmd_parser_test.cc b/o3d/command_buffer/service/cross/cmd_parser_test.cc index ae48a9b..d85eb67 100644 --- a/o3d/command_buffer/service/cross/cmd_parser_test.cc +++ b/o3d/command_buffer/service/cross/cmd_parser_test.cc @@ -58,7 +58,7 @@ class CommandParserTest : public testing::Test { virtual void TearDown() {} // Adds a DoCommand expectation in the mock. - void AddDoCommandExpect(BufferSyncInterface::ParseError _return, + void AddDoCommandExpect(parse_error::ParseError _return, unsigned int command, unsigned int arg_count, CommandBufferEntry *args) { @@ -115,8 +115,8 @@ TEST_F(CommandParserTest, TestSimple) { parser->set_put(put); EXPECT_EQ(put, parser->put()); - AddDoCommandExpect(BufferSyncInterface::kParseNoError, 123, 0, NULL); - EXPECT_EQ(BufferSyncInterface::kParseNoError, parser->ProcessCommand()); + AddDoCommandExpect(parse_error::kParseNoError, 123, 0, NULL); + EXPECT_EQ(parse_error::kParseNoError, parser->ProcessCommand()); EXPECT_EQ(put, parser->get()); Mock::VerifyAndClearExpectations(api_mock()); @@ -133,8 +133,8 @@ TEST_F(CommandParserTest, TestSimple) { CommandBufferEntry param_array[2]; param_array[0].value_int32 = 2134; param_array[1].value_float = 1.f; - AddDoCommandExpect(BufferSyncInterface::kParseNoError, 456, 2, param_array); - EXPECT_EQ(BufferSyncInterface::kParseNoError, parser->ProcessCommand()); + AddDoCommandExpect(parse_error::kParseNoError, 456, 2, param_array); + EXPECT_EQ(parse_error::kParseNoError, parser->ProcessCommand()); EXPECT_EQ(put, parser->get()); Mock::VerifyAndClearExpectations(api_mock()); } @@ -162,14 +162,14 @@ TEST_F(CommandParserTest, TestMultipleCommands) { CommandBufferEntry param_array[2]; param_array[0].value_int32 = 5151; - AddDoCommandExpect(BufferSyncInterface::kParseNoError, 789, 1, param_array); + AddDoCommandExpect(parse_error::kParseNoError, 789, 1, param_array); param_array[1].value_int32 = 3434; - AddDoCommandExpect(BufferSyncInterface::kParseNoError, 2121, 1, + AddDoCommandExpect(parse_error::kParseNoError, 2121, 1, param_array+1); - EXPECT_EQ(BufferSyncInterface::kParseNoError, parser->ProcessCommand()); + EXPECT_EQ(parse_error::kParseNoError, parser->ProcessCommand()); EXPECT_EQ(put_cmd2, parser->get()); - EXPECT_EQ(BufferSyncInterface::kParseNoError, parser->ProcessCommand()); + EXPECT_EQ(parse_error::kParseNoError, parser->ProcessCommand()); EXPECT_EQ(put, parser->get()); Mock::VerifyAndClearExpectations(api_mock()); @@ -188,12 +188,12 @@ TEST_F(CommandParserTest, TestMultipleCommands) { EXPECT_EQ(put, parser->put()); param_array[0].value_int32 = 5656; - AddDoCommandExpect(BufferSyncInterface::kParseNoError, 4545, 1, param_array); + AddDoCommandExpect(parse_error::kParseNoError, 4545, 1, param_array); param_array[1].value_int32 = 7878; - AddDoCommandExpect(BufferSyncInterface::kParseNoError, 6767, 1, + AddDoCommandExpect(parse_error::kParseNoError, 6767, 1, param_array+1); - EXPECT_EQ(BufferSyncInterface::kParseNoError, parser->ProcessAllCommands()); + EXPECT_EQ(parse_error::kParseNoError, parser->ProcessAllCommands()); EXPECT_EQ(put, parser->get()); Mock::VerifyAndClearExpectations(api_mock()); } @@ -209,11 +209,11 @@ TEST_F(CommandParserTest, TestWrap) { header.size = 1; header.command = i; buffer()[put++].value_header = header; - AddDoCommandExpect(BufferSyncInterface::kParseNoError, i, 0, NULL); + AddDoCommandExpect(parse_error::kParseNoError, i, 0, NULL); } parser->set_put(put); EXPECT_EQ(put, parser->put()); - EXPECT_EQ(BufferSyncInterface::kParseNoError, parser->ProcessAllCommands()); + EXPECT_EQ(parse_error::kParseNoError, parser->ProcessAllCommands()); EXPECT_EQ(put, parser->get()); Mock::VerifyAndClearExpectations(api_mock()); @@ -225,13 +225,13 @@ TEST_F(CommandParserTest, TestWrap) { buffer()[put++].value_int32 = 5; CommandBufferEntry param; param.value_int32 = 5; - AddDoCommandExpect(BufferSyncInterface::kParseNoError, 3, 1, ¶m); + AddDoCommandExpect(parse_error::kParseNoError, 3, 1, ¶m); DCHECK_EQ(5u, put); put = 0; parser->set_put(put); EXPECT_EQ(put, parser->put()); - EXPECT_EQ(BufferSyncInterface::kParseNoError, parser->ProcessAllCommands()); + EXPECT_EQ(parse_error::kParseNoError, parser->ProcessAllCommands()); EXPECT_EQ(put, parser->get()); Mock::VerifyAndClearExpectations(api_mock()); @@ -241,10 +241,10 @@ TEST_F(CommandParserTest, TestWrap) { buffer()[put++].value_header = header; buffer()[put++].value_int32 = 6; param.value_int32 = 6; - AddDoCommandExpect(BufferSyncInterface::kParseNoError, 4, 1, ¶m); + AddDoCommandExpect(parse_error::kParseNoError, 4, 1, ¶m); parser->set_put(put); EXPECT_EQ(put, parser->put()); - EXPECT_EQ(BufferSyncInterface::kParseNoError, parser->ProcessAllCommands()); + EXPECT_EQ(parse_error::kParseNoError, parser->ProcessAllCommands()); EXPECT_EQ(put, parser->get()); Mock::VerifyAndClearExpectations(api_mock()); } @@ -262,7 +262,7 @@ TEST_F(CommandParserTest, TestError) { parser->set_put(put); EXPECT_EQ(put, parser->put()); - EXPECT_EQ(BufferSyncInterface::kParseInvalidSize, + EXPECT_EQ(parse_error::kParseInvalidSize, parser->ProcessAllCommands()); // check that no DoCommand call was made. Mock::VerifyAndClearExpectations(api_mock()); @@ -277,7 +277,7 @@ TEST_F(CommandParserTest, TestError) { parser->set_put(put); EXPECT_EQ(put, parser->put()); - EXPECT_EQ(BufferSyncInterface::kParseOutOfBounds, + EXPECT_EQ(parse_error::kParseOutOfBounds, parser->ProcessAllCommands()); // check that no DoCommand call was made. Mock::VerifyAndClearExpectations(api_mock()); @@ -297,16 +297,16 @@ TEST_F(CommandParserTest, TestError) { parser->set_put(put); EXPECT_EQ(put, parser->put()); // have the first command fail to parse. - AddDoCommandExpect(BufferSyncInterface::kParseUnknownCommand, 3, 0, NULL); - EXPECT_EQ(BufferSyncInterface::kParseUnknownCommand, + AddDoCommandExpect(parse_error::kParseUnknownCommand, 3, 0, NULL); + EXPECT_EQ(parse_error::kParseUnknownCommand, parser->ProcessAllCommands()); // check that only one command was executed, and that get reflects that // correctly. EXPECT_EQ(put_post_fail, parser->get()); Mock::VerifyAndClearExpectations(api_mock()); // make the second one succeed, and check that the parser recovered fine. - AddDoCommandExpect(BufferSyncInterface::kParseNoError, 4, 0, NULL); - EXPECT_EQ(BufferSyncInterface::kParseNoError, parser->ProcessAllCommands()); + AddDoCommandExpect(parse_error::kParseNoError, 4, 0, NULL); + EXPECT_EQ(parse_error::kParseNoError, parser->ProcessAllCommands()); EXPECT_EQ(put, parser->get()); Mock::VerifyAndClearExpectations(api_mock()); } diff --git a/o3d/command_buffer/service/cross/gapi_decoder.cc b/o3d/command_buffer/service/cross/gapi_decoder.cc index db55421..650d8d9 100644 --- a/o3d/command_buffer/service/cross/gapi_decoder.cc +++ b/o3d/command_buffer/service/cross/gapi_decoder.cc @@ -82,7 +82,7 @@ const CommandInfo g_command_info[] = { // Note: args is a pointer to the command buffer. As such, it could be changed // by a (malicious) client at any time, so if validation has to happen, it // should operate on a copy of them. -BufferSyncInterface::ParseError GAPIDecoder::DoCommand( +parse_error::ParseError GAPIDecoder::DoCommand( unsigned int command, unsigned int arg_count, const void* cmd_data) { @@ -103,10 +103,10 @@ BufferSyncInterface::ParseError GAPIDecoder::DoCommand( #undef O3D_COMMAND_BUFFER_CMD_OP } } else { - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; } } - return BufferSyncInterface::kParseUnknownCommand; + return parse_error::kParseUnknownCommand; } void *GAPIDecoder::GetAddressAndCheckSize(unsigned int shm_id, @@ -119,51 +119,51 @@ void *GAPIDecoder::GetAddressAndCheckSize(unsigned int shm_id, return static_cast<char *>(shm_addr) + offset; } -BufferSyncInterface::ParseError GAPIDecoder::HandleNoop( +parse_error::ParseError GAPIDecoder::HandleNoop( uint32 arg_count, const cmd::Noop& args) { - return BufferSyncInterface::kParseNoError; + return parse_error::kParseNoError; } -BufferSyncInterface::ParseError GAPIDecoder::HandleSetToken( +parse_error::ParseError GAPIDecoder::HandleSetToken( uint32 arg_count, const cmd::SetToken& args) { engine_->set_token(args.token); - return BufferSyncInterface::kParseNoError; + return parse_error::kParseNoError; } -BufferSyncInterface::ParseError GAPIDecoder::HandleBeginFrame( +parse_error::ParseError GAPIDecoder::HandleBeginFrame( uint32 arg_count, const cmd::BeginFrame& args) { gapi_->BeginFrame(); - return BufferSyncInterface::kParseNoError; + return parse_error::kParseNoError; } -BufferSyncInterface::ParseError GAPIDecoder::HandleEndFrame( +parse_error::ParseError GAPIDecoder::HandleEndFrame( uint32 arg_count, const cmd::EndFrame& args) { gapi_->EndFrame(); - return BufferSyncInterface::kParseNoError; + return parse_error::kParseNoError; } -BufferSyncInterface::ParseError GAPIDecoder::HandleClear( +parse_error::ParseError GAPIDecoder::HandleClear( uint32 arg_count, const cmd::Clear& args) { // Pull out some values so they can't be changed by another thread after we've // validated them. uint32 buffers = args.buffers; if (buffers & ~command_buffer::kAllBuffers) - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; RGBA rgba; rgba.red = args.red; rgba.green = args.green; rgba.blue = args.blue; rgba.alpha = args.alpha; gapi_->Clear(buffers, rgba, args.depth, args.stencil); - return BufferSyncInterface::kParseNoError; + return parse_error::kParseNoError; } -BufferSyncInterface::ParseError GAPIDecoder::HandleSetViewport( +parse_error::ParseError GAPIDecoder::HandleSetViewport( uint32 arg_count, const cmd::SetViewport& args) { gapi_->SetViewport(args.left, @@ -172,35 +172,35 @@ BufferSyncInterface::ParseError GAPIDecoder::HandleSetViewport( args.height, args.z_min, args.z_max); - return BufferSyncInterface::kParseNoError; + return parse_error::kParseNoError; } -BufferSyncInterface::ParseError GAPIDecoder::HandleCreateVertexBuffer( +parse_error::ParseError GAPIDecoder::HandleCreateVertexBuffer( uint32 arg_count, const cmd::CreateVertexBuffer& args) { return gapi_->CreateVertexBuffer( args.vertex_buffer_id, args.size, args.flags); } -BufferSyncInterface::ParseError GAPIDecoder::HandleDestroyVertexBuffer( +parse_error::ParseError GAPIDecoder::HandleDestroyVertexBuffer( uint32 arg_count, const cmd::DestroyVertexBuffer& args) { return gapi_->DestroyVertexBuffer(args.vertex_buffer_id); } -BufferSyncInterface::ParseError GAPIDecoder::HandleSetVertexBufferDataImmediate( +parse_error::ParseError GAPIDecoder::HandleSetVertexBufferDataImmediate( uint32 arg_count, const cmd::SetVertexBufferDataImmediate& args) { uint32 size = ImmediateDataSize(arg_count, args); if (size == 0) { - return BufferSyncInterface::kParseNoError; + return parse_error::kParseNoError; } return gapi_->SetVertexBufferData(args.vertex_buffer_id, args.offset, size, AddressAfterStruct(args)); } -BufferSyncInterface::ParseError GAPIDecoder::HandleSetVertexBufferData( +parse_error::ParseError GAPIDecoder::HandleSetVertexBufferData( uint32 arg_count, const cmd::SetVertexBufferData& args) { // Pull out some values so they can't be changed by another thread after we've @@ -209,12 +209,12 @@ BufferSyncInterface::ParseError GAPIDecoder::HandleSetVertexBufferData( void *data = GetAddressAndCheckSize(args.shared_memory.id, args.shared_memory.offset, size); - if (!data) return BufferSyncInterface::kParseInvalidArguments; + if (!data) return parse_error::kParseInvalidArguments; return gapi_->SetVertexBufferData( args.vertex_buffer_id, args.offset, size, data); } -BufferSyncInterface::ParseError GAPIDecoder::HandleGetVertexBufferData( +parse_error::ParseError GAPIDecoder::HandleGetVertexBufferData( uint32 arg_count, const cmd::GetVertexBufferData& args) { // Pull out some values so they can't be changed by another thread after we've @@ -223,35 +223,35 @@ BufferSyncInterface::ParseError GAPIDecoder::HandleGetVertexBufferData( void *data = GetAddressAndCheckSize(args.shared_memory.id, args.shared_memory.offset, size); - if (!data) return BufferSyncInterface::kParseInvalidArguments; + if (!data) return parse_error::kParseInvalidArguments; return gapi_->GetVertexBufferData( args.vertex_buffer_id, args.offset, size, data); } -BufferSyncInterface::ParseError GAPIDecoder::HandleCreateIndexBuffer( +parse_error::ParseError GAPIDecoder::HandleCreateIndexBuffer( uint32 arg_count, const cmd::CreateIndexBuffer& args) { return gapi_->CreateIndexBuffer(args.index_buffer_id, args.size, args.flags); } -BufferSyncInterface::ParseError GAPIDecoder::HandleDestroyIndexBuffer( +parse_error::ParseError GAPIDecoder::HandleDestroyIndexBuffer( uint32 arg_count, const cmd::DestroyIndexBuffer& args) { return gapi_->DestroyIndexBuffer(args.index_buffer_id); } -BufferSyncInterface::ParseError GAPIDecoder::HandleSetIndexBufferDataImmediate( +parse_error::ParseError GAPIDecoder::HandleSetIndexBufferDataImmediate( uint32 arg_count, const cmd::SetIndexBufferDataImmediate& args) { uint32 size = ImmediateDataSize(arg_count, args); if (size == 0) { - return BufferSyncInterface::kParseNoError; + return parse_error::kParseNoError; } return gapi_->SetIndexBufferData(args.index_buffer_id, args.offset, size, AddressAfterStruct(args)); } -BufferSyncInterface::ParseError GAPIDecoder::HandleSetIndexBufferData( +parse_error::ParseError GAPIDecoder::HandleSetIndexBufferData( uint32 arg_count, const cmd::SetIndexBufferData& args) { // Pull out some values so they can't be changed by another thread after we've @@ -260,12 +260,12 @@ BufferSyncInterface::ParseError GAPIDecoder::HandleSetIndexBufferData( void *data = GetAddressAndCheckSize(args.shared_memory.id, args.shared_memory.offset, size); - if (!data) return BufferSyncInterface::kParseInvalidArguments; + if (!data) return parse_error::kParseInvalidArguments; return gapi_->SetIndexBufferData( args.index_buffer_id, args.offset, size, data); } -BufferSyncInterface::ParseError GAPIDecoder::HandleGetIndexBufferData( +parse_error::ParseError GAPIDecoder::HandleGetIndexBufferData( uint32 arg_count, const cmd::GetIndexBufferData& args) { // Pull out some values so they can't be changed by another thread after we've @@ -274,24 +274,24 @@ BufferSyncInterface::ParseError GAPIDecoder::HandleGetIndexBufferData( void *data = GetAddressAndCheckSize(args.shared_memory.id, args.shared_memory.offset, size); - if (!data) return BufferSyncInterface::kParseInvalidArguments; + if (!data) return parse_error::kParseInvalidArguments; return gapi_->GetIndexBufferData( args.index_buffer_id, args.offset, size, data); } -BufferSyncInterface::ParseError GAPIDecoder::HandleCreateVertexStruct( +parse_error::ParseError GAPIDecoder::HandleCreateVertexStruct( uint32 arg_count, const cmd::CreateVertexStruct& args) { return gapi_->CreateVertexStruct(args.vertex_struct_id, args.input_count); } -BufferSyncInterface::ParseError GAPIDecoder::HandleDestroyVertexStruct( +parse_error::ParseError GAPIDecoder::HandleDestroyVertexStruct( uint32 arg_count, const cmd::DestroyVertexStruct& args) { return gapi_->DestroyVertexStruct(args.vertex_struct_id); } -BufferSyncInterface::ParseError GAPIDecoder::HandleSetVertexInput( +parse_error::ParseError GAPIDecoder::HandleSetVertexInput( uint32 arg_count, const cmd::SetVertexInput& args) { unsigned int type_stride_semantic = args.type_stride_semantic; @@ -305,7 +305,7 @@ BufferSyncInterface::ParseError GAPIDecoder::HandleSetVertexInput( cmd::SetVertexInput::Stride::Get(type_stride_semantic); if (semantic >= vertex_struct::kNumSemantics || type >= vertex_struct::kNumTypes || stride == 0) - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; return gapi_->SetVertexInput( args.vertex_struct_id, args.input_index, args.vertex_buffer_id, args.offset, stride, @@ -314,40 +314,40 @@ BufferSyncInterface::ParseError GAPIDecoder::HandleSetVertexInput( semantic_index); } -BufferSyncInterface::ParseError GAPIDecoder::HandleSetVertexStruct( +parse_error::ParseError GAPIDecoder::HandleSetVertexStruct( uint32 arg_count, const cmd::SetVertexStruct& args) { return gapi_->SetVertexStruct(args.vertex_struct_id); } -BufferSyncInterface::ParseError GAPIDecoder::HandleDraw( +parse_error::ParseError GAPIDecoder::HandleDraw( uint32 arg_count, const cmd::Draw& args) { // Pull out some values so they can't be changed by another thread after we've // validated them. uint32 primitive_type = args.primitive_type; if (primitive_type >= command_buffer::kMaxPrimitiveType) - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; return gapi_->Draw( static_cast<command_buffer::PrimitiveType>(primitive_type), args.first, args.count); } -BufferSyncInterface::ParseError GAPIDecoder::HandleDrawIndexed( +parse_error::ParseError GAPIDecoder::HandleDrawIndexed( uint32 arg_count, const cmd::DrawIndexed& args) { // Pull out some values so they can't be changed by another thread after we've // validated them. uint32 primitive_type = args.primitive_type; if (primitive_type >= command_buffer::kMaxPrimitiveType) - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; return gapi_->DrawIndexed( static_cast<command_buffer::PrimitiveType>(primitive_type), args.index_buffer_id, args.first, args.count, args.min_index, args.max_index); } -BufferSyncInterface::ParseError GAPIDecoder::HandleCreateEffect( +parse_error::ParseError GAPIDecoder::HandleCreateEffect( uint32 arg_count, const cmd::CreateEffect& args) { // Pull out some values so they can't be changed by another thread after we've @@ -356,11 +356,11 @@ BufferSyncInterface::ParseError GAPIDecoder::HandleCreateEffect( void *data = GetAddressAndCheckSize(args.shared_memory.id, args.shared_memory.offset, size); - if (!data) return BufferSyncInterface::kParseInvalidArguments; + if (!data) return parse_error::kParseInvalidArguments; return gapi_->CreateEffect(args.effect_id, size, data); } -BufferSyncInterface::ParseError GAPIDecoder::HandleCreateEffectImmediate( +parse_error::ParseError GAPIDecoder::HandleCreateEffectImmediate( uint32 arg_count, const cmd::CreateEffectImmediate& args) { // Pull out some values so they can't be changed by another thread after we've @@ -368,27 +368,27 @@ BufferSyncInterface::ParseError GAPIDecoder::HandleCreateEffectImmediate( uint32 size = args.size; uint32 data_size = ImmediateDataSize(arg_count, args); if (size > data_size) { - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; } if (data_size == 0) { - return BufferSyncInterface::kParseNoError; + return parse_error::kParseNoError; } return gapi_->CreateEffect(args.effect_id, size, AddressAfterStruct(args)); } -BufferSyncInterface::ParseError GAPIDecoder::HandleDestroyEffect( +parse_error::ParseError GAPIDecoder::HandleDestroyEffect( uint32 arg_count, const cmd::DestroyEffect& args) { return gapi_->DestroyEffect(args.effect_id); } -BufferSyncInterface::ParseError GAPIDecoder::HandleSetEffect( +parse_error::ParseError GAPIDecoder::HandleSetEffect( uint32 arg_count, const cmd::SetEffect& args) { return gapi_->SetEffect(args.effect_id); } -BufferSyncInterface::ParseError GAPIDecoder::HandleGetParamCount( +parse_error::ParseError GAPIDecoder::HandleGetParamCount( uint32 arg_count, const cmd::GetParamCount& args) { // Pull out some values so they can't be changed by another thread after we've @@ -397,17 +397,17 @@ BufferSyncInterface::ParseError GAPIDecoder::HandleGetParamCount( void *data = GetAddressAndCheckSize(args.shared_memory.id, args.shared_memory.offset, size); - if (!data) return BufferSyncInterface::kParseInvalidArguments; + if (!data) return parse_error::kParseInvalidArguments; return gapi_->GetParamCount(args.effect_id, size, data); } -BufferSyncInterface::ParseError GAPIDecoder::HandleCreateParam( +parse_error::ParseError GAPIDecoder::HandleCreateParam( uint32 arg_count, const cmd::CreateParam& args) { return gapi_->CreateParam(args.param_id, args.effect_id, args.index); } -BufferSyncInterface::ParseError GAPIDecoder::HandleCreateParamByName( +parse_error::ParseError GAPIDecoder::HandleCreateParamByName( uint32 arg_count, const cmd::CreateParamByName& args) { // Pull out some values so they can't be changed by another thread after we've @@ -416,12 +416,12 @@ BufferSyncInterface::ParseError GAPIDecoder::HandleCreateParamByName( void *data = GetAddressAndCheckSize(args.shared_memory.id, args.shared_memory.offset, size); - if (!data) return BufferSyncInterface::kParseInvalidArguments; + if (!data) return parse_error::kParseInvalidArguments; return gapi_->CreateParamByName(args.param_id, args.effect_id, size, data); } -BufferSyncInterface::ParseError GAPIDecoder::HandleCreateParamByNameImmediate( +parse_error::ParseError GAPIDecoder::HandleCreateParamByNameImmediate( uint32 arg_count, const cmd::CreateParamByNameImmediate& args) { // Pull out some values so they can't be changed by another thread after we've @@ -429,21 +429,21 @@ BufferSyncInterface::ParseError GAPIDecoder::HandleCreateParamByNameImmediate( uint32 size = args.size; uint32 data_size = ImmediateDataSize(arg_count, args); if (size > data_size) - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; if (data_size == 0) { - return BufferSyncInterface::kParseNoError; + return parse_error::kParseNoError; } return gapi_->CreateParamByName(args.param_id, args.effect_id, size, AddressAfterStruct(args)); } -BufferSyncInterface::ParseError GAPIDecoder::HandleDestroyParam( +parse_error::ParseError GAPIDecoder::HandleDestroyParam( uint32 arg_count, const cmd::DestroyParam& args) { return gapi_->DestroyParam(args.param_id); } -BufferSyncInterface::ParseError GAPIDecoder::HandleSetParamData( +parse_error::ParseError GAPIDecoder::HandleSetParamData( uint32 arg_count, const cmd::SetParamData& args) { // Pull out some values so they can't be changed by another thread after we've @@ -452,11 +452,11 @@ BufferSyncInterface::ParseError GAPIDecoder::HandleSetParamData( void *data = GetAddressAndCheckSize(args.shared_memory.id, args.shared_memory.offset, size); - if (!data) return BufferSyncInterface::kParseInvalidArguments; + if (!data) return parse_error::kParseInvalidArguments; return gapi_->SetParamData(args.param_id, size, data); } -BufferSyncInterface::ParseError GAPIDecoder::HandleSetParamDataImmediate( +parse_error::ParseError GAPIDecoder::HandleSetParamDataImmediate( uint32 arg_count, const cmd::SetParamDataImmediate& args) { // Pull out some values so they can't be changed by another thread after we've @@ -464,15 +464,15 @@ BufferSyncInterface::ParseError GAPIDecoder::HandleSetParamDataImmediate( uint32 size = args.size; uint32 data_size = ImmediateDataSize(arg_count, args); if (size > data_size) { - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; } if (data_size == 0) { - return BufferSyncInterface::kParseNoError; + return parse_error::kParseNoError; } return gapi_->SetParamData(args.param_id, size, AddressAfterStruct(args)); } -BufferSyncInterface::ParseError GAPIDecoder::HandleGetParamDesc( +parse_error::ParseError GAPIDecoder::HandleGetParamDesc( uint32 arg_count, const cmd::GetParamDesc& args) { // Pull out some values so they can't be changed by another thread after we've @@ -481,11 +481,11 @@ BufferSyncInterface::ParseError GAPIDecoder::HandleGetParamDesc( void *data = GetAddressAndCheckSize(args.shared_memory.id, args.shared_memory.offset, size); - if (!data) return BufferSyncInterface::kParseInvalidArguments; + if (!data) return parse_error::kParseInvalidArguments; return gapi_->GetParamDesc(args.param_id, size, data); } -BufferSyncInterface::ParseError GAPIDecoder::HandleGetStreamCount( +parse_error::ParseError GAPIDecoder::HandleGetStreamCount( uint32 arg_count, const cmd::GetStreamCount& args) { // Pull out some values so they can't be changed by another thread after we've @@ -494,11 +494,11 @@ BufferSyncInterface::ParseError GAPIDecoder::HandleGetStreamCount( void *data = GetAddressAndCheckSize(args.shared_memory.id, args.shared_memory.offset, size); - if (!data) return BufferSyncInterface::kParseInvalidArguments; + if (!data) return parse_error::kParseInvalidArguments; return gapi_->GetStreamCount(args.effect_id, size, data); } -BufferSyncInterface::ParseError GAPIDecoder::HandleGetStreamDesc( +parse_error::ParseError GAPIDecoder::HandleGetStreamDesc( uint32 arg_count, const cmd::GetStreamDesc& args) { // Pull out some values so they can't be changed by another thread after we've @@ -507,17 +507,17 @@ BufferSyncInterface::ParseError GAPIDecoder::HandleGetStreamDesc( void *data = GetAddressAndCheckSize(args.shared_memory.id, args.shared_memory.offset, size); - if (!data) return BufferSyncInterface::kParseInvalidArguments; + if (!data) return parse_error::kParseInvalidArguments; return gapi_->GetStreamDesc(args.effect_id, args.index, size, data); } -BufferSyncInterface::ParseError GAPIDecoder::HandleDestroyTexture( +parse_error::ParseError GAPIDecoder::HandleDestroyTexture( uint32 arg_count, const cmd::DestroyTexture& args) { return gapi_->DestroyTexture(args.texture_id); } -BufferSyncInterface::ParseError GAPIDecoder::HandleCreateTexture2d( +parse_error::ParseError GAPIDecoder::HandleCreateTexture2d( uint32 arg_count, const cmd::CreateTexture2d& args) { unsigned int width_height = args.width_height; @@ -532,14 +532,14 @@ BufferSyncInterface::ParseError GAPIDecoder::HandleCreateTexture2d( 1 + base::bits::Log2Ceiling(std::max(width, height)); if ((width == 0) || (height == 0) || (levels > max_levels) || (unused != 0) || (format == texture::kUnknown) || (levels == 0)) - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; bool enable_render_surfaces = !!flags; return gapi_->CreateTexture2D(args.texture_id, width, height, levels, static_cast<texture::Format>(format), flags, enable_render_surfaces); } -BufferSyncInterface::ParseError GAPIDecoder::HandleCreateTexture3d( +parse_error::ParseError GAPIDecoder::HandleCreateTexture3d( uint32 arg_count, const cmd::CreateTexture3d& args) { unsigned int width_height = args.width_height; @@ -559,14 +559,14 @@ BufferSyncInterface::ParseError GAPIDecoder::HandleCreateTexture3d( if ((width == 0) || (height == 0) || (depth == 0) || (levels > max_levels) || (unused1 != 0) || (unused2 != 0) || (format == texture::kUnknown) || (levels == 0)) - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; bool enable_render_surfaces = !!flags; return gapi_->CreateTexture3D(args.texture_id, width, height, depth, levels, static_cast<texture::Format>(format), flags, enable_render_surfaces); } -BufferSyncInterface::ParseError GAPIDecoder::HandleCreateTextureCube( +parse_error::ParseError GAPIDecoder::HandleCreateTextureCube( uint32 arg_count, const cmd::CreateTextureCube& args) { unsigned int side_unused = args.edge_length; @@ -583,14 +583,14 @@ BufferSyncInterface::ParseError GAPIDecoder::HandleCreateTextureCube( unsigned int max_levels = 1 + base::bits::Log2Ceiling(side); if ((side == 0) || (levels > max_levels) || (unused1 != 0) || (unused2 != 0) || (format == texture::kUnknown) || (levels == 0)) - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; bool enable_render_surfaces = !!flags; return gapi_->CreateTextureCube(args.texture_id, side, levels, static_cast<texture::Format>(format), flags, enable_render_surfaces); } -BufferSyncInterface::ParseError GAPIDecoder::HandleSetTextureData( +parse_error::ParseError GAPIDecoder::HandleSetTextureData( uint32 arg_count, const cmd::SetTextureData& args) { unsigned int x_y = args.x_y; @@ -610,14 +610,14 @@ BufferSyncInterface::ParseError GAPIDecoder::HandleSetTextureData( const void *data = GetAddressAndCheckSize(args.shared_memory.id, args.shared_memory.offset, size); if (face >= 6 || unused != 0 || !data) - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; return gapi_->SetTextureData( args.texture_id, x, y, z, width, height, depth, level, static_cast<texture::Face>(face), args.row_pitch, args.slice_pitch, size, data); } -BufferSyncInterface::ParseError GAPIDecoder::HandleSetTextureDataImmediate( +parse_error::ParseError GAPIDecoder::HandleSetTextureDataImmediate( uint32 arg_count, const cmd::SetTextureDataImmediate& args) { unsigned int x_y = args.x_y; @@ -637,9 +637,9 @@ BufferSyncInterface::ParseError GAPIDecoder::HandleSetTextureDataImmediate( uint32 data_size = ImmediateDataSize(arg_count, args); if (face >= 6 || unused != 0 || size > data_size) - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; if (data_size == 0) { - return BufferSyncInterface::kParseNoError; + return parse_error::kParseNoError; } return gapi_->SetTextureData( args.texture_id, x, y, z, width, height, depth, level, @@ -647,7 +647,7 @@ BufferSyncInterface::ParseError GAPIDecoder::HandleSetTextureDataImmediate( args.slice_pitch, size, AddressAfterStruct(args)); } -BufferSyncInterface::ParseError GAPIDecoder::HandleGetTextureData( +parse_error::ParseError GAPIDecoder::HandleGetTextureData( uint32 arg_count, const cmd::GetTextureData& args) { unsigned int x_y = args.x_y; @@ -667,31 +667,31 @@ BufferSyncInterface::ParseError GAPIDecoder::HandleGetTextureData( void *data = GetAddressAndCheckSize(args.shared_memory.id, args.shared_memory.offset, size); if (face >= 6 || unused != 0 || !data) - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; return gapi_->GetTextureData( args.texture_id, x, y, z, width, height, depth, level, static_cast<texture::Face>(face), args.row_pitch, args.slice_pitch, size, data); } -BufferSyncInterface::ParseError GAPIDecoder::HandleCreateSampler( +parse_error::ParseError GAPIDecoder::HandleCreateSampler( uint32 arg_count, const cmd::CreateSampler& args) { return gapi_->CreateSampler(args.sampler_id); } -BufferSyncInterface::ParseError GAPIDecoder::HandleDestroySampler( +parse_error::ParseError GAPIDecoder::HandleDestroySampler( uint32 arg_count, const cmd::DestroySampler& args) { return gapi_->DestroySampler(args.sampler_id); } -BufferSyncInterface::ParseError GAPIDecoder::HandleSetSamplerStates( +parse_error::ParseError GAPIDecoder::HandleSetSamplerStates( uint32 arg_count, const cmd::SetSamplerStates& args) { Uint32 arg = args.sampler_states; if (cmd::SetSamplerStates::Unused::Get(arg) != 0) - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; unsigned int address_u_value = cmd::SetSamplerStates::AddressingU::Get(arg); unsigned int address_v_value = cmd::SetSamplerStates::AddressingV::Get(arg); unsigned int address_w_value = cmd::SetSamplerStates::AddressingW::Get(arg); @@ -708,7 +708,7 @@ BufferSyncInterface::ParseError GAPIDecoder::HandleSetSamplerStates( mag_filter_value == sampler::kNone || min_filter_value == sampler::kNone || max_anisotropy == 0) { - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; } gapi_->SetSamplerStates( args.sampler_id, @@ -719,10 +719,10 @@ BufferSyncInterface::ParseError GAPIDecoder::HandleSetSamplerStates( static_cast<sampler::FilteringMode>(min_filter_value), static_cast<sampler::FilteringMode>(mip_filter_value), max_anisotropy); - return BufferSyncInterface::kParseNoError; + return parse_error::kParseNoError; } -BufferSyncInterface::ParseError GAPIDecoder::HandleSetSamplerBorderColor( +parse_error::ParseError GAPIDecoder::HandleSetSamplerBorderColor( uint32 arg_count, const cmd::SetSamplerBorderColor& args) { RGBA rgba; @@ -733,18 +733,18 @@ BufferSyncInterface::ParseError GAPIDecoder::HandleSetSamplerBorderColor( return gapi_->SetSamplerBorderColor(args.sampler_id, rgba); } -BufferSyncInterface::ParseError GAPIDecoder::HandleSetSamplerTexture( +parse_error::ParseError GAPIDecoder::HandleSetSamplerTexture( uint32 arg_count, const cmd::SetSamplerTexture& args) { return gapi_->SetSamplerTexture(args.sampler_id, args.texture_id); } -BufferSyncInterface::ParseError GAPIDecoder::HandleSetScissor( +parse_error::ParseError GAPIDecoder::HandleSetScissor( uint32 arg_count, const cmd::SetScissor& args) { Uint32 x_y_enable = args.x_y_enable; if (cmd::SetScissor::Unused::Get(x_y_enable) != 0) - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; unsigned int x = cmd::SetScissor::X::Get(x_y_enable); unsigned int y = cmd::SetScissor::Y::Get(x_y_enable); bool enable = cmd::SetScissor::Enable::Get(x_y_enable) != 0; @@ -752,30 +752,30 @@ BufferSyncInterface::ParseError GAPIDecoder::HandleSetScissor( unsigned int width = cmd::SetScissor::Width::Get(width_height); unsigned int height = cmd::SetScissor::Height::Get(width_height); gapi_->SetScissor(enable, x, y, width, height); - return BufferSyncInterface::kParseNoError; + return parse_error::kParseNoError; } -BufferSyncInterface::ParseError GAPIDecoder::HandleSetPolygonOffset( +parse_error::ParseError GAPIDecoder::HandleSetPolygonOffset( uint32 arg_count, const cmd::SetPolygonOffset& args) { gapi_->SetPolygonOffset(args.slope_factor, args.units); - return BufferSyncInterface::kParseNoError; + return parse_error::kParseNoError; } -BufferSyncInterface::ParseError GAPIDecoder::HandleSetPointLineRaster( +parse_error::ParseError GAPIDecoder::HandleSetPointLineRaster( uint32 arg_count, const cmd::SetPointLineRaster& args) { Uint32 enables = args.enables; if (cmd::SetPointLineRaster::Unused::Get(enables) != 0) - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; bool line_smooth = !!cmd::SetPointLineRaster::LineSmoothEnable::Get(enables); bool point_sprite = !!cmd::SetPointLineRaster::PointSpriteEnable::Get(enables); gapi_->SetPointLineRaster(line_smooth, point_sprite, args.point_size); - return BufferSyncInterface::kParseNoError; + return parse_error::kParseNoError; } -BufferSyncInterface::ParseError GAPIDecoder::HandleSetPolygonRaster( +parse_error::ParseError GAPIDecoder::HandleSetPolygonRaster( uint32 arg_count, const cmd::SetPolygonRaster& args) { Uint32 fill_cull = args.fill_cull; @@ -784,19 +784,19 @@ BufferSyncInterface::ParseError GAPIDecoder::HandleSetPolygonRaster( if (cmd::SetPolygonRaster::Unused::Get(fill_cull) != 0 || fill_value >= command_buffer::kNumPolygonMode || cull_value >= command_buffer::kNumFaceCullMode) - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; gapi_->SetPolygonRaster( static_cast<command_buffer::PolygonMode>(fill_value), static_cast<command_buffer::FaceCullMode>(cull_value)); - return BufferSyncInterface::kParseNoError; + return parse_error::kParseNoError; } -BufferSyncInterface::ParseError GAPIDecoder::HandleSetAlphaTest( +parse_error::ParseError GAPIDecoder::HandleSetAlphaTest( uint32 arg_count, const cmd::SetAlphaTest& args) { Uint32 func_enable = args.func_enable; if (cmd::SetAlphaTest::Unused::Get(func_enable) != 0) - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; // Check that the bitmask get cannot generate values outside of the // allowed range. COMPILE_ASSERT(cmd::SetAlphaTest::Func::kMask < @@ -806,15 +806,15 @@ BufferSyncInterface::ParseError GAPIDecoder::HandleSetAlphaTest( cmd::SetAlphaTest::Func::Get(func_enable)); bool enable = cmd::SetAlphaTest::Enable::Get(func_enable) != 0; gapi_->SetAlphaTest(enable, args.value, comp); - return BufferSyncInterface::kParseNoError; + return parse_error::kParseNoError; } -BufferSyncInterface::ParseError GAPIDecoder::HandleSetDepthTest( +parse_error::ParseError GAPIDecoder::HandleSetDepthTest( uint32 arg_count, const cmd::SetDepthTest& args) { Uint32 func_enable = args.func_enable; if (cmd::SetDepthTest::Unused::Get(func_enable) != 0) - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; // Check that the bitmask get cannot generate values outside of the // allowed range. COMPILE_ASSERT(cmd::SetDepthTest::Func::kMask < @@ -825,10 +825,10 @@ BufferSyncInterface::ParseError GAPIDecoder::HandleSetDepthTest( bool write_enable = cmd::SetDepthTest::WriteEnable::Get(func_enable) != 0; bool enable = cmd::SetDepthTest::Enable::Get(func_enable) != 0; gapi_->SetDepthTest(enable, write_enable, comp); - return BufferSyncInterface::kParseNoError; + return parse_error::kParseNoError; } -BufferSyncInterface::ParseError GAPIDecoder::HandleSetStencilTest( +parse_error::ParseError GAPIDecoder::HandleSetStencilTest( uint32 arg_count, const cmd::SetStencilTest& args) { Uint32 arg0 = args.stencil_args0; @@ -836,7 +836,7 @@ BufferSyncInterface::ParseError GAPIDecoder::HandleSetStencilTest( if (cmd::SetStencilTest::Unused0::Get(arg0) != 0 || cmd::SetStencilTest::Unused1::Get(arg1) != 0 || cmd::SetStencilTest::Unused2::Get(arg1) != 0) - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; unsigned int write_mask = cmd::SetStencilTest::WriteMask::Get(arg0); unsigned int compare_mask = cmd::SetStencilTest::CompareMask::Get(arg0); unsigned int ref = cmd::SetStencilTest::ReferenceValue::Get(arg0); @@ -844,25 +844,25 @@ BufferSyncInterface::ParseError GAPIDecoder::HandleSetStencilTest( bool separate_ccw = cmd::SetStencilTest::SeparateCCW::Get(arg0) != 0; gapi_->SetStencilTest(enable, separate_ccw, write_mask, compare_mask, ref, arg1); - return BufferSyncInterface::kParseNoError; + return parse_error::kParseNoError; } -BufferSyncInterface::ParseError GAPIDecoder::HandleSetColorWrite( +parse_error::ParseError GAPIDecoder::HandleSetColorWrite( uint32 arg_count, const cmd::SetColorWrite& args) { Uint32 enables = args.flags; if (cmd::SetColorWrite::Unused::Get(enables) != 0) - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; bool red = cmd::SetColorWrite::RedMask::Get(enables) != 0; bool green = cmd::SetColorWrite::GreenMask::Get(enables) != 0; bool blue = cmd::SetColorWrite::BlueMask::Get(enables) != 0; bool alpha = cmd::SetColorWrite::AlphaMask::Get(enables) != 0; bool dither = cmd::SetColorWrite::DitherEnable::Get(enables) != 0; gapi_->SetColorWrite(red, green, blue, alpha, dither); - return BufferSyncInterface::kParseNoError; + return parse_error::kParseNoError; } -BufferSyncInterface::ParseError GAPIDecoder::HandleSetBlending( +parse_error::ParseError GAPIDecoder::HandleSetBlending( uint32 arg_count, const cmd::SetBlending& args) { Uint32 arg = args.blend_settings; @@ -882,7 +882,7 @@ BufferSyncInterface::ParseError GAPIDecoder::HandleSetBlending( alpha_eq >= command_buffer::kNumBlendEq || alpha_src >= command_buffer::kNumBlendFunc || alpha_dst >= command_buffer::kNumBlendFunc) - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; gapi_->SetBlending(enable, separate_alpha, static_cast<command_buffer::BlendEq>(color_eq), @@ -891,10 +891,10 @@ BufferSyncInterface::ParseError GAPIDecoder::HandleSetBlending( static_cast<command_buffer::BlendEq>(alpha_eq), static_cast<command_buffer::BlendFunc>(alpha_src), static_cast<command_buffer::BlendFunc>(alpha_dst)); - return BufferSyncInterface::kParseNoError; + return parse_error::kParseNoError; } -BufferSyncInterface::ParseError GAPIDecoder::HandleSetBlendingColor( +parse_error::ParseError GAPIDecoder::HandleSetBlendingColor( uint32 arg_count, const cmd::SetBlendingColor& args) { RGBA rgba; @@ -903,10 +903,10 @@ BufferSyncInterface::ParseError GAPIDecoder::HandleSetBlendingColor( rgba.blue = args.blue; rgba.alpha = args.alpha; gapi_->SetBlendingColor(rgba); - return BufferSyncInterface::kParseNoError; + return parse_error::kParseNoError; } -BufferSyncInterface::ParseError GAPIDecoder::HandleCreateRenderSurface( +parse_error::ParseError GAPIDecoder::HandleCreateRenderSurface( uint32 arg_count, const cmd::CreateRenderSurface& args) { unsigned int width_height = args.width_height; @@ -920,13 +920,13 @@ BufferSyncInterface::ParseError GAPIDecoder::HandleCreateRenderSurface( side, args.texture_id); } -BufferSyncInterface::ParseError GAPIDecoder::HandleDestroyRenderSurface( +parse_error::ParseError GAPIDecoder::HandleDestroyRenderSurface( uint32 arg_count, const cmd::DestroyRenderSurface& args) { return gapi_->DestroyRenderSurface(args.render_surface_id); } -BufferSyncInterface::ParseError GAPIDecoder::HandleCreateDepthSurface( +parse_error::ParseError GAPIDecoder::HandleCreateDepthSurface( uint32 arg_count, const cmd::CreateDepthSurface& args) { unsigned int width_height = args.width_height; @@ -935,23 +935,23 @@ BufferSyncInterface::ParseError GAPIDecoder::HandleCreateDepthSurface( return gapi_->CreateDepthSurface(args.depth_surface_id, width, height); } -BufferSyncInterface::ParseError GAPIDecoder::HandleDestroyDepthSurface( +parse_error::ParseError GAPIDecoder::HandleDestroyDepthSurface( uint32 arg_count, const cmd::DestroyDepthSurface& args) { return gapi_->DestroyDepthSurface(args.depth_surface_id); } -BufferSyncInterface::ParseError GAPIDecoder::HandleSetRenderSurface( +parse_error::ParseError GAPIDecoder::HandleSetRenderSurface( uint32 arg_count, const cmd::SetRenderSurface& args) { return gapi_->SetRenderSurface(args.render_surface_id, args.depth_surface_id); } -BufferSyncInterface::ParseError GAPIDecoder::HandleSetBackSurfaces( +parse_error::ParseError GAPIDecoder::HandleSetBackSurfaces( uint32 arg_count, const cmd::SetBackSurfaces& args) { gapi_->SetBackSurfaces(); - return BufferSyncInterface::kParseNoError; + return parse_error::kParseNoError; } } // namespace command_buffer diff --git a/o3d/command_buffer/service/cross/gapi_decoder.h b/o3d/command_buffer/service/cross/gapi_decoder.h index 8779cf2..08555eb 100644 --- a/o3d/command_buffer/service/cross/gapi_decoder.h +++ b/o3d/command_buffer/service/cross/gapi_decoder.h @@ -42,13 +42,13 @@ namespace o3d { namespace command_buffer { class GAPIInterface; -class CommandBufferUpcallInterface; +class CommandBufferEngine; // This class implements the AsyncAPIInterface interface, decoding GAPI // commands and sending them to a GAPI interface. class GAPIDecoder : public AsyncAPIInterface { public: - typedef BufferSyncInterface::ParseError ParseError; + typedef parse_error::ParseError ParseError; explicit GAPIDecoder(GAPIInterface *gapi) : gapi_(gapi), engine_(NULL) {} virtual ~GAPIDecoder() {} @@ -60,7 +60,7 @@ class GAPIDecoder : public AsyncAPIInterface { // Sets the engine, to get shared memory buffers from, and to set the token // to. - void set_engine(CommandBufferUpcallInterface *engine) { engine_ = engine; } + void set_engine(CommandBufferEngine *engine) { engine_ = engine; } private: // Gets the address of shared memory data, given a shared memory ID and an // offset. Also checks that the size is consistent with the shared memory @@ -88,7 +88,7 @@ class GAPIDecoder : public AsyncAPIInterface { #undef O3D_COMMAND_BUFFER_CMD_OP GAPIInterface *gapi_; - CommandBufferUpcallInterface *engine_; + CommandBufferEngine *engine_; }; } // namespace command_buffer diff --git a/o3d/command_buffer/service/cross/gl/effect_gl.cc b/o3d/command_buffer/service/cross/gl/effect_gl.cc index 21c0e04..2d24f7b 100644 --- a/o3d/command_buffer/service/cross/gl/effect_gl.cc +++ b/o3d/command_buffer/service/cross/gl/effect_gl.cc @@ -706,7 +706,7 @@ EffectParamGL *EffectGL::CreateParamByName(const char *name) { return EffectParamGL::Create(this, index); } -BufferSyncInterface::ParseError GAPIGL::CreateEffect(ResourceId id, +parse_error::ParseError GAPIGL::CreateEffect(ResourceId id, unsigned int size, const void *data) { if (id == current_effect_id_) DirtyEffect(); @@ -721,109 +721,109 @@ BufferSyncInterface::ParseError GAPIGL::CreateEffect(ResourceId id, &vertex_program_entry, &fragment_program_entry, &effect_code)) { - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; } EffectGL * effect = EffectGL::Create(this, effect_code, vertex_program_entry, fragment_program_entry); - if (!effect) return BufferSyncInterface::kParseInvalidArguments; + if (!effect) return parse_error::kParseInvalidArguments; effects_.Assign(id, effect); - return BufferSyncInterface::kParseNoError; + return parse_error::kParseNoError; } -BufferSyncInterface::ParseError GAPIGL::DestroyEffect(ResourceId id) { +parse_error::ParseError GAPIGL::DestroyEffect(ResourceId id) { if (id == current_effect_id_) DirtyEffect(); return effects_.Destroy(id) ? - BufferSyncInterface::kParseNoError : - BufferSyncInterface::kParseInvalidArguments; + parse_error::kParseNoError : + parse_error::kParseInvalidArguments; } -BufferSyncInterface::ParseError GAPIGL::SetEffect(ResourceId id) { +parse_error::ParseError GAPIGL::SetEffect(ResourceId id) { DirtyEffect(); current_effect_id_ = id; - return BufferSyncInterface::kParseNoError; + return parse_error::kParseNoError; } -BufferSyncInterface::ParseError GAPIGL::GetParamCount(ResourceId id, +parse_error::ParseError GAPIGL::GetParamCount(ResourceId id, unsigned int size, void *data) { EffectGL *effect = effects_.Get(id); if (!effect || size < sizeof(Uint32)) // NOLINT - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; *static_cast<Uint32 *>(data) = effect->GetParamCount(); - return BufferSyncInterface::kParseNoError; + return parse_error::kParseNoError; } -BufferSyncInterface::ParseError GAPIGL::CreateParam(ResourceId param_id, +parse_error::ParseError GAPIGL::CreateParam(ResourceId param_id, ResourceId effect_id, unsigned int index) { EffectGL *effect = effects_.Get(effect_id); - if (!effect) return BufferSyncInterface::kParseInvalidArguments; + if (!effect) return parse_error::kParseInvalidArguments; EffectParamGL *param = effect->CreateParam(index); - if (!param) return BufferSyncInterface::kParseInvalidArguments; + if (!param) return parse_error::kParseInvalidArguments; effect_params_.Assign(param_id, param); - return BufferSyncInterface::kParseNoError; + return parse_error::kParseNoError; } -BufferSyncInterface::ParseError GAPIGL::CreateParamByName(ResourceId param_id, +parse_error::ParseError GAPIGL::CreateParamByName(ResourceId param_id, ResourceId effect_id, unsigned int size, const void *name) { EffectGL *effect = effects_.Get(effect_id); - if (!effect) return BufferSyncInterface::kParseInvalidArguments; + if (!effect) return parse_error::kParseInvalidArguments; std::string string_name(static_cast<const char *>(name), size); EffectParamGL *param = effect->CreateParamByName(string_name.c_str()); - if (!param) return BufferSyncInterface::kParseInvalidArguments; + if (!param) return parse_error::kParseInvalidArguments; effect_params_.Assign(param_id, param); - return BufferSyncInterface::kParseNoError; + return parse_error::kParseNoError; } -BufferSyncInterface::ParseError GAPIGL::DestroyParam(ResourceId id) { +parse_error::ParseError GAPIGL::DestroyParam(ResourceId id) { return effect_params_.Destroy(id) ? - BufferSyncInterface::kParseNoError : - BufferSyncInterface::kParseInvalidArguments; + parse_error::kParseNoError : + parse_error::kParseInvalidArguments; } -BufferSyncInterface::ParseError GAPIGL::SetParamData(ResourceId id, +parse_error::ParseError GAPIGL::SetParamData(ResourceId id, unsigned int size, const void *data) { EffectParamGL *param = effect_params_.Get(id); - if (!param) return BufferSyncInterface::kParseInvalidArguments; + if (!param) return parse_error::kParseInvalidArguments; return param->SetData(this, size, data) ? - BufferSyncInterface::kParseNoError : - BufferSyncInterface::kParseInvalidArguments; + parse_error::kParseNoError : + parse_error::kParseInvalidArguments; } -BufferSyncInterface::ParseError GAPIGL::GetParamDesc(ResourceId id, +parse_error::ParseError GAPIGL::GetParamDesc(ResourceId id, unsigned int size, void *data) { EffectParamGL *param = effect_params_.Get(id); - if (!param) return BufferSyncInterface::kParseInvalidArguments; + if (!param) return parse_error::kParseInvalidArguments; return param->GetDesc(size, data) ? - BufferSyncInterface::kParseNoError : - BufferSyncInterface::kParseInvalidArguments; + parse_error::kParseNoError : + parse_error::kParseInvalidArguments; } -BufferSyncInterface::ParseError GAPIGL::GetStreamCount( +parse_error::ParseError GAPIGL::GetStreamCount( ResourceId id, unsigned int size, void *data) { EffectGL *effect = effects_.Get(id); if (!effect || size < sizeof(Uint32)) // NOLINT - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; *static_cast<Uint32 *>(data) = effect->GetStreamCount(); - return BufferSyncInterface::kParseNoError; + return parse_error::kParseNoError; } -BufferSyncInterface::ParseError GAPIGL::GetStreamDesc(ResourceId id, +parse_error::ParseError GAPIGL::GetStreamDesc(ResourceId id, unsigned int index, unsigned int size, void *data) { EffectGL *effect = effects_.Get(id); - if (!effect) return BufferSyncInterface::kParseInvalidArguments; + if (!effect) return parse_error::kParseInvalidArguments; return effect->GetStreamDesc(index, size, data) ? - BufferSyncInterface::kParseNoError : - BufferSyncInterface::kParseInvalidArguments; + parse_error::kParseNoError : + parse_error::kParseInvalidArguments; } // If the current effect is valid, call End on it, and tag for revalidation. diff --git a/o3d/command_buffer/service/cross/gl/geometry_gl.cc b/o3d/command_buffer/service/cross/gl/geometry_gl.cc index b290472..47604f1 100644 --- a/o3d/command_buffer/service/cross/gl/geometry_gl.cc +++ b/o3d/command_buffer/service/cross/gl/geometry_gl.cc @@ -305,97 +305,97 @@ void VertexStructGL::Compile() { dirty_ = false; } -BufferSyncInterface::ParseError GAPIGL::CreateVertexBuffer(ResourceId id, +parse_error::ParseError GAPIGL::CreateVertexBuffer(ResourceId id, unsigned int size, unsigned int flags) { VertexBufferGL *vertex_buffer = new VertexBufferGL(size, flags); vertex_buffer->Create(); vertex_buffers_.Assign(id, vertex_buffer); - return BufferSyncInterface::kParseNoError; + return parse_error::kParseNoError; } -BufferSyncInterface::ParseError GAPIGL::DestroyVertexBuffer(ResourceId id) { +parse_error::ParseError GAPIGL::DestroyVertexBuffer(ResourceId id) { return vertex_buffers_.Destroy(id) ? - BufferSyncInterface::kParseNoError : - BufferSyncInterface::kParseInvalidArguments; + parse_error::kParseNoError : + parse_error::kParseInvalidArguments; } -BufferSyncInterface::ParseError GAPIGL::SetVertexBufferData(ResourceId id, +parse_error::ParseError GAPIGL::SetVertexBufferData(ResourceId id, unsigned int offset, unsigned int size, const void *data) { VertexBufferGL *vertex_buffer = vertex_buffers_.Get(id); - if (!vertex_buffer) return BufferSyncInterface::kParseInvalidArguments; + if (!vertex_buffer) return parse_error::kParseInvalidArguments; return vertex_buffer->SetData(offset, size, data) ? - BufferSyncInterface::kParseNoError : - BufferSyncInterface::kParseInvalidArguments; + parse_error::kParseNoError : + parse_error::kParseInvalidArguments; } -BufferSyncInterface::ParseError GAPIGL::GetVertexBufferData(ResourceId id, +parse_error::ParseError GAPIGL::GetVertexBufferData(ResourceId id, unsigned int offset, unsigned int size, void *data) { VertexBufferGL *vertex_buffer = vertex_buffers_.Get(id); - if (!vertex_buffer) return BufferSyncInterface::kParseInvalidArguments; + if (!vertex_buffer) return parse_error::kParseInvalidArguments; return vertex_buffer->GetData(offset, size, data) ? - BufferSyncInterface::kParseNoError : - BufferSyncInterface::kParseInvalidArguments; + parse_error::kParseNoError : + parse_error::kParseInvalidArguments; } -BufferSyncInterface::ParseError GAPIGL::CreateIndexBuffer(ResourceId id, +parse_error::ParseError GAPIGL::CreateIndexBuffer(ResourceId id, unsigned int size, unsigned int flags) { IndexBufferGL *index_buffer = new IndexBufferGL(size, flags); index_buffer->Create(); index_buffers_.Assign(id, index_buffer); - return BufferSyncInterface::kParseNoError; + return parse_error::kParseNoError; } -BufferSyncInterface::ParseError GAPIGL::DestroyIndexBuffer(ResourceId id) { +parse_error::ParseError GAPIGL::DestroyIndexBuffer(ResourceId id) { return index_buffers_.Destroy(id) ? - BufferSyncInterface::kParseNoError : - BufferSyncInterface::kParseInvalidArguments; + parse_error::kParseNoError : + parse_error::kParseInvalidArguments; } -BufferSyncInterface::ParseError GAPIGL::SetIndexBufferData(ResourceId id, +parse_error::ParseError GAPIGL::SetIndexBufferData(ResourceId id, unsigned int offset, unsigned int size, const void *data) { IndexBufferGL *index_buffer = index_buffers_.Get(id); - if (!index_buffer) return BufferSyncInterface::kParseInvalidArguments; + if (!index_buffer) return parse_error::kParseInvalidArguments; return index_buffer->SetData(offset, size, data) ? - BufferSyncInterface::kParseNoError : - BufferSyncInterface::kParseInvalidArguments; + parse_error::kParseNoError : + parse_error::kParseInvalidArguments; } -BufferSyncInterface::ParseError GAPIGL::GetIndexBufferData(ResourceId id, +parse_error::ParseError GAPIGL::GetIndexBufferData(ResourceId id, unsigned int offset, unsigned int size, void *data) { IndexBufferGL *index_buffer = index_buffers_.Get(id); - if (!index_buffer) return BufferSyncInterface::kParseInvalidArguments; + if (!index_buffer) return parse_error::kParseInvalidArguments; return index_buffer->GetData(offset, size, data) ? - BufferSyncInterface::kParseNoError : - BufferSyncInterface::kParseInvalidArguments; + parse_error::kParseNoError : + parse_error::kParseInvalidArguments; } -BufferSyncInterface::ParseError GAPIGL::CreateVertexStruct( +parse_error::ParseError GAPIGL::CreateVertexStruct( ResourceId id, unsigned int input_count) { if (id == current_vertex_struct_) validate_streams_ = true; VertexStructGL *vertex_struct = new VertexStructGL(input_count); vertex_structs_.Assign(id, vertex_struct); - return BufferSyncInterface::kParseNoError; + return parse_error::kParseNoError; } -BufferSyncInterface::ParseError GAPIGL::DestroyVertexStruct(ResourceId id) { +parse_error::ParseError GAPIGL::DestroyVertexStruct(ResourceId id) { if (id == current_vertex_struct_) validate_streams_ = true; return vertex_structs_.Destroy(id) ? - BufferSyncInterface::kParseNoError : - BufferSyncInterface::kParseInvalidArguments; + parse_error::kParseNoError : + parse_error::kParseInvalidArguments; } -BufferSyncInterface::ParseError GAPIGL::SetVertexInput( +parse_error::ParseError GAPIGL::SetVertexInput( ResourceId vertex_struct_id, unsigned int input_index, ResourceId vertex_buffer_id, @@ -407,22 +407,22 @@ BufferSyncInterface::ParseError GAPIGL::SetVertexInput( switch (semantic) { case vertex_struct::kPosition: if (semantic_index != 0) { - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; } break; case vertex_struct::kNormal: if (semantic_index != 0) { - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; } break; case vertex_struct::kColor: if (semantic_index >= 2) { - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; } break; case vertex_struct::kTexCoord: if (semantic_index >= 8) { - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; } break; default: @@ -432,16 +432,16 @@ BufferSyncInterface::ParseError GAPIGL::SetVertexInput( if (vertex_buffer_id == current_vertex_struct_) validate_streams_ = true; VertexStructGL *vertex_struct = vertex_structs_.Get(vertex_struct_id); if (!vertex_struct || input_index >= vertex_struct->count()) - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; vertex_struct->SetInput(input_index, vertex_buffer_id, offset, stride, type, semantic, semantic_index); - return BufferSyncInterface::kParseNoError; + return parse_error::kParseNoError; } -BufferSyncInterface::ParseError GAPIGL::SetVertexStruct(ResourceId id) { +parse_error::ParseError GAPIGL::SetVertexStruct(ResourceId id) { current_vertex_struct_ = id; validate_streams_ = true; - return BufferSyncInterface::kParseNoError; + return parse_error::kParseNoError; } bool GAPIGL::ValidateStreams() { @@ -493,27 +493,27 @@ void PrimitiveTypeToGL(command_buffer::PrimitiveType primitive_type, } // anonymous namespace -BufferSyncInterface::ParseError GAPIGL::Draw(PrimitiveType primitive_type, +parse_error::ParseError GAPIGL::Draw(PrimitiveType primitive_type, unsigned int first, unsigned int count) { if (validate_effect_ && !ValidateEffect()) { - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; } DCHECK(current_effect_); if (validate_streams_ && !ValidateStreams()) { - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; } GLenum gl_mode = GL_POINTS; PrimitiveTypeToGL(primitive_type, &gl_mode, &count); if (first + count > max_vertices_) { - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; } glDrawArrays(gl_mode, first, count); CHECK_GL_ERROR(); - return BufferSyncInterface::kParseNoError; + return parse_error::kParseNoError; } -BufferSyncInterface::ParseError GAPIGL::DrawIndexed( +parse_error::ParseError GAPIGL::DrawIndexed( PrimitiveType primitive_type, ResourceId index_buffer_id, unsigned int first, @@ -521,16 +521,16 @@ BufferSyncInterface::ParseError GAPIGL::DrawIndexed( unsigned int min_index, unsigned int max_index) { IndexBufferGL *index_buffer = index_buffers_.Get(index_buffer_id); - if (!index_buffer) return BufferSyncInterface::kParseInvalidArguments; + if (!index_buffer) return parse_error::kParseInvalidArguments; if (validate_effect_ && !ValidateEffect()) { - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; } DCHECK(current_effect_); if (validate_streams_ && !ValidateStreams()) { - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; } if ((min_index >= max_vertices_) || (max_index > max_vertices_)) { - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; } GLenum gl_mode = GL_POINTS; PrimitiveTypeToGL(primitive_type, &gl_mode, &count); @@ -541,12 +541,12 @@ BufferSyncInterface::ParseError GAPIGL::DrawIndexed( sizeof(GLuint) : sizeof(GLushort); // NOLINT GLuint offset = first * index_size; if (offset + count * index_size > index_buffer->size()) { - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; } glDrawRangeElements(gl_mode, min_index, max_index, count, index_type, OffsetToPtr(offset)); CHECK_GL_ERROR(); - return BufferSyncInterface::kParseNoError; + return parse_error::kParseNoError; } } // namespace command_buffer diff --git a/o3d/command_buffer/service/cross/gl/render_surface_gl.cc b/o3d/command_buffer/service/cross/gl/render_surface_gl.cc index c7ed2d7..35634ff 100644 --- a/o3d/command_buffer/service/cross/gl/render_surface_gl.cc +++ b/o3d/command_buffer/service/cross/gl/render_surface_gl.cc @@ -109,7 +109,7 @@ RenderDepthStencilSurfaceGL* RenderDepthStencilSurfaceGL::Create( } // Copies the data from a texture resource. -BufferSyncInterface::ParseError GAPIGL::CreateRenderSurface( +parse_error::ParseError GAPIGL::CreateRenderSurface( ResourceId id, unsigned int width, unsigned int height, @@ -118,11 +118,11 @@ BufferSyncInterface::ParseError GAPIGL::CreateRenderSurface( ResourceId texture_id) { if (id == current_surface_id_) { // This will delete the current surface which would be bad. - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; } TextureGL *texture = textures_.Get(texture_id); if (!texture->render_surfaces_enabled()) { - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; } else { RenderSurfaceGL* render_surface = RenderSurfaceGL::Create(width, height, @@ -130,46 +130,46 @@ BufferSyncInterface::ParseError GAPIGL::CreateRenderSurface( side, texture); if (render_surface == NULL) { - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; } render_surfaces_.Assign(id, render_surface); } - return BufferSyncInterface::kParseNoError; + return parse_error::kParseNoError; } -BufferSyncInterface::ParseError GAPIGL::DestroyRenderSurface(ResourceId id) { +parse_error::ParseError GAPIGL::DestroyRenderSurface(ResourceId id) { if (id == current_surface_id_) { - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; } return render_surfaces_.Destroy(id) ? - BufferSyncInterface::kParseNoError : - BufferSyncInterface::kParseInvalidArguments; + parse_error::kParseNoError : + parse_error::kParseInvalidArguments; } -BufferSyncInterface::ParseError GAPIGL::CreateDepthSurface( +parse_error::ParseError GAPIGL::CreateDepthSurface( ResourceId id, unsigned int width, unsigned int height) { if (id == current_depth_surface_id_) { // This will delete the current surface which would be bad. - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; } RenderDepthStencilSurfaceGL* depth_surface = RenderDepthStencilSurfaceGL::Create(width, height); if (depth_surface == NULL) { - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; } depth_surfaces_.Assign(id, depth_surface); - return BufferSyncInterface::kParseNoError; + return parse_error::kParseNoError; } -BufferSyncInterface::ParseError GAPIGL::DestroyDepthSurface(ResourceId id) { +parse_error::ParseError GAPIGL::DestroyDepthSurface(ResourceId id) { if (id == current_depth_surface_id_) { - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; } return depth_surfaces_.Destroy(id) ? - BufferSyncInterface::kParseNoError : - BufferSyncInterface::kParseInvalidArguments; + parse_error::kParseNoError : + parse_error::kParseInvalidArguments; } void ResetBoundAttachments() { @@ -219,12 +219,12 @@ bool BindDepthStencilBuffer(const RenderDepthStencilSurfaceGL* gl_surface) { return true; } -BufferSyncInterface::ParseError GAPIGL::SetRenderSurface( +parse_error::ParseError GAPIGL::SetRenderSurface( ResourceId render_surface_id, ResourceId depth_stencil_id) { if (render_surfaces_.Get(render_surface_id) == NULL && depth_surfaces_.Get(depth_stencil_id) == NULL) { - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; } ::glBindFramebufferEXT(GL_FRAMEBUFFER, render_surface_framebuffer_); @@ -237,7 +237,7 @@ BufferSyncInterface::ParseError GAPIGL::SetRenderSurface( if (!render_surface->texture()-> InstallFrameBufferObjects(render_surface) || !BindDepthStencilBuffer(depth_surface)) { - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; } // RenderSurface rendering is performed with an inverted Y, so the front @@ -247,7 +247,7 @@ BufferSyncInterface::ParseError GAPIGL::SetRenderSurface( current_surface_id_ = render_surface_id; current_depth_surface_id_ = depth_stencil_id; - return BufferSyncInterface::kParseNoError; + return parse_error::kParseNoError; } void GAPIGL::SetBackSurfaces() { diff --git a/o3d/command_buffer/service/cross/gl/sampler_gl.cc b/o3d/command_buffer/service/cross/gl/sampler_gl.cc index 159e131..7f09a4e 100644 --- a/o3d/command_buffer/service/cross/gl/sampler_gl.cc +++ b/o3d/command_buffer/service/cross/gl/sampler_gl.cc @@ -173,24 +173,24 @@ void SamplerGL::SetBorderColor(const RGBA &color) { gl_border_color_[3] = color.alpha; } -BufferSyncInterface::ParseError GAPIGL::CreateSampler( +parse_error::ParseError GAPIGL::CreateSampler( ResourceId id) { // Dirty effect, because this sampler id may be used. DirtyEffect(); samplers_.Assign(id, new SamplerGL()); - return BufferSyncInterface::kParseNoError; + return parse_error::kParseNoError; } // Destroys the Sampler resource. -BufferSyncInterface::ParseError GAPIGL::DestroySampler(ResourceId id) { +parse_error::ParseError GAPIGL::DestroySampler(ResourceId id) { // Dirty effect, because this sampler id may be used. DirtyEffect(); return samplers_.Destroy(id) ? - BufferSyncInterface::kParseNoError : - BufferSyncInterface::kParseInvalidArguments; + parse_error::kParseNoError : + parse_error::kParseInvalidArguments; } -BufferSyncInterface::ParseError GAPIGL::SetSamplerStates( +parse_error::ParseError GAPIGL::SetSamplerStates( ResourceId id, sampler::AddressingMode addressing_u, sampler::AddressingMode addressing_v, @@ -201,36 +201,36 @@ BufferSyncInterface::ParseError GAPIGL::SetSamplerStates( unsigned int max_anisotropy) { SamplerGL *sampler = samplers_.Get(id); if (!sampler) - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; // Dirty effect, because this sampler id may be used. DirtyEffect(); sampler->SetStates(addressing_u, addressing_v, addressing_w, mag_filter, min_filter, mip_filter, max_anisotropy); - return BufferSyncInterface::kParseNoError; + return parse_error::kParseNoError; } -BufferSyncInterface::ParseError GAPIGL::SetSamplerBorderColor( +parse_error::ParseError GAPIGL::SetSamplerBorderColor( ResourceId id, const RGBA &color) { SamplerGL *sampler = samplers_.Get(id); if (!sampler) - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; // Dirty effect, because this sampler id may be used. DirtyEffect(); sampler->SetBorderColor(color); - return BufferSyncInterface::kParseNoError; + return parse_error::kParseNoError; } -BufferSyncInterface::ParseError GAPIGL::SetSamplerTexture( +parse_error::ParseError GAPIGL::SetSamplerTexture( ResourceId id, ResourceId texture_id) { SamplerGL *sampler = samplers_.Get(id); if (!sampler) - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; // Dirty effect, because this sampler id may be used. DirtyEffect(); sampler->SetTexture(texture_id); - return BufferSyncInterface::kParseNoError; + return parse_error::kParseNoError; } diff --git a/o3d/command_buffer/service/cross/gl/texture_gl.cc b/o3d/command_buffer/service/cross/gl/texture_gl.cc index 2b01e48..6a92048 100644 --- a/o3d/command_buffer/service/cross/gl/texture_gl.cc +++ b/o3d/command_buffer/service/cross/gl/texture_gl.cc @@ -646,16 +646,16 @@ bool TextureCubeGL::InstallFrameBufferObjects( // GAPIGL functions. // Destroys a texture resource. -BufferSyncInterface::ParseError GAPIGL::DestroyTexture(ResourceId id) { +parse_error::ParseError GAPIGL::DestroyTexture(ResourceId id) { // Dirty effect, because this texture id may be used. DirtyEffect(); return textures_.Destroy(id) ? - BufferSyncInterface::kParseNoError : - BufferSyncInterface::kParseInvalidArguments; + parse_error::kParseNoError : + parse_error::kParseInvalidArguments; } // Creates a 2D texture resource. -BufferSyncInterface::ParseError GAPIGL::CreateTexture2D( +parse_error::ParseError GAPIGL::CreateTexture2D( ResourceId id, unsigned int width, unsigned int height, @@ -665,15 +665,15 @@ BufferSyncInterface::ParseError GAPIGL::CreateTexture2D( bool enable_render_surfaces) { Texture2DGL *texture = Texture2DGL::Create( width, height, levels, format, flags, enable_render_surfaces); - if (!texture) return BufferSyncInterface::kParseInvalidArguments; + if (!texture) return parse_error::kParseInvalidArguments; // Dirty effect, because this texture id may be used. DirtyEffect(); textures_.Assign(id, texture); - return BufferSyncInterface::kParseNoError; + return parse_error::kParseNoError; } // Creates a 3D texture resource. -BufferSyncInterface::ParseError GAPIGL::CreateTexture3D( +parse_error::ParseError GAPIGL::CreateTexture3D( ResourceId id, unsigned int width, unsigned int height, @@ -684,15 +684,15 @@ BufferSyncInterface::ParseError GAPIGL::CreateTexture3D( bool enable_render_surfaces) { Texture3DGL *texture = Texture3DGL::Create( width, height, depth, levels, format, flags, enable_render_surfaces); - if (!texture) return BufferSyncInterface::kParseInvalidArguments; + if (!texture) return parse_error::kParseInvalidArguments; // Dirty effect, because this texture id may be used. DirtyEffect(); textures_.Assign(id, texture); - return BufferSyncInterface::kParseNoError; + return parse_error::kParseNoError; } // Creates a cube map texture resource. -BufferSyncInterface::ParseError GAPIGL::CreateTextureCube( +parse_error::ParseError GAPIGL::CreateTextureCube( ResourceId id, unsigned int side, unsigned int levels, @@ -701,15 +701,15 @@ BufferSyncInterface::ParseError GAPIGL::CreateTextureCube( bool enable_render_surfaces) { TextureCubeGL *texture = TextureCubeGL::Create( side, levels, format, flags, enable_render_surfaces); - if (!texture) return BufferSyncInterface::kParseInvalidArguments; + if (!texture) return parse_error::kParseInvalidArguments; // Dirty effect, because this texture id may be used. DirtyEffect(); textures_.Assign(id, texture); - return BufferSyncInterface::kParseNoError; + return parse_error::kParseNoError; } // Copies the data into a texture resource. -BufferSyncInterface::ParseError GAPIGL::SetTextureData( +parse_error::ParseError GAPIGL::SetTextureData( ResourceId id, unsigned int x, unsigned int y, @@ -725,19 +725,19 @@ BufferSyncInterface::ParseError GAPIGL::SetTextureData( const void *data) { TextureGL *texture = textures_.Get(id); if (!texture) - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; Volume volume = {x, y, z, width, height, depth}; // Dirty effect: SetData may need to call glBindTexture which will mess up the // sampler parameters. DirtyEffect(); return texture->SetData(volume, level, face, row_pitch, slice_pitch, size, data) ? - BufferSyncInterface::kParseNoError : - BufferSyncInterface::kParseInvalidArguments; + parse_error::kParseNoError : + parse_error::kParseInvalidArguments; } // Copies the data from a texture resource. -BufferSyncInterface::ParseError GAPIGL::GetTextureData( +parse_error::ParseError GAPIGL::GetTextureData( ResourceId id, unsigned int x, unsigned int y, @@ -753,15 +753,15 @@ BufferSyncInterface::ParseError GAPIGL::GetTextureData( void *data) { TextureGL *texture = textures_.Get(id); if (!texture) - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; Volume volume = {x, y, z, width, height, depth}; // Dirty effect: GetData may need to call glBindTexture which will mess up the // sampler parameters. DirtyEffect(); return texture->GetData(volume, level, face, row_pitch, slice_pitch, size, data) ? - BufferSyncInterface::kParseNoError : - BufferSyncInterface::kParseInvalidArguments; + parse_error::kParseNoError : + parse_error::kParseInvalidArguments; } } // namespace command_buffer diff --git a/o3d/command_buffer/service/cross/mocks.h b/o3d/command_buffer/service/cross/mocks.h index 3135249..abacb5b 100644 --- a/o3d/command_buffer/service/cross/mocks.h +++ b/o3d/command_buffer/service/cross/mocks.h @@ -51,8 +51,8 @@ namespace command_buffer { class AsyncAPIMock : public AsyncAPIInterface { public: AsyncAPIMock() { - testing::DefaultValue<BufferSyncInterface::ParseError>::Set( - BufferSyncInterface::kParseNoError); + testing::DefaultValue<parse_error::ParseError>::Set( + parse_error::kParseNoError); } // Predicate that matches args passed to DoCommand, by looking at the values. @@ -77,7 +77,7 @@ class AsyncAPIMock : public AsyncAPIInterface { CommandBufferEntry *args_; }; - MOCK_METHOD3(DoCommand, BufferSyncInterface::ParseError( + MOCK_METHOD3(DoCommand, parse_error::ParseError( unsigned int command, unsigned int arg_count, const void* cmd_data)); @@ -100,55 +100,6 @@ class AsyncAPIMock : public AsyncAPIInterface { CommandBufferEngine *engine_; }; -class RPCProcessMock : public RPCProcessInterface { - public: - RPCProcessMock() - : would_have_blocked_(false), - message_count_(0) { - ON_CALL(*this, ProcessMessage()).WillByDefault( - testing::Invoke(this, &RPCProcessMock::DefaultProcessMessage)); - ON_CALL(*this, HasMessage()).WillByDefault( - testing::Invoke(this, &RPCProcessMock::DefaultHasMessage)); - } - MOCK_METHOD0(ProcessMessage, bool()); - MOCK_METHOD0(HasMessage, bool()); - - void Reset() { - would_have_blocked_ = false; - message_count_ = 0; - } - - bool DefaultProcessMessage() { - if (message_count_ > 0) { - --message_count_; - } else { - would_have_blocked_ = true; - } - return true; - } - - bool DefaultHasMessage() { - return message_count_ > 0; - } - - bool AddMessage() { - ++message_count_; - return true; - } - - bool would_have_blocked() { return would_have_blocked_; } - void set_would_have_blocked(bool would_have_blocked) { - would_have_blocked_ = would_have_blocked; - } - - unsigned int message_count() { return message_count_; } - void set_message_count(unsigned int count) { message_count_ = count; } - private: - bool would_have_blocked_; - unsigned int message_count_; -}; - - } // namespace command_buffer } // namespace o3d diff --git a/o3d/command_buffer/service/cross/plugin.cc b/o3d/command_buffer/service/cross/plugin.cc deleted file mode 100644 index 1a20dd5..0000000 --- a/o3d/command_buffer/service/cross/plugin.cc +++ /dev/null @@ -1,439 +0,0 @@ -/* - * Copyright 2009, Google Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - - -// This file contains the command renderer service (renderer) plug-in. -// NOTE: this is only implemented on Windows currently. -// TODO: other platforms. - -#include <npupp.h> -#include <build/build_config.h> -#ifdef OS_WIN -#include <windows.h> -#endif - -#include "command_buffer/common/cross/gapi_interface.h" -#include "command_buffer/common/cross/rpc_imc.h" -#include "command_buffer/service/cross/buffer_rpc.h" -#include "command_buffer/service/cross/cmd_buffer_engine.h" -#include "command_buffer/service/cross/gapi_decoder.h" -#ifdef OS_WIN -#include "command_buffer/service/win/d3d9/gapi_d3d9.h" -#endif -#include "third_party/native_client/googleclient/native_client/src/trusted/desc/nrd_all_modules.h" -#include "third_party/nixysa/static_glue/npapi/npn_api.h" - -namespace o3d { -namespace command_buffer { - -// The Plugin class implements the plug-in instance. It derives from NPObject -// to be the scriptable object as well. -class Plugin : public NPObject { - public: - // Sets the window used by the plug-in. - NPError SetWindow(NPWindow *window); - - // Gets the NPClass representing the NPAPI entrypoints to the object. - static NPClass *GetNPClass() { - return &class_; - } - - private: - explicit Plugin(NPP npp); - ~Plugin(); - - // Creates the renderer using the IMC socket. This is called from Javascript - // using the create() function. - void Create(nacl::HtpHandle socket); - - // Destroys the renderer. This is called from Javascript using the destroy() - // function. - void Destroy(); - - // NPAPI bindings. - static NPObject *Allocate(NPP npp, NPClass *npclass); - static void Deallocate(NPObject *object); - static bool HasMethod(NPObject *header, NPIdentifier name); - static bool Invoke(NPObject *header, NPIdentifier name, - const NPVariant *args, uint32_t argCount, - NPVariant *result); - static bool InvokeDefault(NPObject *header, const NPVariant *args, - uint32_t argCount, NPVariant *result); - static bool HasProperty(NPObject *header, NPIdentifier name); - static bool GetProperty(NPObject *header, NPIdentifier name, - NPVariant *variant); - static bool SetProperty(NPObject *header, NPIdentifier name, - const NPVariant *variant); - static bool Enumerate(NPObject *header, NPIdentifier **value, - uint32_t *count); - -#ifdef OS_WIN - static DWORD WINAPI ThreadMain(void *param) { - static_cast<Plugin *>(param)->DoThread(); - return 0; - } -#endif - // Executes the main renderer thread. - void DoThread(); - - NPP npp_; - static NPClass class_; - NPIdentifier create_id_; - NPIdentifier destroy_id_; - NPIdentifier handle_id_; - -#ifdef OS_WIN - HWND hwnd_; - HANDLE thread_; - DWORD thread_id_; -#endif - - nacl::HtpHandle handle_; - scoped_ptr<GAPIInterface> gapi_; -}; - - -Plugin::Plugin(NPP npp) - : npp_(npp), -#ifdef OS_WIN - hwnd_(NULL), - thread_(NULL), - thread_id_(0), -#endif - handle_(nacl::kInvalidHtpHandle) { - const char *names[3] = {"create", "destroy", "handle"}; - NPIdentifier ids[3]; - NPN_GetStringIdentifiers(names, 3, ids); - create_id_ = ids[0]; - destroy_id_ = ids[1]; - handle_id_ = ids[2]; -} - -Plugin::~Plugin() { - if (gapi_.get()) Destroy(); -} - -NPError Plugin::SetWindow(NPWindow *window) { -#ifdef OS_WIN - HWND hWnd = window ? static_cast<HWND>(window->window) : NULL; - hwnd_ = hWnd; - return NPERR_NO_ERROR; -#endif // OS_WIN -} - -// Creates the renderer. This spawns a thread that answers requests (the D3D -// context is created in that other thread, so that we don't need to enable -// multi-threading on it). -void Plugin::Create(nacl::HtpHandle handle) { - if (gapi_.get()) return; - handle_ = handle; -#ifdef CB_SERVICE_D3D9 - if (!hwnd_) return; - GAPID3D9 *gapi_d3d = new GAPID3D9; - gapi_d3d->set_hwnd(hwnd_); - gapi_.reset(gapi_d3d); - // TODO: use chrome/base threads. - thread_ = ::CreateThread(NULL, 0, ThreadMain, this, 0, &thread_id_); -#endif -} - -// Destroys the renderer. This terminates the renderer thread, and waits until -// it is finished. -void Plugin::Destroy() { - if (!gapi_.get()) return; -#ifdef OS_WIN - ::PostThreadMessage(thread_id_, WM_USER, 0, 0); - ::WaitForSingleObject(thread_, INFINITE); - ::CloseHandle(thread_); -#endif - gapi_.reset(NULL); -} - -// Executes the main renderer thread: answers requests, executes commands. -void Plugin::DoThread() { - scoped_ptr<GAPIDecoder> decoder(new GAPIDecoder(gapi_.get())); - scoped_ptr<CommandBufferEngine> engine( - new CommandBufferEngine(decoder.get())); - decoder->set_engine(engine.get()); - - IMCMessageProcessor processor(handle_, engine->rpc_impl()); - engine->set_process_interface(&processor); - IMCSender sender(handle_); - engine->set_client_rpc(&sender); - - gapi_->Initialize(); - while (true) { - bool done = false; -#ifdef OS_WIN - MSG msg; - while (::PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { - ::TranslateMessage(&msg); - ::DispatchMessage(&msg); - if (msg.message == WM_USER) { - done = true; - break; - } - } -#endif - if (done) break; - // NOTE: DoWork will block when there is nothing to do. This can be an - // issue at termination if the browser tries to kill the plug-in before the - // NaCl module, because then this thread won't terminate, and it will block - // the main (browser) thread. Workaround: kill the NaCl module (kill the - // sel_ldr window). - // TODO: Fix this. It needs select()/poll() or a timeout in the - // IMC library, and that doesn't exist currently. We could use non-blocking, - // e.g. HasWork() and sleep if there is nothing to do, but that would - // translate into unacceptable latencies - 10ms per call. - if (!engine->DoWork()) break; - } - gapi_->Destroy(); -} - -NPClass Plugin::class_ = { - NP_CLASS_STRUCT_VERSION, - Plugin::Allocate, - Plugin::Deallocate, - 0, - Plugin::HasMethod, - Plugin::Invoke, - 0, - Plugin::HasProperty, - Plugin::GetProperty, - Plugin::SetProperty, - 0, - Plugin::Enumerate, -}; - -NPObject *Plugin::Allocate(NPP npp, NPClass *npclass) { - return new Plugin(npp); -} - -void Plugin::Deallocate(NPObject *object) { - delete static_cast<Plugin *>(object); -} - -bool Plugin::HasMethod(NPObject *header, NPIdentifier name) { - Plugin *plugin = static_cast<Plugin *>(header); - // 2 methods supported: create(handle) and destroy(). - return (name == plugin->create_id_ || - name == plugin->destroy_id_); -} - -bool Plugin::Invoke(NPObject *header, NPIdentifier name, - const NPVariant *args, uint32_t argCount, - NPVariant *result) { - Plugin *plugin = static_cast<Plugin *>(header); - VOID_TO_NPVARIANT(*result); - if (name == plugin->create_id_ && argCount == 1 && - NPVARIANT_IS_OBJECT(args[0])) { - // create(handle) was called. - // - // Temporary ugly hack: the NPObject is a wrapper around a HtpHandle, but - // to get that handle we need to get the "handle" property on it which is a - // string that represents the address in memory of that HtpHandle. - NPObject *object = NPVARIANT_TO_OBJECT(args[0]); - - NPVariant handle_prop; - bool result = NPN_GetProperty(plugin->npp_, object, plugin->handle_id_, - &handle_prop); - if (!result || !NPVARIANT_IS_STRING(handle_prop)) - return false; - String handle_string(NPVARIANT_TO_STRING(handle_prop).utf8characters, - NPVARIANT_TO_STRING(handle_prop).utf8length); - intptr_t handle_value = strtol(handle_string.c_str(), NULL, 0); - nacl::HtpHandle handle = reinterpret_cast<nacl::HtpHandle>(handle_value); - plugin->Create(handle); - return true; - } else if (name == plugin->destroy_id_ && argCount == 0) { - // destroy() was called. - plugin->Destroy(); - return true; - } else { - return false; - } -} - -bool Plugin::InvokeDefault(NPObject *header, const NPVariant *args, - uint32_t argCount, NPVariant *result) { - return false; -} - -bool Plugin::HasProperty(NPObject *header, NPIdentifier name) { - return false; -} - -bool Plugin::GetProperty(NPObject *header, NPIdentifier name, - NPVariant *variant) { - return false; -} - -bool Plugin::SetProperty(NPObject *header, NPIdentifier name, - const NPVariant *variant) { - return false; -} - -bool Plugin::Enumerate(NPObject *header, NPIdentifier **value, - uint32_t *count) { - Plugin *plugin = static_cast<Plugin *>(header); - *count = 2; - NPIdentifier *ids = static_cast<NPIdentifier *>( - NPN_MemAlloc(*count * sizeof(NPIdentifier))); - ids[0] = plugin->create_id_; - ids[1] = plugin->destroy_id_; - *value = ids; - return true; -} - -} // namespace command_buffer -} // namespace o3d - -using o3d::command_buffer::Plugin; - -extern "C" { -// NPAPI entry points. - -char *NP_GetMIMEDescription(void) { - return "application/vnd.cmdbuf::CommandBuffer MIME"; -} - -NPError OSCALL NP_Initialize(NPNetscapeFuncs *browserFuncs) { - NPError retval = InitializeNPNApi(browserFuncs); - if (retval != NPERR_NO_ERROR) return retval; - return NPERR_NO_ERROR; -} - -NPError OSCALL NP_GetEntryPoints(NPPluginFuncs *pluginFuncs) { - pluginFuncs->version = 11; - pluginFuncs->size = sizeof(pluginFuncs); - pluginFuncs->newp = NPP_New; - pluginFuncs->destroy = NPP_Destroy; - pluginFuncs->setwindow = NPP_SetWindow; - pluginFuncs->newstream = NPP_NewStream; - pluginFuncs->destroystream = NPP_DestroyStream; - pluginFuncs->asfile = NPP_StreamAsFile; - pluginFuncs->writeready = NPP_WriteReady; - pluginFuncs->write = NPP_Write; - pluginFuncs->print = NPP_Print; - pluginFuncs->event = NPP_HandleEvent; - pluginFuncs->urlnotify = NPP_URLNotify; - pluginFuncs->getvalue = NPP_GetValue; - pluginFuncs->setvalue = NPP_SetValue; - - return NPERR_NO_ERROR; -} - -NPError OSCALL NP_Shutdown(void) { - return NPERR_NO_ERROR; -} - -// Creates a plugin instance. -NPError NPP_New(NPMIMEType pluginType, NPP instance, uint16 mode, int16 argc, - char *argn[], char *argv[], NPSavedData *saved) { - NPObject *object = NPN_CreateObject(instance, Plugin::GetNPClass()); - if (object == NULL) { - return NPERR_OUT_OF_MEMORY_ERROR; - } - instance->pdata = object; - return NPERR_NO_ERROR; -} - -// Destroys a plugin instance. -NPError NPP_Destroy(NPP instance, NPSavedData **save) { - Plugin *obj = static_cast<Plugin*>(instance->pdata); - if (obj) { - obj->SetWindow(NULL); - NPN_ReleaseObject(obj); - instance->pdata = NULL; - } - - return NPERR_NO_ERROR; -} - -// Sets the window used by the plugin instance. -NPError NPP_SetWindow(NPP instance, NPWindow *window) { - Plugin *obj = static_cast<Plugin*>(instance->pdata); - obj->SetWindow(window); - return NPERR_NO_ERROR; -} - -// Gets the scriptable object for the plug-in instance. -NPError NPP_GetValue(NPP instance, NPPVariable variable, void *value) { - switch (variable) { - case NPPVpluginScriptableNPObject: { - void **v = static_cast<void **>(value); - Plugin *obj = static_cast<Plugin*>(instance->pdata); - NPN_RetainObject(obj); - *v = obj; - return NPERR_NO_ERROR; - } - default: - break; - } - return NPERR_GENERIC_ERROR; -} - -NPError NPP_NewStream(NPP instance, NPMIMEType type, NPStream *stream, - NPBool seekable, uint16 *stype) { - return NPERR_NO_ERROR; -} - -NPError NPP_DestroyStream(NPP instance, NPStream *stream, NPReason reason) { - return NPERR_NO_ERROR; -} - -int32 NPP_WriteReady(NPP instance, NPStream *stream) { - return 4096; -} - -int32 NPP_Write(NPP instance, NPStream *stream, int32 offset, int32 len, - void *buffer) { - return len; -} - -void NPP_StreamAsFile(NPP instance, NPStream *stream, const char *fname) { -} - -void NPP_Print(NPP instance, NPPrint *platformPrint) { -} - -int16 NPP_HandleEvent(NPP instance, void *event) { - return 0; -} - -void NPP_URLNotify(NPP instance, const char *url, NPReason reason, - void *notifyData) { -} - -NPError NPP_SetValue(NPP instance, NPNVariable variable, void *value) { - return NPERR_GENERIC_ERROR; -} -} // extern "C" diff --git a/o3d/command_buffer/service/win/big_test_main.cc b/o3d/command_buffer/service/win/big_test_main.cc deleted file mode 100644 index a88dc2d..0000000 --- a/o3d/command_buffer/service/win/big_test_main.cc +++ /dev/null @@ -1,179 +0,0 @@ -/* - * Copyright 2009, Google Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - - -#include <windows.h> -#include <Shellapi.h> -#include "command_buffer/service/cross/big_test_helpers.h" - -#if defined(CB_SERVICE_D3D9) -#include "command_buffer/service/win/d3d9/gapi_d3d9.h" -#elif defined(CB_SERVICE_GL) -#include "command_buffer/service/cross/gl/gapi_gl.h" -#endif - -#include "core/cross/types.h" - -namespace o3d { -namespace command_buffer { - -String *g_program_path = NULL; -GAPIInterface *g_gapi = NULL; - -class Thread { - public: - Thread(ThreadFunc func, void *data) - : handle_(NULL), - func_(func), - data_(data) { - } - - ~Thread() {} - - HANDLE handle() const { return handle_; } - void set_handle(HANDLE handle) { handle_ = handle; } - - void * data() const { return data_; } - ThreadFunc func() const { return func_; } - - private: - HANDLE handle_; - ThreadFunc func_; - void * data_; -}; - -DWORD WINAPI ThreadMain(LPVOID lpParam) { - Thread *thread = static_cast<Thread *>(lpParam); - ThreadFunc func = thread->func(); - func(thread->data()); - return 0; -} - -Thread *CreateThread(ThreadFunc func, void* param) { - Thread *thread = new Thread(func, param); - HANDLE handle = ::CreateThread(NULL, 0, ThreadMain, thread, 0, NULL); - return thread; -} - -void JoinThread(Thread *thread) { - ::WaitForSingleObject(thread->handle(), INFINITE); - ::CloseHandle(thread->handle()); - delete thread; -} - -bool ProcessSystemMessages() { - MSG msg; - while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { - if (msg.message == WM_QUIT) { - return false; - } - TranslateMessage(&msg); - DispatchMessage(&msg); - } - return true; -} - -} // namespace command_buffer -} // namespace o3d - -using o3d::String; -using o3d::command_buffer::g_program_path; -using o3d::command_buffer::g_gapi; - -#if defined(CB_SERVICE_D3D9) -using o3d::command_buffer::GAPID3D9; -#elif defined(CB_SERVICE_GL) -using o3d::command_buffer::GAPIGL; -#endif - -LRESULT CALLBACK WindowProc(HWND hWnd, - UINT msg, - WPARAM wParam, - LPARAM lParam) { - switch (msg) { - case WM_CLOSE: - PostQuitMessage(0); - break; - case WM_DESTROY: - PostQuitMessage(0); - break; - default: - return DefWindowProc(hWnd, msg, wParam, lParam); - } - return 0; -} - -int main(int argc, char *argv[]) { - WNDCLASSEX wc = { - sizeof(WNDCLASSEX), CS_CLASSDC, WindowProc, 0L, 0L, GetModuleHandle(NULL), - NULL, NULL, NULL, NULL, L"O3D big test", NULL - }; - RegisterClassEx(&wc); - - // Create the application's window. - HWND hWnd = CreateWindow(L"O3D big test", L"O3D Big Test", - WS_OVERLAPPEDWINDOW | WS_VISIBLE, 100, 100, 300, - 300, GetDesktopWindow(), NULL, wc.hInstance, NULL); - UpdateWindow(hWnd); - -#if defined(CB_SERVICE_D3D9) - GAPID3D9 gapi; -#elif defined(CB_SERVICE_GL) - GAPIGL gapi; -#endif - - gapi.set_hwnd(hWnd); - g_gapi = &gapi; - - wchar_t program_filename[512]; - GetModuleFileName(NULL, program_filename, sizeof(program_filename)); - program_filename[511] = 0; - - String program_path = WideToUTF8(std::wstring(program_filename)); - - // Remove all characters starting with last '\'. - size_t backslash_pos = program_path.rfind('\\'); - if (backslash_pos != String::npos) { - program_path.erase(backslash_pos); - } - g_program_path = &program_path; - - // Convert the command line arguments to an argc, argv format. - LPWSTR *arg_list = NULL; - int arg_count; - arg_list = CommandLineToArgvW(GetCommandLineW(), &arg_count); - - int ret = big_test_main(arg_count, arg_list); - - g_gapi = NULL; - g_program_path = NULL; - return ret; -} diff --git a/o3d/command_buffer/service/win/d3d9/effect_d3d9.cc b/o3d/command_buffer/service/win/d3d9/effect_d3d9.cc index e2a9720..bb80079 100644 --- a/o3d/command_buffer/service/win/d3d9/effect_d3d9.cc +++ b/o3d/command_buffer/service/win/d3d9/effect_d3d9.cc @@ -520,7 +520,7 @@ bool EffectParamD3D9::SetData(GAPID3D9 *gapi, // Calls EffectD3D9::Create, and assign the result to the resource ID. // If changing the current effect, dirty it. -BufferSyncInterface::ParseError GAPID3D9::CreateEffect( +parse_error::ParseError GAPID3D9::CreateEffect( ResourceId id, unsigned int size, const void *data) { @@ -536,120 +536,120 @@ BufferSyncInterface::ParseError GAPID3D9::CreateEffect( &vertex_program_entry, &fragment_program_entry, &effect_code)) { - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; } EffectD3D9 * effect = EffectD3D9::Create(this, effect_code, vertex_program_entry, fragment_program_entry); - if (!effect) return BufferSyncInterface::kParseInvalidArguments; + if (!effect) return parse_error::kParseInvalidArguments; effects_.Assign(id, effect); - return BufferSyncInterface::kParseNoError; + return parse_error::kParseNoError; } // Destroys the Effect resource. // If destroying the current effect, dirty it. -BufferSyncInterface::ParseError GAPID3D9::DestroyEffect(ResourceId id) { +parse_error::ParseError GAPID3D9::DestroyEffect(ResourceId id) { if (id == current_effect_id_) DirtyEffect(); return effects_.Destroy(id) ? - BufferSyncInterface::kParseNoError : - BufferSyncInterface::kParseInvalidArguments; + parse_error::kParseNoError : + parse_error::kParseInvalidArguments; } // Sets the current effect ID, dirtying the current effect. -BufferSyncInterface::ParseError GAPID3D9::SetEffect(ResourceId id) { +parse_error::ParseError GAPID3D9::SetEffect(ResourceId id) { DirtyEffect(); current_effect_id_ = id; - return BufferSyncInterface::kParseNoError; + return parse_error::kParseNoError; } // Gets the param count from the effect and store it in the memory buffer. -BufferSyncInterface::ParseError GAPID3D9::GetParamCount( +parse_error::ParseError GAPID3D9::GetParamCount( ResourceId id, unsigned int size, void *data) { EffectD3D9 *effect = effects_.Get(id); if (!effect || size < sizeof(Uint32)) // NOLINT - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; *static_cast<Uint32 *>(data) = effect->GetParamCount(); - return BufferSyncInterface::kParseNoError; + return parse_error::kParseNoError; } -BufferSyncInterface::ParseError GAPID3D9::CreateParam( +parse_error::ParseError GAPID3D9::CreateParam( ResourceId param_id, ResourceId effect_id, unsigned int index) { EffectD3D9 *effect = effects_.Get(effect_id); - if (!effect) return BufferSyncInterface::kParseInvalidArguments; + if (!effect) return parse_error::kParseInvalidArguments; EffectParamD3D9 *param = effect->CreateParam(index); - if (!param) return BufferSyncInterface::kParseInvalidArguments; + if (!param) return parse_error::kParseInvalidArguments; effect_params_.Assign(param_id, param); - return BufferSyncInterface::kParseNoError; + return parse_error::kParseNoError; } -BufferSyncInterface::ParseError GAPID3D9::CreateParamByName( +parse_error::ParseError GAPID3D9::CreateParamByName( ResourceId param_id, ResourceId effect_id, unsigned int size, const void *name) { EffectD3D9 *effect = effects_.Get(effect_id); - if (!effect) return BufferSyncInterface::kParseInvalidArguments; + if (!effect) return parse_error::kParseInvalidArguments; std::string string_name(static_cast<const char *>(name), size); EffectParamD3D9 *param = effect->CreateParamByName(string_name.c_str()); - if (!param) return BufferSyncInterface::kParseInvalidArguments; + if (!param) return parse_error::kParseInvalidArguments; effect_params_.Assign(param_id, param); - return BufferSyncInterface::kParseNoError; + return parse_error::kParseNoError; } -BufferSyncInterface::ParseError GAPID3D9::DestroyParam(ResourceId id) { +parse_error::ParseError GAPID3D9::DestroyParam(ResourceId id) { return effect_params_.Destroy(id) ? - BufferSyncInterface::kParseNoError : - BufferSyncInterface::kParseInvalidArguments; + parse_error::kParseNoError : + parse_error::kParseInvalidArguments; } -BufferSyncInterface::ParseError GAPID3D9::SetParamData( +parse_error::ParseError GAPID3D9::SetParamData( ResourceId id, unsigned int size, const void *data) { EffectParamD3D9 *param = effect_params_.Get(id); - if (!param) return BufferSyncInterface::kParseInvalidArguments; + if (!param) return parse_error::kParseInvalidArguments; return param->SetData(this, size, data) ? - BufferSyncInterface::kParseNoError : - BufferSyncInterface::kParseInvalidArguments; + parse_error::kParseNoError : + parse_error::kParseInvalidArguments; } -BufferSyncInterface::ParseError GAPID3D9::GetParamDesc( +parse_error::ParseError GAPID3D9::GetParamDesc( ResourceId id, unsigned int size, void *data) { EffectParamD3D9 *param = effect_params_.Get(id); - if (!param) return BufferSyncInterface::kParseInvalidArguments; + if (!param) return parse_error::kParseInvalidArguments; return param->GetDesc(size, data) ? - BufferSyncInterface::kParseNoError : - BufferSyncInterface::kParseInvalidArguments; + parse_error::kParseNoError : + parse_error::kParseInvalidArguments; } // Gets the stream count from the effect and stores it in the memory buffer. -BufferSyncInterface::ParseError GAPID3D9::GetStreamCount( +parse_error::ParseError GAPID3D9::GetStreamCount( ResourceId id, unsigned int size, void *data) { EffectD3D9 *effect = effects_.Get(id); if (!effect || size < sizeof(Uint32)) // NOLINT - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; *static_cast<Uint32 *>(data) = effect->GetStreamCount(); - return BufferSyncInterface::kParseNoError; + return parse_error::kParseNoError; } -BufferSyncInterface::ParseError GAPID3D9::GetStreamDesc( +parse_error::ParseError GAPID3D9::GetStreamDesc( ResourceId id, unsigned int index, unsigned int size, void *data) { EffectD3D9 *effect = effects_.Get(id); - if (!effect) return BufferSyncInterface::kParseInvalidArguments; + if (!effect) return parse_error::kParseInvalidArguments; return effect->GetStreamDesc(index, size, data) ? - BufferSyncInterface::kParseNoError : - BufferSyncInterface::kParseInvalidArguments; + parse_error::kParseNoError : + parse_error::kParseInvalidArguments; } diff --git a/o3d/command_buffer/service/win/d3d9/gapi_d3d9.cc b/o3d/command_buffer/service/win/d3d9/gapi_d3d9.cc index df9cb46..79ada6f 100644 --- a/o3d/command_buffer/service/win/d3d9/gapi_d3d9.cc +++ b/o3d/command_buffer/service/win/d3d9/gapi_d3d9.cc @@ -239,10 +239,10 @@ static unsigned int RGBAToARGB(unsigned int rgba) { } // Sets the current VertexStruct. Just keep track of the ID. -BufferSyncInterface::ParseError GAPID3D9::SetVertexStruct(ResourceId id) { +parse_error::ParseError GAPID3D9::SetVertexStruct(ResourceId id) { current_vertex_struct_ = id; validate_streams_ = true; - return BufferSyncInterface::kParseNoError; + return parse_error::kParseNoError; } bool GAPID3D9::FindDirect3DFunctions() { @@ -330,32 +330,32 @@ static D3DPRIMITIVETYPE D3DPrimitive( } // Draws with the current vertex struct. -BufferSyncInterface::ParseError GAPID3D9::Draw( +parse_error::ParseError GAPID3D9::Draw( PrimitiveType primitive_type, unsigned int first, unsigned int count) { if (validate_streams_ && !ValidateStreams()) { // TODO: add proper error management - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; } if (validate_effect_ && !ValidateEffect()) { // TODO: add proper error management - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; } DCHECK(current_effect_); if (!current_effect_->CommitParameters()) { - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; } if (first + count > max_vertices_) { // TODO: add proper error management - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; } HR(d3d_device_->DrawPrimitive(D3DPrimitive(primitive_type), first, count)); - return BufferSyncInterface::kParseNoError; + return parse_error::kParseNoError; } // Draws with the current vertex struct. -BufferSyncInterface::ParseError GAPID3D9::DrawIndexed( +parse_error::ParseError GAPID3D9::DrawIndexed( PrimitiveType primitive_type, ResourceId index_buffer_id, unsigned int first, @@ -363,29 +363,29 @@ BufferSyncInterface::ParseError GAPID3D9::DrawIndexed( unsigned int min_index, unsigned int max_index) { IndexBufferD3D9 *index_buffer = index_buffers_.Get(index_buffer_id); - if (!index_buffer) return BufferSyncInterface::kParseInvalidArguments; + if (!index_buffer) return parse_error::kParseInvalidArguments; if (validate_streams_ && !ValidateStreams()) { // TODO: add proper error management - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; } if (validate_effect_ && !ValidateEffect()) { // TODO: add proper error management - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; } DCHECK(current_effect_); if (!current_effect_->CommitParameters()) { - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; } if ((min_index >= max_vertices_) || (max_index > max_vertices_)) { // TODO: add proper error management - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; } HR(d3d_device_->SetIndices(index_buffer->d3d_index_buffer())); HR(d3d_device_->DrawIndexedPrimitive(D3DPrimitive(primitive_type), 0, min_index, max_index - min_index + 1, first, count)); - return BufferSyncInterface::kParseNoError; + return parse_error::kParseNoError; } } // namespace command_buffer diff --git a/o3d/command_buffer/service/win/d3d9/geometry_d3d9.cc b/o3d/command_buffer/service/win/d3d9/geometry_d3d9.cc index 0123d49..7674585 100644 --- a/o3d/command_buffer/service/win/d3d9/geometry_d3d9.cc +++ b/o3d/command_buffer/service/win/d3d9/geometry_d3d9.cc @@ -309,112 +309,112 @@ void VertexStructD3D9::Compile(IDirect3DDevice9 *d3d_device) { } // Creates and assigns a VertexBufferD3D9 resource. -BufferSyncInterface::ParseError GAPID3D9::CreateVertexBuffer( +parse_error::ParseError GAPID3D9::CreateVertexBuffer( ResourceId id, unsigned int size, unsigned int flags) { VertexBufferD3D9 *vertex_buffer = new VertexBufferD3D9(size, flags); vertex_buffer->Create(this); vertex_buffers_.Assign(id, vertex_buffer); - return BufferSyncInterface::kParseNoError; + return parse_error::kParseNoError; } // Destroys a VertexBufferD3D9 resource. -BufferSyncInterface::ParseError GAPID3D9::DestroyVertexBuffer(ResourceId id) { +parse_error::ParseError GAPID3D9::DestroyVertexBuffer(ResourceId id) { return vertex_buffers_.Destroy(id) ? - BufferSyncInterface::kParseNoError : - BufferSyncInterface::kParseInvalidArguments; + parse_error::kParseNoError : + parse_error::kParseInvalidArguments; } // Copies the data into the VertexBufferD3D9 resource. -BufferSyncInterface::ParseError GAPID3D9::SetVertexBufferData( +parse_error::ParseError GAPID3D9::SetVertexBufferData( ResourceId id, unsigned int offset, unsigned int size, const void *data) { VertexBufferD3D9 *vertex_buffer = vertex_buffers_.Get(id); - if (!vertex_buffer) return BufferSyncInterface::kParseInvalidArguments; + if (!vertex_buffer) return parse_error::kParseInvalidArguments; return vertex_buffer->SetData(offset, size, data) ? - BufferSyncInterface::kParseNoError : - BufferSyncInterface::kParseInvalidArguments; + parse_error::kParseNoError : + parse_error::kParseInvalidArguments; } // Copies the data from the VertexBufferD3D9 resource. -BufferSyncInterface::ParseError GAPID3D9::GetVertexBufferData( +parse_error::ParseError GAPID3D9::GetVertexBufferData( ResourceId id, unsigned int offset, unsigned int size, void *data) { VertexBufferD3D9 *vertex_buffer = vertex_buffers_.Get(id); - if (!vertex_buffer) return BufferSyncInterface::kParseInvalidArguments; + if (!vertex_buffer) return parse_error::kParseInvalidArguments; return vertex_buffer->GetData(offset, size, data) ? - BufferSyncInterface::kParseNoError : - BufferSyncInterface::kParseInvalidArguments; + parse_error::kParseNoError : + parse_error::kParseInvalidArguments; } // Creates and assigns an IndexBufferD3D9 resource. -BufferSyncInterface::ParseError GAPID3D9::CreateIndexBuffer( +parse_error::ParseError GAPID3D9::CreateIndexBuffer( ResourceId id, unsigned int size, unsigned int flags) { IndexBufferD3D9 *index_buffer = new IndexBufferD3D9(size, flags); index_buffer->Create(this); index_buffers_.Assign(id, index_buffer); - return BufferSyncInterface::kParseNoError; + return parse_error::kParseNoError; } // Destroys an IndexBufferD3D9 resource. -BufferSyncInterface::ParseError GAPID3D9::DestroyIndexBuffer(ResourceId id) { +parse_error::ParseError GAPID3D9::DestroyIndexBuffer(ResourceId id) { return index_buffers_.Destroy(id) ? - BufferSyncInterface::kParseNoError : - BufferSyncInterface::kParseInvalidArguments; + parse_error::kParseNoError : + parse_error::kParseInvalidArguments; } // Copies the data into the IndexBufferD3D9 resource. -BufferSyncInterface::ParseError GAPID3D9::SetIndexBufferData( +parse_error::ParseError GAPID3D9::SetIndexBufferData( ResourceId id, unsigned int offset, unsigned int size, const void *data) { IndexBufferD3D9 *index_buffer = index_buffers_.Get(id); - if (!index_buffer) return BufferSyncInterface::kParseInvalidArguments; + if (!index_buffer) return parse_error::kParseInvalidArguments; return index_buffer->SetData(offset, size, data) ? - BufferSyncInterface::kParseNoError : - BufferSyncInterface::kParseInvalidArguments; + parse_error::kParseNoError : + parse_error::kParseInvalidArguments; } // Copies the data from the IndexBufferD3D9 resource. -BufferSyncInterface::ParseError GAPID3D9::GetIndexBufferData( +parse_error::ParseError GAPID3D9::GetIndexBufferData( ResourceId id, unsigned int offset, unsigned int size, void *data) { IndexBufferD3D9 *index_buffer = index_buffers_.Get(id); - if (!index_buffer) return BufferSyncInterface::kParseInvalidArguments; + if (!index_buffer) return parse_error::kParseInvalidArguments; return index_buffer->GetData(offset, size, data) ? - BufferSyncInterface::kParseNoError : - BufferSyncInterface::kParseInvalidArguments; + parse_error::kParseNoError : + parse_error::kParseInvalidArguments; } // Creates and assigns a VertexStructD3D9 resource. -BufferSyncInterface::ParseError GAPID3D9::CreateVertexStruct( +parse_error::ParseError GAPID3D9::CreateVertexStruct( ResourceId id, unsigned int input_count) { if (id == current_vertex_struct_) validate_streams_ = true; VertexStructD3D9 *vertex_struct = new VertexStructD3D9(input_count); vertex_structs_.Assign(id, vertex_struct); - return BufferSyncInterface::kParseNoError; + return parse_error::kParseNoError; } // Destroys a VertexStructD3D9 resource. -BufferSyncInterface::ParseError GAPID3D9::DestroyVertexStruct(ResourceId id) { +parse_error::ParseError GAPID3D9::DestroyVertexStruct(ResourceId id) { if (id == current_vertex_struct_) validate_streams_ = true; return vertex_structs_.Destroy(id) ? - BufferSyncInterface::kParseNoError : - BufferSyncInterface::kParseInvalidArguments; + parse_error::kParseNoError : + parse_error::kParseInvalidArguments; } // Sets an input into a VertexStructD3D9 resource. -BufferSyncInterface::ParseError GAPID3D9::SetVertexInput( +parse_error::ParseError GAPID3D9::SetVertexInput( ResourceId vertex_struct_id, unsigned int input_index, ResourceId vertex_buffer_id, @@ -426,10 +426,10 @@ BufferSyncInterface::ParseError GAPID3D9::SetVertexInput( if (vertex_buffer_id == current_vertex_struct_) validate_streams_ = true; VertexStructD3D9 *vertex_struct = vertex_structs_.Get(vertex_struct_id); if (!vertex_struct || input_index >= vertex_struct->count()) - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; vertex_struct->SetInput(input_index, vertex_buffer_id, offset, stride, type, semantic, semantic_index); - return BufferSyncInterface::kParseNoError; + return parse_error::kParseNoError; } } // namespace command_buffer diff --git a/o3d/command_buffer/service/win/d3d9/render_surface_d3d9.cc b/o3d/command_buffer/service/win/d3d9/render_surface_d3d9.cc index bf2281f..8141edd 100644 --- a/o3d/command_buffer/service/win/d3d9/render_surface_d3d9.cc +++ b/o3d/command_buffer/service/win/d3d9/render_surface_d3d9.cc @@ -127,7 +127,7 @@ RenderDepthStencilSurfaceD3D9* RenderDepthStencilSurfaceD3D9::Create( // GAPI Interface functions --------------------------------------------------- // Copies the data from a texture resource. -BufferSyncInterface::ParseError GAPID3D9::CreateRenderSurface( +parse_error::ParseError GAPID3D9::CreateRenderSurface( ResourceId id, unsigned int width, unsigned int height, @@ -136,11 +136,11 @@ BufferSyncInterface::ParseError GAPID3D9::CreateRenderSurface( ResourceId texture_id) { if (id == current_surface_id_) { // This will delete the current surface which would be bad. - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; } TextureD3D9 *texture = textures_.Get(texture_id); if (!texture->render_surfaces_enabled()) { - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; } else { RenderSurfaceD3D9 *render_surface = RenderSurfaceD3D9::Create(this, width, @@ -149,49 +149,49 @@ BufferSyncInterface::ParseError GAPID3D9::CreateRenderSurface( side, texture); if (render_surface == NULL) { - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; } render_surfaces_.Assign(id, render_surface); } - return BufferSyncInterface::kParseNoError; + return parse_error::kParseNoError; } -BufferSyncInterface::ParseError GAPID3D9::DestroyRenderSurface(ResourceId id) { +parse_error::ParseError GAPID3D9::DestroyRenderSurface(ResourceId id) { if (id == current_surface_id_) { - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; } return render_surfaces_.Destroy(id) ? - BufferSyncInterface::kParseNoError : - BufferSyncInterface::kParseInvalidArguments; + parse_error::kParseNoError : + parse_error::kParseInvalidArguments; } -BufferSyncInterface::ParseError GAPID3D9::CreateDepthSurface( +parse_error::ParseError GAPID3D9::CreateDepthSurface( ResourceId id, unsigned int width, unsigned int height) { if (id == current_depth_surface_id_) { // This will delete the current surface which would be bad. - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; } RenderDepthStencilSurfaceD3D9 *depth_surface = RenderDepthStencilSurfaceD3D9::Create(this, width, height); if (depth_surface == NULL) { - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; } depth_surfaces_.Assign(id, depth_surface); - return BufferSyncInterface::kParseNoError; + return parse_error::kParseNoError; } -BufferSyncInterface::ParseError GAPID3D9::DestroyDepthSurface(ResourceId id) { +parse_error::ParseError GAPID3D9::DestroyDepthSurface(ResourceId id) { if (id == current_depth_surface_id_) { - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; } return depth_surfaces_.Destroy(id) ? - BufferSyncInterface::kParseNoError : - BufferSyncInterface::kParseInvalidArguments; + parse_error::kParseNoError : + parse_error::kParseInvalidArguments; } -BufferSyncInterface::ParseError GAPID3D9::SetRenderSurface( +parse_error::ParseError GAPID3D9::SetRenderSurface( ResourceId render_surface_id, ResourceId depth_stencil_id) { RenderSurfaceD3D9 *d3d_render_surface = @@ -200,7 +200,7 @@ BufferSyncInterface::ParseError GAPID3D9::SetRenderSurface( depth_surfaces_.Get(depth_stencil_id); if (d3d_render_surface == NULL && d3d_render_depth_surface == NULL) { - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; } IDirect3DSurface9 *d3d_surface = @@ -215,7 +215,7 @@ BufferSyncInterface::ParseError GAPID3D9::SetRenderSurface( HR(device->SetDepthStencilSurface(d3d_depth_surface)); current_surface_id_ = render_surface_id; current_depth_surface_id_ = depth_stencil_id; - return BufferSyncInterface::kParseNoError; + return parse_error::kParseNoError; } void GAPID3D9::SetBackSurfaces() { diff --git a/o3d/command_buffer/service/win/d3d9/sampler_d3d9.cc b/o3d/command_buffer/service/win/d3d9/sampler_d3d9.cc index 1e9be7b..3823aae 100644 --- a/o3d/command_buffer/service/win/d3d9/sampler_d3d9.cc +++ b/o3d/command_buffer/service/win/d3d9/sampler_d3d9.cc @@ -134,24 +134,24 @@ void SamplerD3D9::SetBorderColor(const RGBA &color) { d3d_border_color_ = RGBAToD3DCOLOR(color); } -BufferSyncInterface::ParseError GAPID3D9::CreateSampler( +parse_error::ParseError GAPID3D9::CreateSampler( ResourceId id) { // Dirty effect, because this sampler id may be used DirtyEffect(); samplers_.Assign(id, new SamplerD3D9()); - return BufferSyncInterface::kParseNoError; + return parse_error::kParseNoError; } // Destroys the Sampler resource. -BufferSyncInterface::ParseError GAPID3D9::DestroySampler(ResourceId id) { +parse_error::ParseError GAPID3D9::DestroySampler(ResourceId id) { // Dirty effect, because this sampler id may be used DirtyEffect(); return samplers_.Destroy(id) ? - BufferSyncInterface::kParseNoError : - BufferSyncInterface::kParseInvalidArguments; + parse_error::kParseNoError : + parse_error::kParseInvalidArguments; } -BufferSyncInterface::ParseError GAPID3D9::SetSamplerStates( +parse_error::ParseError GAPID3D9::SetSamplerStates( ResourceId id, sampler::AddressingMode addressing_u, sampler::AddressingMode addressing_v, @@ -162,36 +162,36 @@ BufferSyncInterface::ParseError GAPID3D9::SetSamplerStates( unsigned int max_anisotropy) { SamplerD3D9 *sampler = samplers_.Get(id); if (!sampler) - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; // Dirty effect, because this sampler id may be used DirtyEffect(); sampler->SetStates(addressing_u, addressing_v, addressing_w, mag_filter, min_filter, mip_filter, max_anisotropy); - return BufferSyncInterface::kParseNoError; + return parse_error::kParseNoError; } -BufferSyncInterface::ParseError GAPID3D9::SetSamplerBorderColor( +parse_error::ParseError GAPID3D9::SetSamplerBorderColor( ResourceId id, const RGBA &color) { SamplerD3D9 *sampler = samplers_.Get(id); if (!sampler) - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; // Dirty effect, because this sampler id may be used DirtyEffect(); sampler->SetBorderColor(color); - return BufferSyncInterface::kParseNoError; + return parse_error::kParseNoError; } -BufferSyncInterface::ParseError GAPID3D9::SetSamplerTexture( +parse_error::ParseError GAPID3D9::SetSamplerTexture( ResourceId id, ResourceId texture_id) { SamplerD3D9 *sampler = samplers_.Get(id); if (!sampler) - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; // Dirty effect, because this sampler id may be used DirtyEffect(); sampler->SetTexture(texture_id); - return BufferSyncInterface::kParseNoError; + return parse_error::kParseNoError; } diff --git a/o3d/command_buffer/service/win/d3d9/texture_d3d9.cc b/o3d/command_buffer/service/win/d3d9/texture_d3d9.cc index 4e55edb..f9c235a 100644 --- a/o3d/command_buffer/service/win/d3d9/texture_d3d9.cc +++ b/o3d/command_buffer/service/win/d3d9/texture_d3d9.cc @@ -611,16 +611,16 @@ bool TextureCubeD3D9::CreateRenderSurface( // GAPID3D9 functions. // Destroys a texture resource. -BufferSyncInterface::ParseError GAPID3D9::DestroyTexture(ResourceId id) { +parse_error::ParseError GAPID3D9::DestroyTexture(ResourceId id) { // Dirty effect, because this texture id may be used DirtyEffect(); return textures_.Destroy(id) ? - BufferSyncInterface::kParseNoError : - BufferSyncInterface::kParseInvalidArguments; + parse_error::kParseNoError : + parse_error::kParseInvalidArguments; } // Creates a 2D texture resource. -BufferSyncInterface::ParseError GAPID3D9::CreateTexture2D( +parse_error::ParseError GAPID3D9::CreateTexture2D( ResourceId id, unsigned int width, unsigned int height, @@ -631,15 +631,15 @@ BufferSyncInterface::ParseError GAPID3D9::CreateTexture2D( Texture2DD3D9 *texture = Texture2DD3D9::Create(this, width, height, levels, format, flags, enable_render_surfaces); - if (!texture) return BufferSyncInterface::kParseInvalidArguments; + if (!texture) return parse_error::kParseInvalidArguments; // Dirty effect, because this texture id may be used DirtyEffect(); textures_.Assign(id, texture); - return BufferSyncInterface::kParseNoError; + return parse_error::kParseNoError; } // Creates a 3D texture resource. -BufferSyncInterface::ParseError GAPID3D9::CreateTexture3D( +parse_error::ParseError GAPID3D9::CreateTexture3D( ResourceId id, unsigned int width, unsigned int height, @@ -651,15 +651,15 @@ BufferSyncInterface::ParseError GAPID3D9::CreateTexture3D( Texture3DD3D9 *texture = Texture3DD3D9::Create(this, width, height, depth, levels, format, flags, enable_render_surfaces); - if (!texture) return BufferSyncInterface::kParseInvalidArguments; + if (!texture) return parse_error::kParseInvalidArguments; // Dirty effect, because this texture id may be used DirtyEffect(); textures_.Assign(id, texture); - return BufferSyncInterface::kParseNoError; + return parse_error::kParseNoError; } // Creates a cube map texture resource. -BufferSyncInterface::ParseError GAPID3D9::CreateTextureCube( +parse_error::ParseError GAPID3D9::CreateTextureCube( ResourceId id, unsigned int side, unsigned int levels, @@ -669,15 +669,15 @@ BufferSyncInterface::ParseError GAPID3D9::CreateTextureCube( TextureCubeD3D9 *texture = TextureCubeD3D9::Create(this, side, levels, format, flags, enable_render_surfaces); - if (!texture) return BufferSyncInterface::kParseInvalidArguments; + if (!texture) return parse_error::kParseInvalidArguments; // Dirty effect, because this texture id may be used DirtyEffect(); textures_.Assign(id, texture); - return BufferSyncInterface::kParseNoError; + return parse_error::kParseNoError; } // Copies the data into a texture resource. -BufferSyncInterface::ParseError GAPID3D9::SetTextureData( +parse_error::ParseError GAPID3D9::SetTextureData( ResourceId id, unsigned int x, unsigned int y, @@ -693,16 +693,16 @@ BufferSyncInterface::ParseError GAPID3D9::SetTextureData( const void *data) { TextureD3D9 *texture = textures_.Get(id); if (!texture) - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; Volume volume = {x, y, z, width, height, depth}; return texture->SetData(this, volume, level, face, row_pitch, slice_pitch, size, data) ? - BufferSyncInterface::kParseNoError : - BufferSyncInterface::kParseInvalidArguments; + parse_error::kParseNoError : + parse_error::kParseInvalidArguments; } // Copies the data from a texture resource. -BufferSyncInterface::ParseError GAPID3D9::GetTextureData( +parse_error::ParseError GAPID3D9::GetTextureData( ResourceId id, unsigned int x, unsigned int y, @@ -718,12 +718,12 @@ BufferSyncInterface::ParseError GAPID3D9::GetTextureData( void *data) { TextureD3D9 *texture = textures_.Get(id); if (!texture) - return BufferSyncInterface::kParseInvalidArguments; + return parse_error::kParseInvalidArguments; Volume volume = {x, y, z, width, height, depth}; return texture->GetData(this, volume, level, face, row_pitch, slice_pitch, size, data) ? - BufferSyncInterface::kParseNoError : - BufferSyncInterface::kParseInvalidArguments; + parse_error::kParseNoError : + parse_error::kParseInvalidArguments; } } // namespace command_buffer diff --git a/o3d/command_buffer/service/win/plugin.def b/o3d/command_buffer/service/win/plugin.def deleted file mode 100644 index 292cf78..0000000 --- a/o3d/command_buffer/service/win/plugin.def +++ /dev/null @@ -1,6 +0,0 @@ -LIBRARY npo3d_cb_plugin - -EXPORTS - NP_GetEntryPoints @1 - NP_Initialize @2 - NP_Shutdown @3 diff --git a/o3d/command_buffer/service/win/plugin.rc b/o3d/command_buffer/service/win/plugin.rc deleted file mode 100644 index 393668e..0000000 --- a/o3d/command_buffer/service/win/plugin.rc +++ /dev/null @@ -1,100 +0,0 @@ -// Microsoft Visual C++ generated resource script. -// -#define APSTUDIO_READONLY_SYMBOLS -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 2 resource. -// -#include "afxres.h" - -///////////////////////////////////////////////////////////////////////////// -#undef APSTUDIO_READONLY_SYMBOLS - -///////////////////////////////////////////////////////////////////////////// -// English (U.S.) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) -#ifdef _WIN32 -LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US -#pragma code_page(1252) -#endif //_WIN32 - -#ifdef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// TEXTINCLUDE -// - -1 TEXTINCLUDE -BEGIN - "resource.h\0" -END - -2 TEXTINCLUDE -BEGIN - "#include ""afxres.h""\r\n" - "\0" -END - -3 TEXTINCLUDE -BEGIN - "\r\n" - "\0" -END - -#endif // APSTUDIO_INVOKED - - -///////////////////////////////////////////////////////////////////////////// -// -// Version -// - -VS_VERSION_INFO VERSIONINFO - FILEVERSION 0,0,0,1 - PRODUCTVERSION 0,0,0,1 - FILEFLAGSMASK 0x17L -#ifdef _DEBUG - FILEFLAGS 0x1L -#else - FILEFLAGS 0x0L -#endif - FILEOS 0x4L - FILETYPE 0x2L - FILESUBTYPE 0x0L -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "040904e4" - BEGIN - VALUE "FileDescription", "CommandBuffer SRV Plugin" - VALUE "FileVersion", "0,0,0,1" - VALUE "InternalName", "" - VALUE "LegalCopyright", "Copyright (C) 2008" - VALUE "MIMEType", "application/vnd.cmdbuf" - VALUE "OriginalFilename", "npo3d_cb_plugin.dll" - VALUE "ProductName", "CommandBuffer SRV Plugin" - VALUE "ProductVersion", "0,0,0,1" - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x409, 1252 - END -END - -#endif // English (U.S.) resources -///////////////////////////////////////////////////////////////////////////// - - - -#ifndef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 3 resource. -// - - -///////////////////////////////////////////////////////////////////////////// -#endif // not APSTUDIO_INVOKED - diff --git a/o3d/core/build.scons b/o3d/core/build.scons index bb7217e..62e803e 100644 --- a/o3d/core/build.scons +++ b/o3d/core/build.scons @@ -175,29 +175,11 @@ elif 'RENDERER_GL' in env['CPPDEFINES'] : 'cross/gl/utils_gl.cc', "cross/gl/sampler_gl.cc", ] -elif 'RENDERER_CB' in env['CPPDEFINES'] : - platform_inputs += [ - 'cross/command_buffer/buffer_cb.cc', - 'cross/command_buffer/effect_cb.cc', - 'cross/command_buffer/install_check.cc', - 'cross/command_buffer/param_cache_cb.cc', - 'cross/command_buffer/primitive_cb.cc', - 'cross/command_buffer/renderer_cb.cc', - 'cross/command_buffer/render_surface_cb.cc', - 'cross/command_buffer/sampler_cb.cc', - 'cross/command_buffer/states_cb.cc', - 'cross/command_buffer/stream_bank_cb.cc', - 'cross/command_buffer/texture_cb.cc', - ] - if env['TARGET_PLATFORM'] == 'WINDOWS': - platform_inputs += [ - 'win/command_buffer/win32_cb_server.cc', - ] elif 'RENDERER_MOCK' in env['CPPDEFINES'] : platform_inputs += [ ] else : print 'No renderer defined, exiting.\n' - print """Add 'RENDERER=gl', 'RENDERER=d3d' or 'RENDERER=cb' to the command line.""" + print """Add 'RENDERER=gl' or 'RENDERER=d3d' to the command line.""" Exit(1) if env['TARGET_PLATFORM'] == 'MAC': diff --git a/o3d/core/core.gyp b/o3d/core/core.gyp index e4bc0f4..9216f36 100644 --- a/o3d/core/core.gyp +++ b/o3d/core/core.gyp @@ -318,8 +318,6 @@ 'type': 'static_library', 'dependencies': [ '../../skia/skia.gyp:skia', - '../command_buffer/command_buffer.gyp:command_buffer_client', - '../command_buffer/command_buffer.gyp:command_buffer_service', ], 'sources': [ ], @@ -396,6 +394,16 @@ ], ['renderer == "cb"', { + 'dependencies': [ + '../command_buffer/command_buffer.gyp:command_buffer_client', + '../command_buffer/command_buffer.gyp:command_buffer_service', + '../gpu_plugin/gpu_plugin.gyp:np_utils', + + # These dependencies is only needed for RendererCBLocal. They can + # be removed when RendererCBLocal is not needed. + '../gpu_plugin/gpu_plugin.gyp:command_buffer', + '../gpu_plugin/gpu_plugin.gyp:np_utils', + ], 'sources': [ 'cross/command_buffer/buffer_cb.cc', 'cross/command_buffer/buffer_cb.h', @@ -422,14 +430,6 @@ ], }, ], - ['renderer == "cb" and OS == "win"', - { - 'sources': [ - 'win/command_buffer/win32_cb_server.cc', - 'win/command_buffer/win32_cb_server.h', - ], - }, - ], ], }, { diff --git a/o3d/command_buffer/common/cross/buffer_sync_api.cc b/o3d/core/cross/command_buffer/display_window_cb.h index 6679108..52cd08a 100644 --- a/o3d/command_buffer/common/cross/buffer_sync_api.cc +++ b/o3d/core/cross/command_buffer/display_window_cb.h @@ -30,14 +30,61 @@ */ -#include "command_buffer/common/cross/buffer_sync_api.h" +#ifndef O3D_CORE_WIN_DISPLAY_WINDOW_CB_H_ +#define O3D_CORE_WIN_DISPLAY_WINDOW_CB_H_ + +#include "core/cross/display_window.h" +#include "gpu_plugin/np_utils/np_object_pointer.h" namespace o3d { -namespace command_buffer { -#ifndef COMPILER_MSVC -const unsigned int BufferSyncInterface::kInvalidSharedMemoryId; -#endif +// DisplayWindow subclass without information needed to connect to and use +// an out-of-process command buffer renderer. +class DisplayWindowCB : public DisplayWindow { + public: + DisplayWindowCB() : npp_(NULL), width_(0), height_(0) {} + virtual ~DisplayWindowCB() {} + + NPP npp() const { + return npp_; + } + + void set_npp(NPP npp) { + npp_ = npp; + } + + gpu_plugin::NPObjectPointer<NPObject> command_buffer() const { + return command_buffer_; + } + + void set_command_buffer( + const gpu_plugin::NPObjectPointer<NPObject> command_buffer) { + command_buffer_ = command_buffer; + } + + int width() const { + return width_; + } + + void set_width(int width) { + width_ = width; + } + + int height() const { + return height_; + } + + void set_height(int height) { + height_ = height; + } + + private: + NPP npp_; + gpu_plugin::NPObjectPointer<NPObject> command_buffer_; + int width_; + int height_; + DISALLOW_COPY_AND_ASSIGN(DisplayWindowCB); +}; +} // end namespace o3d -} // namespace command_buffer -} // namespace o3d +#endif // O3D_CORE_WIN_DISPLAY_WINDOW_CB_H_ diff --git a/o3d/core/cross/command_buffer/effect_cb.cc b/o3d/core/cross/command_buffer/effect_cb.cc index b69be352..172d717 100644 --- a/o3d/core/cross/command_buffer/effect_cb.cc +++ b/o3d/core/cross/command_buffer/effect_cb.cc @@ -37,18 +37,18 @@ #include "core/cross/semantic_manager.h" #include "core/cross/service_locator.h" #include "core/cross/command_buffer/effect_cb.h" -#include "command_buffer/common/cross/buffer_sync_api.h" +#include "command_buffer/common/cross/constants.h" #include "command_buffer/common/cross/cmd_buffer_format.h" #include "command_buffer/client/cross/fenced_allocator.h" #include "command_buffer/client/cross/cmd_buffer_helper.h" namespace o3d { -using command_buffer::BufferSyncInterface; using command_buffer::CommandBufferEntry; using command_buffer::CommandBufferHelper; using command_buffer::ResourceId; namespace effect_param = command_buffer::effect_param; +namespace parse_error = command_buffer::parse_error; namespace vertex_struct = command_buffer::vertex_struct; EffectCB::EffectCB(ServiceLocator *service_locator, RendererCB *renderer) @@ -101,8 +101,7 @@ bool EffectCB::LoadFromFXString(const String& source) { // NOTE: we're calling Finish to check the command result, to see if // the effect has succesfully compiled. helper->Finish(); - if (renderer_->sync_interface()->GetParseError() != - BufferSyncInterface::kParseNoError) { + if (renderer_->GetParseError() != parse_error::kParseNoError) { O3D_ERROR(service_locator()) << "Effect failed to compile."; renderer_->effect_ids().FreeID(resource_id); return false; diff --git a/o3d/core/cross/command_buffer/renderer_cb.cc b/o3d/core/cross/command_buffer/renderer_cb.cc index d576874..4db474f 100644 --- a/o3d/core/cross/command_buffer/renderer_cb.cc +++ b/o3d/core/cross/command_buffer/renderer_cb.cc @@ -47,119 +47,66 @@ #include "core/cross/command_buffer/states_cb.h" #include "core/cross/command_buffer/stream_bank_cb.h" #include "core/cross/command_buffer/texture_cb.h" +#include "core/cross/command_buffer/display_window_cb.h" #include "core/cross/renderer_platform.h" - -#ifdef OS_WIN -#include "core/win/command_buffer/win32_cb_server.h" -#endif +#include "gpu_plugin/command_buffer.h" +#include "gpu_plugin/gpu_processor.h" +#include "gpu_plugin/np_utils/np_browser.h" +#include "gpu_plugin/np_utils/np_utils.h" +#include "gpu_plugin/system_services/shared_memory.h" namespace o3d { using command_buffer::GAPIInterface; using command_buffer::CommandBufferHelper; +using gpu_plugin::CommandBuffer; +using gpu_plugin::GPUProcessor; +using gpu_plugin::NPBrowser; +using gpu_plugin::NPCreateObject; +using gpu_plugin::NPGetProperty; +using gpu_plugin::NPInvoke; +using gpu_plugin::NPInvokeVoid; +using gpu_plugin::NPObjectPointer; +using gpu_plugin::SharedMemory; RendererCB::RendererCB(ServiceLocator* service_locator, - unsigned int command_buffer_size, - unsigned int transfer_memory_size) + int32 transfer_memory_size) : Renderer(service_locator), - cmd_buffer_size_(command_buffer_size), transfer_memory_size_(transfer_memory_size), - transfer_shm_(command_buffer::kRPCInvalidHandle), - transfer_shm_id_(0), + transfer_shm_id_(command_buffer::kInvalidSharedMemoryId), transfer_shm_address_(NULL), - sync_interface_(NULL), + npp_(NULL), helper_(NULL), allocator_(NULL), - cb_server_(NULL), frame_token_(0), state_manager_(new StateManager) { - DCHECK_GT(command_buffer_size, 0U); - DCHECK_GT(transfer_memory_size, 0U); - transfer_shm_ = command_buffer::CreateShm(transfer_memory_size); - transfer_shm_address_ = command_buffer::MapShm(transfer_shm_, - transfer_memory_size); + DCHECK_GT(transfer_memory_size, 0); state_manager_->AddStateHandlers(this); } RendererCB::~RendererCB() { Destroy(); - command_buffer::UnmapShm(transfer_shm_address_, transfer_memory_size_); - command_buffer::DestroyShm(transfer_shm_); } -static const unsigned int kDefaultCommandBufferSize = 256 << 10; -// This should be enough to hold the biggest possible buffer -// (2048x2048xABGR16F texture = 32MB) -static const unsigned int kDefaultTransferMemorySize = 32 << 20; - -RendererCB *RendererCB::CreateDefault(ServiceLocator* service_locator) { - return new RendererCB(service_locator, kDefaultCommandBufferSize, - kDefaultTransferMemorySize); -} - -Renderer::InitStatus RendererCB::InitPlatformSpecific( - const DisplayWindow& display, - bool off_screen) { - if (off_screen) { - // TODO: Off-screen support ? - return UNINITIALIZED; // equivalent to 0/false +void RendererCB::Destroy() { + if (transfer_shm_id_ >= 0) { + NPInvokeVoid(npp_, command_buffer_, "unregisterObject", transfer_shm_id_); + transfer_shm_id_ = command_buffer::kInvalidSharedMemoryId; } -#ifdef OS_WIN - const DisplayWindowWindows &display_platform = - static_cast<const DisplayWindowWindows&>(display); - // Creates a Win32CBServer based on the HWND, and creates the - // command buffer helper, and initializes it. Also, create the - // FencedAllocator for the transfer memory. - cb_server_ = new Win32CBServer(display_platform.hwnd(), features()); - sync_interface_ = cb_server_->GetInterface(); - - RECT windowRect; - ::GetWindowRect(display_platform.hwnd(), &windowRect); - int width = windowRect.right - windowRect.left; - int height = windowRect.bottom - windowRect.top; - InitCommon(width, height); - return SUCCESS; -#else - // TODO: Implement Mac/Linux support before shipping - // command buffers. - return UNINITIALIZED; -#endif -} + transfer_shm_ = NPObjectPointer<NPObject>(); -void RendererCB::InitCommon(unsigned int width, unsigned int height) { - sync_interface_->InitConnection(); - transfer_shm_id_ = sync_interface_->RegisterSharedMemory( - transfer_shm_, transfer_memory_size_); - helper_ = new CommandBufferHelper(sync_interface_); - helper_->Init(cmd_buffer_size_); - frame_token_ = helper_->InsertToken(); - allocator_ = new FencedAllocatorWrapper(transfer_memory_size_, - helper_, - transfer_shm_address_); - SetClientSize(width, height); -} - -void RendererCB::Destroy() { if (allocator_) { delete allocator_; allocator_ = NULL; } + if (helper_) { helper_->Finish(); - if (sync_interface_) { - sync_interface_->CloseConnection(); - sync_interface_->UnregisterSharedMemory(transfer_shm_id_); - sync_interface_ = NULL; - } delete helper_; helper_ = NULL; } -#ifdef OS_WIN - if (cb_server_) { - delete cb_server_; - cb_server_ = NULL; - } -#endif + + npp_ = NULL; } void RendererCB::ApplyDirtyStates() { @@ -314,10 +261,8 @@ const int* RendererCB::GetRGBAUByteNSwizzleTable() { return swizzle_table; } -// This is a factory function for creating Renderer objects. Since -// we're implementing command buffers, we only ever return a CB renderer. -Renderer* Renderer::CreateDefaultRenderer(ServiceLocator* service_locator) { - return RendererCB::CreateDefault(service_locator); +command_buffer::parse_error::ParseError RendererCB::GetParseError() { + return helper_->GetParseError(); } // Creates and returns a platform specific RenderDepthStencilSurface object. @@ -330,4 +275,180 @@ RenderDepthStencilSurface::Ref RendererCB::CreateDepthStencilSurface( height, this)); } + +Renderer::InitStatus RendererCB::InitPlatformSpecific( + const DisplayWindow& display_window, + bool off_screen) { + if (off_screen) { + // TODO: Off-screen support ? + return UNINITIALIZED; // equivalent to 0/false + } + + const DisplayWindowCB& display_platform = + static_cast<const DisplayWindowCB&>(display_window); + + npp_ = display_platform.npp(); + command_buffer_ = display_platform.command_buffer(); + DCHECK(command_buffer_.Get()); + + // Create and initialize a CommandBufferHelper. + helper_ = new CommandBufferHelper(npp_, command_buffer_); + if (!helper_->Initialize()) { + Destroy(); + return INITIALIZATION_ERROR; + } + + // Create and map a block of memory for the transfer buffer. + transfer_shm_ = CreateSharedMemory(transfer_memory_size_, npp_); + if (!transfer_shm_.Get()) { + Destroy(); + return INITIALIZATION_ERROR; + } + size_t size_bytes; + transfer_shm_address_ = NPBrowser::get()->MapMemory(npp_, + transfer_shm_.Get(), + &size_bytes); + if (!transfer_shm_address_) { + Destroy(); + return INITIALIZATION_ERROR; + } + DCHECK(size_bytes == transfer_memory_size_); + + // Register the transfer buffer so it can be identified with an integer + // in future commands. + if (!NPInvoke(npp_, command_buffer_, "registerObject", transfer_shm_, + &transfer_shm_id_)) { + Destroy(); + return INITIALIZATION_ERROR; + } + DCHECK_GE(transfer_shm_id_, 0); + + // Insert a token. + frame_token_ = helper_->InsertToken(); + if (frame_token_ < 0) { + Destroy(); + return INITIALIZATION_ERROR; + } + + // Create a fenced allocator. + allocator_ = new FencedAllocatorWrapper(transfer_memory_size_, + helper_, + transfer_shm_address_); + + SetClientSize(display_platform.width(), display_platform.height()); + + return SUCCESS; +} + +static const unsigned int kDefaultCommandBufferSize = 256 << 10; + +// This should be enough to hold the biggest possible buffer +// (2048x2048xABGR16F texture = 32MB) +static const int32 kDefaultTransferMemorySize = 32 << 20; + +RendererCBLocal *RendererCBLocal::CreateDefault( + ServiceLocator* service_locator) { + return new RendererCBLocal(service_locator, + kDefaultTransferMemorySize); +} + +RendererCBLocal::RendererCBLocal(ServiceLocator* service_locator, + int32 transfer_memory_size) + : RendererCB(service_locator, transfer_memory_size) { +} + +RendererCBLocal::~RendererCBLocal() { +} + +NPObjectPointer<CommandBuffer> RendererCBLocal::CreateCommandBuffer( + NPP npp, void* hwnd, int32 size) { +#if defined(OS_WIN) + NPObjectPointer<SharedMemory> ring_buffer = + NPCreateObject<SharedMemory>(npp); + if (!ring_buffer->Initialize(size)) + return NPObjectPointer<CommandBuffer>(); + + size_t mapped_size; + if (!NPBrowser::get()->MapMemory(npp, + ring_buffer.Get(), + &mapped_size)) { + return NPObjectPointer<CommandBuffer>(); + } + + DCHECK(mapped_size == size); + + NPObjectPointer<CommandBuffer> command_buffer = + NPCreateObject<CommandBuffer>(npp); + if (!command_buffer->Initialize(ring_buffer)) + return NPObjectPointer<CommandBuffer>(); + + scoped_refptr<GPUProcessor> gpu_processor( + new GPUProcessor(npp, command_buffer.Get())); + if (!gpu_processor->Initialize(reinterpret_cast<HWND>(hwnd))) + return NPObjectPointer<CommandBuffer>(); + + command_buffer->SetPutOffsetChangeCallback( + NewCallback(gpu_processor.get(), &GPUProcessor::ProcessCommands)); + + return command_buffer; + +#else + return NPObjectPointer<CommandBuffer>(); +#endif +} + +NPObjectPointer<NPObject> RendererCBLocal::CreateSharedMemory(int32 size, + NPP npp) { + NPObjectPointer<SharedMemory> shared_memory = + NPCreateObject<SharedMemory>(npp); + + if (!shared_memory->Initialize(size)) + return NPObjectPointer<NPObject>(); + + return shared_memory; +} + +RendererCBRemote *RendererCBRemote::CreateDefault( + ServiceLocator* service_locator) { + return new RendererCBRemote(service_locator, + kDefaultTransferMemorySize); +} + +RendererCBRemote::RendererCBRemote(ServiceLocator* service_locator, + int32 transfer_memory_size) + : RendererCB(service_locator, transfer_memory_size) { +} + +RendererCBRemote::~RendererCBRemote() { +} + +NPObjectPointer<NPObject> RendererCBRemote::CreateSharedMemory(int32 size, + NPP npp) { + NPObjectPointer<NPObject> shared_memory; + + NPObjectPointer<NPObject> window = NPObjectPointer<NPObject>::FromReturned( + NPBrowser::get()->GetWindowNPObject(npp)); + if (!window.Get()) + return shared_memory; + + NPObjectPointer<NPObject> chromium; + if (!NPGetProperty(npp, window, "chromium", &chromium) || !chromium.Get()) + return shared_memory; + + NPObjectPointer<NPObject> system; + if (!NPGetProperty(npp, chromium, "system", &system) || !system.Get()) + return shared_memory; + + if (!NPInvoke(npp, system, "createSharedMemory", size, + &shared_memory)) { + return shared_memory; + } + + return shared_memory; +} + +Renderer* Renderer::CreateDefaultRenderer(ServiceLocator* service_locator) { + return RendererCBLocal::CreateDefault(service_locator); +} + } // namespace o3d diff --git a/o3d/core/cross/command_buffer/renderer_cb.h b/o3d/core/cross/command_buffer/renderer_cb.h index 643e05e..5668c21 100644 --- a/o3d/core/cross/command_buffer/renderer_cb.h +++ b/o3d/core/cross/command_buffer/renderer_cb.h @@ -38,9 +38,11 @@ #include "core/cross/precompile.h" #include <vector> #include "core/cross/renderer.h" -#include "command_buffer/common/cross/rpc.h" +#include "command_buffer/common/cross/constants.h" #include "command_buffer/common/cross/resource.h" #include "command_buffer/client/cross/id_allocator.h" +#include "gpu_plugin/command_buffer.h" +#include "gpu_plugin/np_utils/np_object_pointer.h" namespace o3d { namespace command_buffer { @@ -61,15 +63,7 @@ class RendererCB : public Renderer { typedef command_buffer::IdAllocator IdAllocator; typedef command_buffer::FencedAllocatorWrapper FencedAllocatorWrapper; - // Creates a default RendererCB. - // The default command buffer is 256K entries. - // The default transfer buffer is 16MB. - static RendererCB *CreateDefault(ServiceLocator* service_locator); - ~RendererCB(); - - // Initialises the renderer for use, claiming hardware resources. - virtual InitStatus InitPlatformSpecific(const DisplayWindow& display_window, - bool off_screen); + virtual ~RendererCB(); // Handles the plugin resize event. virtual void Resize(int width, int height); @@ -170,13 +164,8 @@ class RendererCB : public Renderer { // Gets the command buffer helper. command_buffer::CommandBufferHelper *helper() const { return helper_; } - // Gets the sync interface. - command_buffer::BufferSyncInterface *sync_interface() const { - return sync_interface_; - } - // Gets the registered ID of the transfer shared memory. - unsigned int transfer_shm_id() const { return transfer_shm_id_; } + int32 transfer_shm_id() const { return transfer_shm_id_; } // Gets the base address of the transfer shared memory. void *transfer_shm_address() const { return transfer_shm_address_; } @@ -189,10 +178,11 @@ class RendererCB : public Renderer { // Overridden from Renderer. virtual const int* GetRGBAUByteNSwizzleTable(); + command_buffer::parse_error::ParseError GetParseError(); + protected: // Protected so that callers are forced to call the factory method. - RendererCB(ServiceLocator* service_locator, unsigned int command_buffer_size, - unsigned int transfer_memory_size); + RendererCB(ServiceLocator* service_locator, int32 transfer_memory_size); // Overridden from Renderer. virtual bool PlatformSpecificBeginDraw(); @@ -254,19 +244,24 @@ class RendererCB : public Renderer { // Overridden from Renderer. virtual void ApplyDirtyStates(); - private: - // Performs cross-platform initialization. - void InitCommon(unsigned int width, unsigned int height); + protected: + // Initializes the renderer for use, claiming hardware resources. + virtual InitStatus InitPlatformSpecific(const DisplayWindow& display_window, + bool off_screen); - unsigned int cmd_buffer_size_; - unsigned int transfer_memory_size_; - command_buffer::RPCShmHandle transfer_shm_; - unsigned int transfer_shm_id_; + // Create a shared memory object of the given size. + virtual gpu_plugin::NPObjectPointer<NPObject> + CreateSharedMemory(int32 size, NPP npp) = 0; + + private: + int32 transfer_memory_size_; + gpu_plugin::NPObjectPointer<NPObject> transfer_shm_; + int32 transfer_shm_id_; void *transfer_shm_address_; - command_buffer::BufferSyncInterface *sync_interface_; + NPP npp_; + gpu_plugin::NPObjectPointer<NPObject> command_buffer_; command_buffer::CommandBufferHelper *helper_; FencedAllocatorWrapper *allocator_; - Win32CBServer *cb_server_; IdAllocator vertex_buffer_ids_; IdAllocator index_buffer_ids_; @@ -277,7 +272,7 @@ class RendererCB : public Renderer { IdAllocator sampler_ids_; IdAllocator render_surface_ids_; IdAllocator depth_surface_ids_; - unsigned int frame_token_; + int32 frame_token_; class StateManager; scoped_ptr<StateManager> state_manager_; @@ -285,6 +280,53 @@ class RendererCB : public Renderer { DISALLOW_COPY_AND_ASSIGN(RendererCB); }; +// This subclass initializes itself with a locally created in-process +// CommandBuffer and GPUProcessor. This class will eventually go away and the +// code in RendererCBRemote will be merged into RendererCB. +class RendererCBLocal : public RendererCB { + public: + static gpu_plugin::NPObjectPointer<gpu_plugin::CommandBuffer> + CreateCommandBuffer(NPP npp, void* hwnd, int32 size); + + // Creates a default RendererCBLocal. + static RendererCBLocal *CreateDefault(ServiceLocator* service_locator); + + protected: + RendererCBLocal(ServiceLocator* service_locator, + int32 transfer_memory_size); + virtual ~RendererCBLocal(); + + // Create a shared memory object of the given size using the system services + // library directly. + virtual gpu_plugin::NPObjectPointer<NPObject> + CreateSharedMemory(int32 size, NPP npp); + + private: + DISALLOW_COPY_AND_ASSIGN(RendererCBLocal); +}; + +// This subclass initializes itself with a remotely created, potentially out- +// of-process CommandBuffer. It requires that the browser supports the "system +// service" to create shared memory, which is not available in the mange branch +// of Chrome. Use RendererCBLocal for now. +class RendererCBRemote : public RendererCB { + public: + // Creates a default RendererCBRemote. + static RendererCBRemote *CreateDefault(ServiceLocator* service_locator); + + protected: + RendererCBRemote(ServiceLocator* service_locator, int32 transfer_memory_size); + virtual ~RendererCBRemote(); + + // Create a shared memory object using the browser's + // chromium.system.createSharedMemory method. + virtual gpu_plugin::NPObjectPointer<NPObject> + CreateSharedMemory(int32 size, NPP npp); + + private: + DISALLOW_COPY_AND_ASSIGN(RendererCBRemote); +}; + } // namespace o3d #endif // O3D_CORE_CROSS_COMMAND_BUFFER_RENDERER_CB_H_ diff --git a/o3d/core/cross/renderer_test.cc b/o3d/core/cross/renderer_test.cc index 680d377..2cde1a9 100644 --- a/o3d/core/cross/renderer_test.cc +++ b/o3d/core/cross/renderer_test.cc @@ -78,6 +78,10 @@ TEST_F(RendererTest, CreateDefaultRenderer) { TEST_F(RendererTest, InitAndDestroyRenderer) { +// TODO(apatrick): This test will not work as is with command buffers because +// it attempts to create a Renderer using the same ring buffer as the +// Renderer created in main. +#if !defined(RENDERER_CB) scoped_ptr<Renderer> renderer( Renderer::CreateDefaultRenderer(service_locator())); EXPECT_TRUE(renderer->Init(*g_display_window, false)); @@ -100,6 +104,7 @@ TEST_F(RendererTest, InitAndDestroyRenderer) { // check that the renderer no longer has a Cg Context. EXPECT_FALSE(gl_renderer->cg_context() != NULL); #endif +#endif // RENDERER_CB } // Offscreen is only supported on D3D currently diff --git a/o3d/core/win/command_buffer/win32_cb_server.cc b/o3d/core/win/command_buffer/win32_cb_server.cc deleted file mode 100644 index 7b70466..0000000 --- a/o3d/core/win/command_buffer/win32_cb_server.cc +++ /dev/null @@ -1,120 +0,0 @@ -/* - * Copyright 2009, Google Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - - -// This file contains the implementation of the Win32CBServer class. - -#include "core/cross/precompile.h" -#include "core/win/command_buffer/win32_cb_server.h" -#include "command_buffer/service/cross/buffer_rpc.h" -#include "command_buffer/service/cross/cmd_buffer_engine.h" -#include "command_buffer/service/cross/gapi_decoder.h" - -namespace o3d { - -using command_buffer::GAPIDecoder; -using command_buffer::IMCSender; -using command_buffer::IMCMessageProcessor; -using command_buffer::BufferSyncProxy; -using command_buffer::CommandBufferEngine; - -Win32CBServer::Win32CBServer(HWND window, Features* features) - : gapi_(), - proxy_(NULL), - imc_sender_(NULL), - thread_(NULL) { - gapi_.set_hwnd(window); - -#if defined(CB_RENDERER_GL) - gapi_.set_anti_aliased(!features->not_anti_aliased()); -#endif - - nacl::Handle handles[2]; - nacl::SocketPair(handles); - - socket_pair_[0] = nacl::CreateImcDesc(handles[0]); - socket_pair_[1] = nacl::CreateImcDesc(handles[1]); - imc_sender_.reset(new IMCSender(socket_pair_[0])); - proxy_.reset(new BufferSyncProxy(imc_sender_.get())); - - thread_ = ::CreateThread(NULL, 0, ThreadMain, this, 0, NULL); -} - -Win32CBServer::~Win32CBServer() { - imc_sender_->SendCall(command_buffer::POISONED_MESSAGE_ID, NULL, 0, NULL, - 0); - ::WaitForSingleObject(thread_, INFINITE); - ::CloseHandle(thread_); - - nacl::Close(socket_pair_[0]); - nacl::Close(socket_pair_[1]); -} - -DWORD WINAPI Win32CBServer::ThreadMain(LPVOID param) { - Win32CBServer *server = static_cast<Win32CBServer *>(param); - - scoped_ptr<GAPIDecoder> decoder(new GAPIDecoder(&server->gapi_)); - scoped_ptr<CommandBufferEngine> engine( - new CommandBufferEngine(decoder.get())); - decoder->set_engine(engine.get()); - - IMCMessageProcessor processor(server->socket_pair_[1], engine->rpc_impl()); - engine->set_process_interface(&processor); - IMCSender sender(server->socket_pair_[1]); - engine->set_client_rpc(&sender); - - server->gapi_.Initialize(); - bool running = true; - while (running) { - MSG msg; - while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { - TranslateMessage(&msg); - DispatchMessage(&msg); - if (msg.message == WM_QUIT) { - running = false; - break; - } - } - if (!running) break; - // DoWork() will block if there is nothing to be done, meaning we are only - // going to handle message after commands are sent. It should happen at - // least once a frame, so it's OK. - // TODO: figure out a way to wait on the socket OR messages with - // MsgWaitForMultipleObjects. Asynchronous ("overlapped") read on the - // socket may let us do that. - running = engine->DoWork(); - } - server->gapi_.Destroy(); - - return 0; -} - -} // namespace o3d diff --git a/o3d/core/win/command_buffer/win32_cb_server.h b/o3d/core/win/command_buffer/win32_cb_server.h deleted file mode 100644 index 49a34f7..0000000 --- a/o3d/core/win/command_buffer/win32_cb_server.h +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright 2009, Google Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - - -// This file declares the Win32CBServer class, helper class that runs a command -// buffer server in a separate win32 thread. - -#ifndef O3D_CORE_WIN_COMMAND_BUFFER_WIN32_CB_SERVER_H_ -#define O3D_CORE_WIN_COMMAND_BUFFER_WIN32_CB_SERVER_H_ - -#include "core/cross/precompile.h" -#include "core/cross/features.h" -#include "command_buffer/common/cross/rpc_imc.h" -#include "command_buffer/client/cross/buffer_sync_proxy.h" -#if defined(CB_SERVICE_D3D9) -#include "command_buffer/service/win/d3d9/gapi_d3d9.h" -#elif defined(CB_SERVICE_GL) -#include "command_buffer/service/cross/gl/gapi_gl.h" -#endif - - -namespace o3d { - -// The current Renderer API assumes we connect directly to the window. This -// class creates a command buffer server in a separate thread, and sets up the -// communication socket. -// This code will go away once we fix the API, and provide a separate mechanism -// to connect to the service. -class Win32CBServer { - public: - explicit Win32CBServer(HWND window, Features* features); - ~Win32CBServer(); - - // Gets the (client-side) command buffer interface. - command_buffer::BufferSyncInterface *GetInterface() { return proxy_.get(); } - - private: - static DWORD WINAPI ThreadMain(LPVOID param); - -#if defined(CB_SERVICE_D3D9) - command_buffer::GAPID3D9 gapi_; -#elif defined(CB_SERVICE_GL) - command_buffer::GAPIGL gapi_; -#endif - nacl::HtpHandle socket_pair_[2]; - scoped_ptr<command_buffer::IMCSender> imc_sender_; - scoped_ptr<command_buffer::BufferSyncProxy> proxy_; - HANDLE thread_; -}; - -} // namespace o3d - -#endif // O3D_CORE_WIN_COMMAND_BUFFER_WIN32_CB_SERVER_H_ diff --git a/o3d/gpu_plugin/command_buffer.cc b/o3d/gpu_plugin/command_buffer.cc index 3dc35b8..2bdb686 100644 --- a/o3d/gpu_plugin/command_buffer.cc +++ b/o3d/gpu_plugin/command_buffer.cc @@ -143,5 +143,11 @@ int32 CommandBuffer::ResetParseError() { return last_error; } +void CommandBuffer::SetParseError(int32 parse_error) { + if (parse_error_ == 0) { + parse_error_ = parse_error; + } +} + } // namespace gpu_plugin } // namespace o3d diff --git a/o3d/gpu_plugin/command_buffer.h b/o3d/gpu_plugin/command_buffer.h index 492bb18..51ce2d0 100644 --- a/o3d/gpu_plugin/command_buffer.h +++ b/o3d/gpu_plugin/command_buffer.h @@ -90,9 +90,7 @@ class CommandBuffer : public DefaultNPObject<NPObject> { int32 ResetParseError(); // Allows the reader to set the current parse error. - void SetParseError(int32 parse_error) { - parse_error_ = parse_error; - } + void SetParseError(int32 parse_error); // Returns whether the command buffer is in the error state. bool GetErrorStatus() { diff --git a/o3d/gpu_plugin/gpu_plugin.gyp b/o3d/gpu_plugin/gpu_plugin.gyp index 8ec77c7..cf23d18 100644 --- a/o3d/gpu_plugin/gpu_plugin.gyp +++ b/o3d/gpu_plugin/gpu_plugin.gyp @@ -15,22 +15,10 @@ ], 'include_dirs': [ '../..', - '../../third_party/npapi', - - # Chrome NPAPI header dir appears before the O3D one so it takes - # priority. TODO(apatrick): one set of NPAPI headers. - '../../third_party/npapi/bindings', - '../../third_party/npapi/include', ], 'all_dependent_settings': { 'include_dirs': [ '../..', - '../../third_party/npapi', - - # Chrome NPAPI header dir appears before the O3D one so it takes - # priority. TODO(apatrick): one set of NPAPI headers. - '../../third_party/npapi/bindings', - '../../third_party/npapi/include', ], }, # 'all_dependent_settings' 'sources': [ @@ -50,13 +38,16 @@ 'np_utils/np_object_mock.h', 'np_utils/np_object_pointer.h', 'np_utils/np_plugin_object.h', + 'np_utils/np_plugin_object_mock.h', 'np_utils/np_plugin_object_factory.cc', 'np_utils/np_plugin_object_factory.h', 'np_utils/np_plugin_object_factory_mock.h', - 'np_utils/np_plugin_object_mock.h', 'np_utils/np_utils.cc', 'np_utils/np_utils.h', 'np_utils/webkit_browser.h', + 'system_services/shared_memory.cc', + 'system_services/shared_memory.h', + 'system_services/shared_memory_mock.h', ], }, @@ -80,165 +71,10 @@ 'np_utils/np_class_unittest.cc', 'np_utils/np_object_pointer_unittest.cc', 'np_utils/np_utils_unittest.cc', - ], - }, - - { - 'target_name': 'system_services', - 'type': '<(library)', - 'dependencies': [ - '../../base/base.gyp:base', - 'np_utils', - ], - 'include_dirs': [ - '../..', - ], - 'sources': [ - 'system_services/shared_memory.cc', - 'system_services/shared_memory.h', - 'system_services/shared_memory_mock.h', - 'system_services/shared_memory_public.h', - ], - }, - - # This is a standalone executable until O3D is fully moved over to using - # gyp. At that point these can become part of the regular O3D unit tests. - { - 'target_name': 'system_services_unittests', - 'type': 'executable', - 'dependencies': [ - 'system_services', - '../../testing/gmock.gyp:gmock', - '../../testing/gmock.gyp:gmockmain', - '../../testing/gtest.gyp:gtest', - ], - 'include_dirs': [ - '../..', - ], - 'sources': [ 'system_services/shared_memory_unittest.cc', ], }, - # This builds a subset of the O3D command buffer common library. This is a - # separate library for the time being because I need a subset that is not - # dependent on NaCl. - { - 'target_name': 'command_buffer_common_subset', - 'type': '<(library)', - 'include_dirs': [ - '..', - '../..', - ], - 'all_dependent_settings': { - 'include_dirs': [ - '..', - ], - }, # 'all_dependent_settings' - 'sources': [ - '../command_buffer/common/cross/bitfield_helpers.h', - '../command_buffer/common/cross/cmd_buffer_format.h', - '../command_buffer/common/cross/gapi_interface.h', - '../command_buffer/common/cross/logging.h', - '../command_buffer/common/cross/mocks.h', - '../command_buffer/common/cross/resource.cc', - '../command_buffer/common/cross/resource.h', - '../command_buffer/common/cross/types.h', - ], - }, - - # This builds a subset of the O3D command buffer service. This is a separate - # library for the time being because I need a subset that is not dependent - # on NaCl. - { - 'target_name': 'command_buffer_service_subset', - 'type': '<(library)', - 'include_dirs': [ - '..', - '../..', - ], - 'all_dependent_settings': { - 'include_dirs': [ - '..', - ], - }, # 'all_dependent_settings' - 'dependencies': [ - 'command_buffer_common_subset', - ], - 'sources': [ - '../command_buffer/service/cross/cmd_parser.cc', - '../command_buffer/service/cross/cmd_parser.h', - '../command_buffer/service/cross/effect_utils.cc', - '../command_buffer/service/cross/effect_utils.h', - '../command_buffer/service/cross/gapi_decoder.cc', - '../command_buffer/service/cross/gapi_decoder.h', - '../command_buffer/service/cross/mocks.h', - '../command_buffer/service/cross/precompile.cc', - '../command_buffer/service/cross/precompile.h', - '../command_buffer/service/cross/resource.cc', - '../command_buffer/service/cross/resource.h', - '../command_buffer/service/cross/texture_utils.cc', - '../command_buffer/service/cross/texture_utils.h', - ], - - 'conditions': [ - ['OS == "win"', - { - 'sources': [ - '../command_buffer/service/win/d3d9/d3d9_utils.h', - '../command_buffer/service/win/d3d9/effect_d3d9.cc', - '../command_buffer/service/win/d3d9/effect_d3d9.h', - '../command_buffer/service/win/d3d9/gapi_d3d9.cc', - '../command_buffer/service/win/d3d9/gapi_d3d9.h', - '../command_buffer/service/win/d3d9/geometry_d3d9.cc', - '../command_buffer/service/win/d3d9/geometry_d3d9.h', - '../command_buffer/service/win/d3d9/render_surface_d3d9.cc', - '../command_buffer/service/win/d3d9/render_surface_d3d9.h', - '../command_buffer/service/win/d3d9/sampler_d3d9.cc', - '../command_buffer/service/win/d3d9/sampler_d3d9.h', - '../command_buffer/service/win/d3d9/states_d3d9.cc', - '../command_buffer/service/win/d3d9/texture_d3d9.cc', - '../command_buffer/service/win/d3d9/texture_d3d9.h', - ], # 'sources' - 'include_dirs': [ - '$(DXSDK_DIR)/Include', - ], - 'all_dependent_settings': { - 'include_dirs': [ - '$(DXSDK_DIR)/Include', - ], - }, # 'all_dependent_settings' - }, - ], - ['OS == "mac" or OS == "linux"', - { - 'sources': [ - '../command_buffer/service/cross/gl/effect_gl.cc', - '../command_buffer/service/cross/gl/effect_gl.h', - '../command_buffer/service/cross/gl/gapi_gl.cc', - '../command_buffer/service/cross/gl/gapi_gl.h', - '../command_buffer/service/cross/gl/geometry_gl.cc', - '../command_buffer/service/cross/gl/geometry_gl.h', - '../command_buffer/service/cross/gl/gl_utils.h', - '../command_buffer/service/cross/gl/sampler_gl.cc', - '../command_buffer/service/cross/gl/sampler_gl.h', - '../command_buffer/service/cross/gl/states_gl.cc', - '../command_buffer/service/cross/gl/texture_gl.cc', - '../command_buffer/service/cross/gl/texture_gl.h', - ], # 'sources' - }, - ], - ['OS == "linux"', - { - 'sources': [ - '../command_buffer/service/linux/x_utils.cc', - '../command_buffer/service/linux/x_utils.h', - ], - }, - ], - ], - }, - # These can eventually be merged back into the gpu_plugin target. There # separated for now so O3D can statically link against them and use command # buffers in-process without the GPU plugin. @@ -247,16 +83,14 @@ 'type': '<(library)', 'dependencies': [ '../../base/base.gyp:base', - 'command_buffer_service_subset', + '../command_buffer/command_buffer.gyp:command_buffer_service', 'np_utils', ], 'include_dirs': [ - '..', '../..', ], 'all_dependent_settings': { 'include_dirs': [ - '..', '../..', ], }, # 'all_dependent_settings' @@ -298,10 +132,9 @@ 'target_name': 'gpu_plugin_unittests', 'type': 'executable', 'dependencies': [ - 'command_buffer_service_subset', + '../command_buffer/command_buffer.gyp:command_buffer_service', 'gpu_plugin', 'np_utils', - 'system_services', '../../testing/gmock.gyp:gmock', '../../testing/gmock.gyp:gmockmain', '../../testing/gtest.gyp:gtest', diff --git a/o3d/gpu_plugin/gpu_processor.cc b/o3d/gpu_plugin/gpu_processor.cc index b757a37..058ffa5 100644 --- a/o3d/gpu_plugin/gpu_processor.cc +++ b/o3d/gpu_plugin/gpu_processor.cc @@ -7,6 +7,9 @@ namespace o3d { namespace gpu_plugin { +GPUProcessor::~GPUProcessor() { +} + namespace { void InvokeProcessCommands(void* data) { static_cast<GPUProcessor*>(data)->ProcessCommands(); @@ -21,16 +24,16 @@ void GPUProcessor::ProcessCommands() { int commands_processed = 0; while (commands_processed < commands_per_update_ && !parser_->IsEmpty()) { - command_buffer::BufferSyncInterface::ParseError parse_error = + command_buffer::parse_error::ParseError parse_error = parser_->ProcessCommand(); switch (parse_error) { - case command_buffer::BufferSyncInterface::kParseUnknownCommand: - case command_buffer::BufferSyncInterface::kParseInvalidArguments: + case command_buffer::parse_error::kParseUnknownCommand: + case command_buffer::parse_error::kParseInvalidArguments: command_buffer_->SetParseError(parse_error); break; - case command_buffer::BufferSyncInterface::kParseInvalidSize: - case command_buffer::BufferSyncInterface::kParseOutOfBounds: + case command_buffer::parse_error::kParseInvalidSize: + case command_buffer::parse_error::kParseOutOfBounds: command_buffer_->SetParseError(parse_error); command_buffer_->RaiseErrorStatus(); return; @@ -46,9 +49,9 @@ void GPUProcessor::ProcessCommands() { } } -void *GPUProcessor::GetSharedMemoryAddress(unsigned int shm_id) { +void *GPUProcessor::GetSharedMemoryAddress(int32 shm_id) { NPObjectPointer<NPObject> shared_memory = - command_buffer_->GetRegisteredObject(static_cast<int32>(shm_id)); + command_buffer_->GetRegisteredObject(shm_id); size_t size; return NPBrowser::get()->MapMemory(npp_, shared_memory.Get(), &size); @@ -56,9 +59,9 @@ void *GPUProcessor::GetSharedMemoryAddress(unsigned int shm_id) { // TODO(apatrick): Consolidate this with the above and return both the address // and size. -size_t GPUProcessor::GetSharedMemorySize(unsigned int shm_id) { +size_t GPUProcessor::GetSharedMemorySize(int32 shm_id) { NPObjectPointer<NPObject> shared_memory = - command_buffer_->GetRegisteredObject(static_cast<int32>(shm_id)); + command_buffer_->GetRegisteredObject(shm_id); size_t size; NPBrowser::get()->MapMemory(npp_, shared_memory.Get(), &size); @@ -66,8 +69,8 @@ size_t GPUProcessor::GetSharedMemorySize(unsigned int shm_id) { return size; } -void GPUProcessor::set_token(unsigned int token) { - command_buffer_->SetToken(static_cast<int32>(token)); +void GPUProcessor::set_token(int32 token) { + command_buffer_->SetToken(token); } } // namespace gpu_plugin diff --git a/o3d/gpu_plugin/gpu_processor.h b/o3d/gpu_plugin/gpu_processor.h index 246b277..f0b9a4b 100644 --- a/o3d/gpu_plugin/gpu_processor.h +++ b/o3d/gpu_plugin/gpu_processor.h @@ -5,6 +5,7 @@ #ifndef O3D_GPU_PLUGIN_GPU_PROCESSOR_H_ #define O3D_GPU_PLUGIN_GPU_PROCESSOR_H_ +#include "base/ref_counted.h" #include "base/scoped_ptr.h" #include "base/shared_memory.h" #include "o3d/command_buffer/service/cross/cmd_buffer_engine.h" @@ -22,16 +23,16 @@ namespace gpu_plugin { // This class processes commands in a command buffer. It is event driven and // posts tasks to the current message loop to do additional work. -class GPUProcessor : public base::RefCountedThreadSafe<GPUProcessor>, - public command_buffer::CommandBufferUpcallInterface { +class GPUProcessor : public ::base::RefCounted<GPUProcessor>, + public command_buffer::CommandBufferEngine { public: GPUProcessor(NPP npp, - const NPObjectPointer<CommandBuffer>& command_buffer); + CommandBuffer* command_buffer); #if defined(OS_WIN) // This constructor is for unit tests. GPUProcessor(NPP npp, - const NPObjectPointer<CommandBuffer>& command_buffer, + CommandBuffer* command_buffer, command_buffer::GAPID3D9* gapi, command_buffer::GAPIDecoder* decoder, command_buffer::CommandParser* parser, @@ -40,6 +41,8 @@ class GPUProcessor : public base::RefCountedThreadSafe<GPUProcessor>, bool Initialize(HWND hwnd); #endif // OS_WIN + virtual ~GPUProcessor(); + void Destroy(); void ProcessCommands(); @@ -48,25 +51,30 @@ class GPUProcessor : public base::RefCountedThreadSafe<GPUProcessor>, void SetWindow(HWND handle, int width, int height); #endif - // Implementation of CommandBufferUpcallInterface. + // Implementation of CommandBufferEngine. // Gets the base address of a registered shared memory buffer. // Parameters: // shm_id: the identifier for the shared memory buffer. - virtual void *GetSharedMemoryAddress(unsigned int shm_id); + virtual void *GetSharedMemoryAddress(int32 shm_id); // Gets the size of a registered shared memory buffer. // Parameters: // shm_id: the identifier for the shared memory buffer. - virtual size_t GetSharedMemorySize(unsigned int shm_id); + virtual size_t GetSharedMemorySize(int32 shm_id); // Sets the token value. - virtual void set_token(unsigned int token); + virtual void set_token(int32 token); private: NPP npp_; - NPObjectPointer<CommandBuffer> command_buffer_; - scoped_ptr<base::SharedMemory> mapped_ring_buffer_; + + // The GPUProcessor holds a weak reference to the CommandBuffer. The + // CommandBuffer owns the GPUProcessor and holds a strong reference to it + // through the ProcessCommands callback. + CommandBuffer* command_buffer_; + + scoped_ptr< ::base::SharedMemory> mapped_ring_buffer_; int commands_per_update_; #if defined(OS_WIN) @@ -79,4 +87,27 @@ class GPUProcessor : public base::RefCountedThreadSafe<GPUProcessor>, } // namespace gpu_plugin } // namespace o3d +// Callbacks to the GPUProcessor hold a reference count. +template <typename Method> +class CallbackStorage<o3d::gpu_plugin::GPUProcessor, Method> { + public: + CallbackStorage(o3d::gpu_plugin::GPUProcessor* obj, Method method) + : obj_(obj), + meth_(method) { + DCHECK(obj_); + obj_->AddRef(); + } + + ~CallbackStorage() { + obj_->Release(); + } + + protected: + o3d::gpu_plugin::GPUProcessor* obj_; + Method meth_; + + private: + DISALLOW_COPY_AND_ASSIGN(CallbackStorage); +}; + #endif // O3D_GPU_PLUGIN_GPU_PROCESSOR_H_ diff --git a/o3d/gpu_plugin/gpu_processor_win.cc b/o3d/gpu_plugin/gpu_processor_win.cc index 30f963f..a9fdae1 100644 --- a/o3d/gpu_plugin/gpu_processor_win.cc +++ b/o3d/gpu_plugin/gpu_processor_win.cc @@ -10,17 +10,18 @@ namespace o3d { namespace gpu_plugin { GPUProcessor::GPUProcessor(NPP npp, - const NPObjectPointer<CommandBuffer>& command_buffer) + CommandBuffer* command_buffer) : npp_(npp), command_buffer_(command_buffer), commands_per_update_(100) { + DCHECK(command_buffer); gapi_.reset(new command_buffer::GAPID3D9); decoder_.reset(new command_buffer::GAPIDecoder(gapi_.get())); decoder_->set_engine(this); } GPUProcessor::GPUProcessor(NPP npp, - const NPObjectPointer<CommandBuffer>& command_buffer, + CommandBuffer* command_buffer, command_buffer::GAPID3D9* gapi, command_buffer::GAPIDecoder* decoder, command_buffer::CommandParser* parser, @@ -28,6 +29,7 @@ GPUProcessor::GPUProcessor(NPP npp, : npp_(npp), command_buffer_(command_buffer), commands_per_update_(commands_per_update) { + DCHECK(command_buffer); gapi_.reset(gapi); decoder_.reset(decoder); parser_.reset(parser); diff --git a/o3d/gpu_plugin/np_utils/np_browser.cc b/o3d/gpu_plugin/np_utils/np_browser.cc index f6f8189..e3756c7 100644 --- a/o3d/gpu_plugin/np_utils/np_browser.cc +++ b/o3d/gpu_plugin/np_utils/np_browser.cc @@ -8,7 +8,10 @@ #if defined(O3D_IN_CHROME) #include "webkit/glue/plugins/nphostapi.h" #else -#include "npupp.h" +#include "o3d/third_party/npapi/include/npupp.h" + +// TODO: Remove this when we figure out what to do about NPN_MapMemory. +#include "o3d/gpu_plugin/system_services/shared_memory.h" #endif namespace o3d { @@ -118,7 +121,13 @@ void NPBrowser::PluginThreadAsyncCall(NPP npp, void* NPBrowser::MapMemory(NPP npp, NPObject* object, size_t* size) { + // NPN_MapMemory is an experiment. It only exists in NPNetscapeFuncs in + // a hacked version of Chromium. +#if defined(O3D_IN_CHROME) return netscape_funcs_->mapmemory(npp, object, size); +#else + return NPN_MapMemory(npp, object, size); +#endif } } // namespace gpu_plugin diff --git a/o3d/gpu_plugin/np_utils/np_browser_stub.cc b/o3d/gpu_plugin/np_utils/np_browser_stub.cc index d6d3e87..c04affe 100644 --- a/o3d/gpu_plugin/np_utils/np_browser_stub.cc +++ b/o3d/gpu_plugin/np_utils/np_browser_stub.cc @@ -3,6 +3,7 @@ // found in the LICENSE file. #include "o3d/gpu_plugin/np_utils/np_browser_stub.h" +#include "o3d/gpu_plugin/system_services/shared_memory.h" #include "base/logging.h" #include "base/message_loop.h" @@ -116,8 +117,7 @@ void StubNPBrowser::PluginThreadAsyncCall( void* StubNPBrowser::MapMemory(NPP npp, NPObject* object, size_t* size) { - *size = 0; - return NULL; + return NPN_MapMemory(npp, object, size); } } // namespace gpu_plugin diff --git a/o3d/gpu_plugin/np_utils/np_headers.h b/o3d/gpu_plugin/np_utils/np_headers.h index 6a2a3c6..f11a054 100644 --- a/o3d/gpu_plugin/np_utils/np_headers.h +++ b/o3d/gpu_plugin/np_utils/np_headers.h @@ -9,10 +9,19 @@ // Chrome and O3D NPAPI headers. #define utf8characters UTF8Characters #define utf8length UTF8Length + +#if defined(O3D_IN_CHROME) +#include "third_party/npapi/bindings/npapi.h" +#include "third_party/npapi/bindings/npruntime.h" +#else +#include "o3d/third_party/npapi/include/npapi.h" +#include "o3d/third_party/npapi/include/npruntime.h" +#endif + // Deliberately not including a directory name because Chromium and O3D put // these headers in different directories. -#include "npapi.h" -#include "npruntime.h" +//#include "npapi.h" +//#include "npruntime.h" #undef utf8characters #undef utf8length diff --git a/o3d/gpu_plugin/system_services/shared_memory.h b/o3d/gpu_plugin/system_services/shared_memory.h index 1ee7df4..da47644 100644 --- a/o3d/gpu_plugin/system_services/shared_memory.h +++ b/o3d/gpu_plugin/system_services/shared_memory.h @@ -10,7 +10,7 @@ #include "o3d/gpu_plugin/np_utils/default_np_object.h" #include "o3d/gpu_plugin/np_utils/np_dispatcher.h" #include "o3d/gpu_plugin/np_utils/np_object_pointer.h" -#include "third_party/npapi/bindings/npruntime.h" +#include "o3d/gpu_plugin/np_utils/np_headers.h" namespace o3d { namespace gpu_plugin { @@ -25,7 +25,7 @@ class SharedMemory : public DefaultNPObject<NPObject> { virtual int32 GetSize(); - base::SharedMemory* shared_memory() const { + ::base::SharedMemory* shared_memory() const { return shared_memory_.get(); } @@ -36,7 +36,7 @@ class SharedMemory : public DefaultNPObject<NPObject> { private: NPP npp_; - scoped_ptr<base::SharedMemory> shared_memory_; + scoped_ptr< ::base::SharedMemory> shared_memory_; DISALLOW_COPY_AND_ASSIGN(SharedMemory); }; diff --git a/o3d/main.scons b/o3d/main.scons index c9ae0bf..10976da 100644 --- a/o3d/main.scons +++ b/o3d/main.scons @@ -482,146 +482,6 @@ windows_gl_optimized_env.Append(BUILD_GROUPS = ['most']) AddWindowsOptimizedSettings(windows_gl_optimized_env) environment_list.append(windows_gl_optimized_env) -windows_cb_env = windows_env.Clone() -windows_cb_env.Append( - CPPDEFINES = ['RENDERER_CB', 'CB_SERVICE_D3D9'], - BUILD_COMPONENTS = [ - 'command_buffer/common', - 'command_buffer/service', - 'command_buffer/client' - ], - RENDERER_INCLUDE_PATH = [], - RENDERER_LIB_PATH = [ - 'command_buffer/common', - 'command_buffer/service', - 'command_buffer/client', - ], - # TODO: remove link-time dependency on d3dx9, using dynamic loading - # instead. - RENDERER_LIBS = [ - 'o3dCmdBuf_service', - 'o3dCmdBuf_client', - 'o3dCmdBuf_common', - 'd3d9', 'dxerr', 'd3dx9' - ] + nacl_htp_all_libs -) - -windows_cb_debug_env = windows_cb_env.Clone( - BUILD_TYPE = 'dbg-cb', - BUILD_TYPE_DESCRIPTION = 'Windows Command Buffer debug build', -) - -AddWindowsDebugSettings(windows_cb_debug_env) -environment_list.append(windows_cb_debug_env) - - -windows_cb_optimized_env = windows_cb_env.Clone( - BUILD_TYPE = 'opt-cb', - BUILD_TYPE_DESCRIPTION = 'Windows Command Buffer optimized build', -) - -AddWindowsOptimizedSettings(windows_cb_optimized_env) -environment_list.append(windows_cb_optimized_env) - - -windows_cb_gl_env = windows_env.Clone() -windows_cb_gl_env.Append( - CPPDEFINES = ['RENDERER_CB', 'CB_SERVICE_GL'], - BUILD_COMPONENTS = [ - 'command_buffer/common', - 'command_buffer/service', - 'command_buffer/client' - ], - RENDERER_INCLUDE_PATH = [ - '$GLEW_DIR/include', - '$CG_DIR/include', - ], - RENDERER_LIB_PATH = [ - 'command_buffer/common', - 'command_buffer/service', - 'command_buffer/client', - '$CG_DIR/lib', - '$GLEW_DIR/lib', - ], - RENDERER_LIBS = [ - 'o3dCmdBuf_service', - 'o3dCmdBuf_client', - 'o3dCmdBuf_common', - 'OpenGL32', - 'glew32', - 'cg', - 'cgGL', - ] + nacl_htp_all_libs, -) - -windows_cb_gl_debug_env = windows_cb_gl_env.Clone( - BUILD_TYPE = 'dbg-cb-gl', - BUILD_TYPE_DESCRIPTION = - 'Windows Command Buffer using OpenGL debug build' -) - -AddWindowsDebugSettings(windows_cb_gl_debug_env) -environment_list.append(windows_cb_gl_debug_env) - -windows_cb_gl_optimized_env = windows_cb_gl_env.Clone( - BUILD_TYPE = 'opt-cb-gl', - BUILD_TYPE_DESCRIPTION = - 'Windows Command Buffer using OpenGL optimized build', -) - -AddWindowsOptimizedSettings(windows_cb_gl_optimized_env) -environment_list.append(windows_cb_gl_optimized_env) - - -# These configs are highly very experimental, and just including them -# necessitate downloading the nacl sdk even if they are not active. So include -# them only when a specific flag is passed on the command line. -if ARGUMENTS.get('enable-nacl', ''): - nacl_env = binaries_env.Clone( - tools = ['naclsdk'], - BUILD_COMPONENTS = [ - 'command_buffer/common', - 'command_buffer/client', - 'command_buffer/samples', - ], - # This should be set by hammer but is not... - TARGET_PLATFORM = 'NACL', - # Only the base IMC lib is necessary in nacl - NACL_HTP_LIBS = [nacl_imc_lib], - CCFLAGS = ['-Wstrict-aliasing'], - NACL_VARIANT = 'nacl', - ) - nacl_env.Append( - CPPDEFINES = ['RENDERER_CB'], - RENDERER_INCLUDE_PATH = [], - RENDERER_LIB_PATH = [ - 'command_buffer/common', - 'command_buffer/client', - ], - RENDERER_LIBS = [ - 'o3dCmdBuf_client', - 'o3dCmdBuf_common', - nacl_imc_lib, - ], - ) - nacl_dbg_env = nacl_env.Clone( - BUILD_TYPE = 'dbg-nacl', - BUILD_TYPE_DESCRIPTION = 'NaCl debug build', - ) - nacl_dbg_env.Append( - CCFLAGS = ['-g'], - ) - environment_list.append(nacl_dbg_env) - nacl_opt_env = nacl_env.Clone( - BUILD_TYPE = 'opt-nacl', - BUILD_TYPE_DESCRIPTION = 'NaCl debug build', - ) - nacl_opt_env.Append( - CCFLAGS = ['-O3'], - CPPDEFINES = ['NDEBUG'], - ) - environment_list.append(nacl_opt_env) - # MacOS ------------------------------------------------------------------ mac_env = binaries_env.Clone( @@ -707,47 +567,6 @@ mac_optimized_env = mac_env.Clone( AddMacOptimizedSettings(mac_optimized_env) environment_list.append(mac_optimized_env) -mac_cb_env = mac_env.Clone() - -mac_cb_env.Append( - CPPDEFINES = ['RENDERER_CB'], - BUILD_COMPONENTS = [ - 'command_buffer/common', - 'command_buffer/service', - 'command_buffer/client' - ], - RENDERER_INCLUDE_PATH = [], - RENDERER_LIB_PATH = [ - 'command_buffer/common', - 'command_buffer/service', - 'command_buffer/client', - ], - RENDERER_LIBS = [ - 'o3dCmdBuf_service', - 'o3dCmdBuf_client', - 'o3dCmdBuf_common', - 'MacStaticGLEW' - ] + nacl_htp_all_libs -) - -mac_cb_debug_env = mac_cb_env.Clone( - BUILD_TYPE = 'dbg-mac-cb', - BUILD_TYPE_DESCRIPTION = 'Mac command buffer debug build', - DEBUG = True, - NACL_VARIANT = 'dbg-mac' -) - -AddMacDebugSettings(mac_cb_debug_env) -environment_list.append(mac_cb_debug_env) - -mac_cb_optimized_env = mac_cb_env.Clone( - BUILD_TYPE = 'opt-mac-cb', - BUILD_TYPE_DESCRIPTION = 'Mac Command Buffer optimized build', -) - -AddMacOptimizedSettings(mac_cb_optimized_env) -environment_list.append(mac_cb_optimized_env) - mac_test_optimized_env = mac_optimized_env.Clone( BUILD_TYPE = 'test-opt-mac', BUILD_TYPE_DESCRIPTION = 'MacOS optimized build for testing', @@ -837,55 +656,6 @@ linux_optimized_env.Append( ) environment_list.append(linux_optimized_env) -linux_cb_env = linux_env.Clone() -linux_cb_env.FilterOut(CPPDEFINES = ['RENDERER_GL']) -linux_cb_env.Append( - CPPDEFINES = ['RENDERER_CB'], - BUILD_COMPONENTS = [ - 'command_buffer/common', - 'command_buffer/service', - 'command_buffer/client' - ], - RENDERER_INCLUDE_PATH = [], - RENDERER_LIB_PATH = [ - 'command_buffer/common', - 'command_buffer/service', - 'command_buffer/client', - ], - RENDERER_LIBS = [ - 'o3dCmdBuf_service', - 'o3dCmdBuf_client', - 'o3dCmdBuf_common', - 'GL', - 'GLEW', - 'Cg', - 'CgGL', - ] + linux_cb_env['NACL_HTP_LIBS'], -) - -linux_cb_debug_env = linux_cb_env.Clone( - BUILD_TYPE = 'dbg-linux-cb', - BUILD_TYPE_DESCRIPTION = 'Linux Command Buffer debug build', - DEBUG = True, - NACL_VARIANT = 'dbg-linux', -) -linux_cb_debug_env.Append( - CCFLAGS = ['-g'], -) -environment_list.append(linux_cb_debug_env) - -linux_cb_optimized_env = linux_cb_env.Clone( - BUILD_TYPE = 'opt-linux-cb', - BUILD_TYPE_DESCRIPTION = 'Linux Command Buffer optimized build', - DEBUG = False, - NACL_VARIANT = 'opt-linux', -) -linux_cb_optimized_env.Append( - CCFLAGS = ['-O3'], - CPPDEFINES = ['-DNDEBUG'], -) -environment_list.append(linux_cb_optimized_env) - # Documentation ------------------------------------------------------------- docs_env = base_env.Clone( diff --git a/o3d/plugin/cross/o3d_glue.cc b/o3d/plugin/cross/o3d_glue.cc index d041907..c52e242 100644 --- a/o3d/plugin/cross/o3d_glue.cc +++ b/o3d/plugin/cross/o3d_glue.cc @@ -29,7 +29,6 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #include <build/build_config.h> #ifdef OS_WIN #include <windows.h> @@ -40,12 +39,12 @@ #include <algorithm> #include "core/cross/renderer.h" #include "core/cross/client_info.h" +#include "gpu_plugin/np_utils/np_headers.h" #include "plugin/cross/o3d_glue.h" #include "plugin/cross/config.h" #include "plugin/cross/stream_manager.h" #include "client_glue.h" #include "globals_glue.h" -#include "third_party/nixysa/static_glue/npapi/common.h" #ifdef OS_MACOSX #include "plugin_mac.h" @@ -659,14 +658,15 @@ void PluginObject::Resize(int width, int height) { if (prev_width_ != width || prev_height_ != height) { prev_width_ = width; prev_height_ = height; + if (renderer_ && !fullscreen_) { // Tell the renderer and client that our window has been resized. // If we're in fullscreen mode when this happens, we don't want to pass // the information through; the renderer will pick it up when we switch // back to plugin mode. - renderer_->Resize(width, height); + renderer_->Resize(prev_width_, prev_height_); // This is just so that the client can send an event to the user. - client()->SendResizeEvent(width, height, fullscreen_); + client()->SendResizeEvent(prev_width_, prev_height_, fullscreen_); } } } @@ -721,8 +721,8 @@ void PluginObject::RedirectToFile(const char *url) { NPObject *global_object; NPN_GetValue(npp(), NPNVWindowNPObject, &global_object); NPString string; - string.utf8characters = full_cmd.get(); - string.utf8length = strlen(string.utf8characters); + string.UTF8Characters = full_cmd.get(); + string.UTF8Length = strlen(string.UTF8Characters); NPVariant result; bool temp = NPN_Evaluate(npp(), global_object, &string, &result); if (temp) { diff --git a/o3d/plugin/plugin.gyp b/o3d/plugin/plugin.gyp index 45d3fe2..27248dc 100644 --- a/o3d/plugin/plugin.gyp +++ b/o3d/plugin/plugin.gyp @@ -50,6 +50,7 @@ '../../v8/tools/gyp/v8.gyp:v8', '../core/core.gyp:o3dCore', '../core/core.gyp:o3dCorePlatform', + '../gpu_plugin/gpu_plugin.gyp:np_utils', '../import/archive.gyp:o3dArchive', '../utils/utils.gyp:o3dUtils', '../../native_client/src/shared/imc/imc.gyp:google_nacl_imc', diff --git a/o3d/plugin/win/main_win.cc b/o3d/plugin/win/main_win.cc index 9458819..33561c7 100644 --- a/o3d/plugin/win/main_win.cc +++ b/o3d/plugin/win/main_win.cc @@ -42,6 +42,7 @@ #include "base/at_exit.h" #include "base/command_line.h" #include "base/logging.h" +#include "base/ref_counted.h" #include "core/cross/display_mode.h" #include "core/cross/event.h" #include "plugin/cross/plugin_logging.h" @@ -50,14 +51,32 @@ #include "v8/include/v8.h" #include "breakpad/win/bluescreen_detector.h" +#if defined(RENDERER_CB) +#include "core/cross/command_buffer/renderer_cb.h" +#include "core/cross/command_buffer/display_window_cb.h" +#include "gpu_plugin/command_buffer.h" +#endif + using glue::_o3d::PluginObject; using glue::StreamManager; using o3d::DisplayWindowWindows; using o3d::Event; +#if defined(RENDERER_CB) +using o3d::gpu_plugin::CommandBuffer; +using o3d::gpu_plugin::NPObjectPointer; +#endif + namespace { // The instance handle of the O3D DLL. HINSTANCE g_module_instance; + +// TODO(apatrick): We can have an NPBrowser in the other configurations when we +// move over to gyp. This is just to avoid having to write scons files for +// np_utils. +#if defined(RENDERER_CB) +o3d::gpu_plugin::NPBrowser* g_browser; +#endif } // namespace anonymous #if !defined(O3D_INTERNAL_PLUGIN) @@ -717,6 +736,11 @@ extern "C" { NPError OSCALL NP_Initialize(NPNetscapeFuncs *browserFuncs) { HANDLE_CRASHES; + +#if defined(RENDERER_CB) + g_browser = new o3d::gpu_plugin::NPBrowser(browserFuncs); +#endif + NPError retval = InitializeNPNApi(browserFuncs); if (retval != NPERR_NO_ERROR) return retval; return InitializePlugin(); @@ -755,6 +779,11 @@ NPError OSCALL NP_Shutdown(void) { g_bluescreen_detector = NULL; } +#if defined(RENDERER_CB) + delete g_browser; + g_browser = NULL; +#endif + #endif // O3D_INTERNAL_PLUGIN return NPERR_NO_ERROR; @@ -887,11 +916,26 @@ NPError NPP_SetWindow(NPP instance, NPWindow *window) { ::ShowWindow(content_window, SW_SHOW); // create and assign the graphics context +#if defined(RENDERER_CB) + const unsigned int kDefaultCommandBufferSize = 256 << 10; + NPObjectPointer<CommandBuffer> command_buffer = + RendererCBLocal::CreateCommandBuffer(instance, + obj->GetHWnd(), + kDefaultCommandBufferSize); + + DisplayWindowCB default_display; + default_display.set_npp(instance); + default_display.set_command_buffer(command_buffer); + + obj->CreateRenderer(default_display); + obj->renderer()->Resize(window->width, window->height); + obj->client()->Init(); +#else DisplayWindowWindows default_display; default_display.set_hwnd(obj->GetHWnd()); - obj->CreateRenderer(default_display); obj->client()->Init(); +#endif // we set the timer to 10ms or 100fps. At the time of this comment // the renderer does a vsync the max fps it will run will be the refresh diff --git a/o3d/tests/build.scons b/o3d/tests/build.scons index d26e4bf..7d20e6c 100644 --- a/o3d/tests/build.scons +++ b/o3d/tests/build.scons @@ -279,21 +279,6 @@ if env['TARGET_PLATFORM']=='WINDOWS': ] ) -# add command buffer renderer unit tests only on that renderer platform. -if 'RENDERER_CB' in env['CPPDEFINES']: - tests += [ - 'command_buffer/client/cross/id_allocator_test.cc', - 'command_buffer/common/cross/bitfield_helpers_test.cc', - 'command_buffer/service/cross/effect_utils_test.cc', - 'command_buffer/service/cross/resource_test.cc', - 'command_buffer/client/cross/cmd_buffer_helper_test.cc', - 'command_buffer/client/cross/fenced_allocator_test.cc', - 'command_buffer/client/cross/buffer_sync_proxy_test.cc', - 'command_buffer/service/cross/buffer_rpc_test.cc', - 'command_buffer/service/cross/cmd_buffer_engine_test.cc', - 'command_buffer/service/cross/cmd_parser_test.cc', - ] - unit_tests = env.Program('unit_tests', tests) # After building the test executable, force the windows executable to output diff --git a/o3d/tests/common/cross/main.cc b/o3d/tests/common/cross/main.cc index b8c3fc3..540107d 100644 --- a/o3d/tests/common/cross/main.cc +++ b/o3d/tests/common/cross/main.cc @@ -33,6 +33,7 @@ // defines the common main() for all unit tests #include <build/build_config.h> #include "base/at_exit.h" +#include "base/message_loop.h" #include "gtest/gtest.h" #ifdef OS_WIN @@ -41,6 +42,7 @@ int test_main(int argc, wchar_t **argv) { int test_main(int argc, char **argv) { #endif ::base::AtExitManager at_exit_manager; + MessageLoop message_loop; testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); diff --git a/o3d/tests/common/win/testing_common.cc b/o3d/tests/common/win/testing_common.cc index e498331..0a31823 100644 --- a/o3d/tests/common/win/testing_common.cc +++ b/o3d/tests/common/win/testing_common.cc @@ -29,7 +29,6 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - // Contains windows-specific code for setting up the Client object // used in the unit tests. Defines WinMain and a WindowProc for running // the GUnit tests @@ -49,6 +48,27 @@ #include "core/cross/renderer.h" #include "core/cross/renderer_platform.h" #include "core/cross/types.h" +#include "core/win/display_window_win.h" + +#if defined(RENDERER_CB) +#include "core/cross/command_buffer/renderer_cb.h" +#include "core/cross/command_buffer/display_window_cb.h" +#include "gpu_plugin/command_buffer.h" +#include "gpu_plugin/np_utils/np_browser_stub.h" +#endif + +using o3d::DisplayWindowWindows; + +#if defined(RENDERER_CB) +using o3d::DisplayWindowCB; +using o3d::gpu_plugin::CommandBuffer; +using o3d::gpu_plugin::NPObjectPointer; +using o3d::gpu_plugin::StubNPBrowser; +using o3d::RendererCBLocal; +#endif + +const int kWindowWidth = 512; +const int kWindowHeight = 512; o3d::ServiceLocator* g_service_locator = NULL; o3d::DisplayWindow* g_display_window = NULL; @@ -112,8 +132,8 @@ int WINAPI WinMain(HINSTANCE instance, WS_OVERLAPPEDWINDOW, -1000, 0, - 512, - 512, + kWindowWidth, + kWindowHeight, 0, 0, instance, @@ -153,16 +173,36 @@ int WINAPI WinMain(HINSTANCE instance, o3d::Profiler profiler(g_service_locator); o3d::Features features(g_service_locator); + // TODO(apatrick): We can have an NPBrowser in the other configurations when + // we move over to gyp. This is just to avoid having to write scons files + // for np_utils. +#if defined(RENDERER_CB) + StubNPBrowser browser; +#endif + // create a renderer device based on the current platform g_renderer = o3d::Renderer::CreateDefaultRenderer(g_service_locator); // Initialize the renderer for off-screen rendering if kOffScreenRenderer // is in the environment. bool success; - o3d::DisplayWindowWindows* display_window = - new o3d::DisplayWindowWindows(); - display_window = display_window; + +#if defined(RENDERER_CB) + const unsigned int kDefaultCommandBufferSize = 256 << 10; + + DisplayWindowCB* display_window = new o3d::DisplayWindowCB; + display_window->set_npp(NULL); + display_window->set_command_buffer(RendererCBLocal::CreateCommandBuffer( + NULL, + g_window_handle, + kDefaultCommandBufferSize)); + display_window->set_width(kWindowWidth); + display_window->set_height(kWindowHeight); +#else + DisplayWindowWindows* display_window = new o3d::DisplayWindowWindows; display_window->set_hwnd(g_window_handle); +#endif + g_display_window = display_window; bool offscreen = (::GetEnvironmentVariableW(kOffScreenRenderer, NULL, 0) != 0); diff --git a/o3d/tests/tests.gyp b/o3d/tests/tests.gyp index 92d4fbf..1aef0cc 100644 --- a/o3d/tests/tests.gyp +++ b/o3d/tests/tests.gyp @@ -102,6 +102,16 @@ ], }, ], + ['renderer == "cb"', + { + 'dependencies': [ + '../command_buffer/command_buffer.gyp:command_buffer_client_test', + '../command_buffer/command_buffer.gyp:command_buffer_common_test', + '../command_buffer/command_buffer.gyp:command_buffer_service_test', + '../gpu_plugin/gpu_plugin.gyp:np_utils', + ] + }, + ], ['OS == "mac"', { 'dependencies': [ @@ -226,15 +236,6 @@ ], }, ], - ['cb_service != "none"', - { - 'dependencies' : [ - '../command_buffer/command_buffer.gyp:command_buffer_client_test', - '../command_buffer/command_buffer.gyp:command_buffer_common_test', - '../command_buffer/command_buffer.gyp:command_buffer_service_test', - ], - }, - ], ], }, ], |